{"model_name":"claude-4.5-opus","codes":{"1":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int W = 10000;\nint n;\nvector<int> px, py, rr;\nint a[201], b[201], c[201], d[201];\n\nbool canExpand(int i, int dir) {\n    int na = a[i], nb = b[i], nc = c[i], nd = d[i];\n    if (dir == 0) na--;\n    else if (dir == 1) nc++;\n    else if (dir == 2) nb--;\n    else nd++;\n    \n    if (na < 0 || nc > W || nb < 0 || nd > W) return false;\n    \n    for (int j = 0; j < n; j++) {\n        if (i == j) continue;\n        if (!(nc <= a[j] || c[j] <= na || nd <= b[j] || d[j] <= nb)) return false;\n    }\n    return true;\n}\n\nvoid expand(int i, int dir) {\n    if (dir == 0) a[i]--;\n    else if (dir == 1) c[i]++;\n    else if (dir == 2) b[i]--;\n    else d[i]++;\n}\n\nlong long area(int i) {\n    return (long long)(c[i] - a[i]) * (d[i] - b[i]);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> n;\n    px.resize(n); py.resize(n); rr.resize(n);\n    \n    for (int i = 0; i < n; i++) {\n        cin >> px[i] >> py[i] >> rr[i];\n        a[i] = px[i]; b[i] = py[i]; c[i] = px[i]+1; d[i] = py[i]+1;\n    }\n    \n    auto start = chrono::high_resolution_clock::now();\n    \n    while (true) {\n        auto now = chrono::high_resolution_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > 4.8) break;\n        \n        bool changed = false;\n        \n        vector<int> order(n);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(), [&](int i, int j) {\n            return rr[i] - area(i) > rr[j] - area(j);\n        });\n        \n        for (int i : order) {\n            for (int dir = 0; dir < 4; dir++) {\n                if (canExpand(i, dir)) {\n                    expand(i, dir);\n                    changed = true;\n                }\n            }\n        }\n        \n        if (!changed) break;\n    }\n    \n    // Shrink rectangles that are too big\n    for (int iter = 0; iter < 1000; iter++) {\n        for (int i = 0; i < n; i++) {\n            if (area(i) <= rr[i]) continue;\n            for (int dir = 0; dir < 4; dir++) {\n                int na = a[i], nb = b[i], nc = c[i], nd = d[i];\n                if (dir == 0) na++;\n                else if (dir == 1) nc--;\n                else if (dir == 2) nb++;\n                else nd--;\n                \n                if (na >= nc || nb >= nd) continue;\n                if (!(na <= px[i] && px[i] < nc && nb <= py[i] && py[i] < nd)) continue;\n                \n                long long newArea = (long long)(nc - na) * (nd - nb);\n                if (newArea >= rr[i]) {\n                    a[i] = na; b[i] = nb; c[i] = nc; d[i] = nd;\n                }\n            }\n        }\n    }\n    \n    for (int i = 0; i < n; i++) {\n        cout << a[i] << \" \" << b[i] << \" \" << c[i] << \" \" << d[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dc[] = {'U', 'D', 'L', 'R'};\n\nint t[N][N], p[N][N];\nint si, sj;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> si >> sj;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            cin >> t[i][j];\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            cin >> p[i][j];\n    \n    struct State {\n        int x, y;\n        int score;\n        bitset<2500> usedTiles;\n        string path;\n    };\n    \n    const int BEAM_WIDTH = 400;\n    \n    vector<State> beam;\n    State init;\n    init.x = si;\n    init.y = sj;\n    init.score = p[si][sj];\n    init.usedTiles.set(t[si][sj]);\n    init.path = \"\";\n    beam.push_back(init);\n    \n    string bestPath = \"\";\n    int bestScore = init.score;\n    \n    auto startTime = chrono::steady_clock::now();\n    \n    while (!beam.empty()) {\n        auto now = chrono::steady_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - startTime).count() > 1900) {\n            for (const auto& state : beam) {\n                if (state.score > bestScore) {\n                    bestScore = state.score;\n                    bestPath = state.path;\n                }\n            }\n            break;\n        }\n        \n        vector<State> nextBeam;\n        nextBeam.reserve(beam.size() * 4);\n        \n        for (const auto& state : beam) {\n            bool canExtend = false;\n            for (int d = 0; d < 4; d++) {\n                int nx = state.x + dx[d];\n                int ny = state.y + dy[d];\n                if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                if (state.usedTiles[t[nx][ny]]) continue;\n                \n                canExtend = true;\n                State newState;\n                newState.x = nx;\n                newState.y = ny;\n                newState.score = state.score + p[nx][ny];\n                newState.usedTiles = state.usedTiles;\n                newState.usedTiles.set(t[nx][ny]);\n                newState.path = state.path + dc[d];\n                nextBeam.push_back(move(newState));\n            }\n            \n            if (!canExtend && state.score > bestScore) {\n                bestScore = state.score;\n                bestPath = state.path;\n            }\n        }\n        \n        if (nextBeam.size() > BEAM_WIDTH) {\n            nth_element(nextBeam.begin(), nextBeam.begin() + BEAM_WIDTH, nextBeam.end(),\n                [](const State& a, const State& b) { return a.score > b.score; });\n            nextBeam.resize(BEAM_WIDTH);\n        }\n        \n        beam = move(nextBeam);\n    }\n    \n    cout << bestPath << endl;\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\ndouble h[N][N-1], v[N-1][N];\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    fill(&h[0][0], &h[0][0] + N*(N-1), 5000.0);\n    fill(&v[0][0], &v[0][0] + (N-1)*N, 5000.0);\n    \n    for (int q = 0; q < 1000; q++) {\n        int si, sj, ti, tj;\n        cin >> si >> sj >> ti >> tj;\n        \n        auto idx = [](int i, int j) { return i * N + j; };\n        vector<double> dist(N*N, 1e18);\n        vector<int> prv(N*N, -1);\n        \n        priority_queue<pair<double,int>, vector<pair<double,int>>, greater<>> pq;\n        dist[idx(si, sj)] = 0;\n        pq.push({0, idx(si, sj)});\n        \n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u]) continue;\n            int i = u / N, j = u % N;\n            \n            auto relax = [&](int ni, int nj, double w) {\n                int nu = idx(ni, nj);\n                if (dist[u] + w < dist[nu]) {\n                    dist[nu] = dist[u] + w;\n                    prv[nu] = u;\n                    pq.push({dist[nu], nu});\n                }\n            };\n            \n            if (i > 0) relax(i-1, j, v[i-1][j]);\n            if (i < N-1) relax(i+1, j, v[i][j]);\n            if (j > 0) relax(i, j-1, h[i][j-1]);\n            if (j < N-1) relax(i, j+1, h[i][j]);\n        }\n        \n        string path = \"\";\n        vector<tuple<int, int, int>> edges;\n        \n        int cur = idx(ti, tj);\n        while (prv[cur] != -1) {\n            int ci = cur / N, cj = cur % N;\n            int pi = prv[cur] / N, pj = prv[cur] % N;\n            \n            if (ci < pi) { path += 'U'; edges.emplace_back(1, ci, cj); }\n            else if (ci > pi) { path += 'D'; edges.emplace_back(1, pi, pj); }\n            else if (cj < pj) { path += 'L'; edges.emplace_back(0, ci, cj); }\n            else { path += 'R'; edges.emplace_back(0, pi, pj); }\n            \n            cur = prv[cur];\n        }\n        \n        reverse(path.begin(), path.end());\n        cout << path << \"\\n\" << flush;\n        \n        int feedback;\n        cin >> feedback;\n        \n        double est = 0;\n        for (auto& [t, ei, ej] : edges) {\n            est += (t == 0) ? h[ei][ej] : v[ei][ej];\n        }\n        \n        double ratio = feedback / est;\n        double alpha = 0.2;\n        for (auto& [t, ei, ej] : edges) {\n            double& w = (t == 0) ? h[ei][ej] : v[ei][ej];\n            w *= (1.0 - alpha + alpha * ratio);\n        }\n    }\n    \n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n, m;\n    cin >> n >> m;\n    \n    vector<string> strs(m);\n    for(int i = 0; i < m; i++) cin >> strs[i];\n    \n    vector<int> order(m);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return strs[a].size() > strs[b].size();\n    });\n    \n    char grid[N][N];\n    fill(&grid[0][0], &grid[N][0], '.');\n    \n    // Greedy placement with max overlap preference\n    for(int idx : order) {\n        const string& s = strs[idx];\n        int bestR = -1, bestC, bestD, bestOv = -1;\n        \n        for(int r = 0; r < N; r++) {\n            for(int c = 0; c < N; c++) {\n                for(int d = 0; d < 2; d++) {\n                    bool can = true;\n                    int ov = 0;\n                    for(int p = 0; p < (int)s.size() && can; p++) {\n                        int ni = d ? (r + p) % N : r;\n                        int nj = d ? c : (c + p) % N;\n                        if(grid[ni][nj] != '.' && grid[ni][nj] != s[p]) can = false;\n                        if(grid[ni][nj] != '.') ov++;\n                    }\n                    if(can && ov > bestOv) {\n                        bestOv = ov;\n                        bestR = r; bestC = c; bestD = d;\n                    }\n                }\n            }\n        }\n        \n        if(bestR >= 0) {\n            for(int p = 0; p < (int)s.size(); p++) {\n                int ni = bestD ? (bestR + p) % N : bestR;\n                int nj = bestD ? bestC : (bestC + p) % N;\n                grid[ni][nj] = s[p];\n            }\n        }\n    }\n    \n    // Fill remaining cells randomly\n    mt19937 rng(42);\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(grid[i][j] == '.') grid[i][j] = 'A' + rng() % 8;\n        }\n    }\n    \n    // Count function for SA\n    auto countMatched = [&]() {\n        int cnt = 0;\n        for(const auto& s : strs) {\n            bool found = false;\n            for(int r = 0; r < N && !found; r++) {\n                for(int c = 0; c < N && !found; c++) {\n                    for(int d = 0; d < 2 && !found; d++) {\n                        bool ok = true;\n                        for(int p = 0; p < (int)s.size() && ok; p++) {\n                            int ni = d ? (r + p) % N : r;\n                            int nj = d ? c : (c + p) % N;\n                            if(grid[ni][nj] != s[p]) ok = false;\n                        }\n                        if(ok) found = true;\n                    }\n                }\n            }\n            if(found) cnt++;\n        }\n        return cnt;\n    };\n    \n    // Simple SA to improve\n    char bestGrid[N][N];\n    memcpy(bestGrid, grid, sizeof(grid));\n    int bestScore = countMatched();\n    int curScore = bestScore;\n    \n    auto start = chrono::high_resolution_clock::now();\n    double T = 2.0;\n    \n    while(true) {\n        auto now = chrono::high_resolution_clock::now();\n        if(chrono::duration<double>(now - start).count() > 2.7) break;\n        \n        int i = rng() % N, j = rng() % N;\n        char old = grid[i][j];\n        char newc = 'A' + rng() % 8;\n        if(newc == old) continue;\n        \n        grid[i][j] = newc;\n        int newScore = countMatched();\n        \n        if(newScore >= curScore || (rng() & 0xFFFF) < 65536.0 * exp((newScore - curScore) / T)) {\n            curScore = newScore;\n            if(newScore > bestScore) {\n                bestScore = newScore;\n                memcpy(bestGrid, grid, sizeof(grid));\n            }\n        } else {\n            grid[i][j] = old;\n        }\n        T *= 0.9999;\n    }\n    \n    for(int i = 0; i < N; i++) {\n        cout << string(bestGrid[i], bestGrid[i] + N) << '\\n';\n    }\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, si, sj;\nvector<string> grid;\nvector<vector<bool>> visible;\nint visible_count = 0;\n\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir_char[] = {'U', 'D', 'L', 'R'};\n\ninline bool is_road(int i, int j) {\n    return i >= 0 && i < N && j >= 0 && j < N && grid[i][j] != '#';\n}\n\nvoid mark_visible(int i, int j) {\n    if (!visible[i][j]) { visible[i][j] = true; visible_count++; }\n    for (int jj = j - 1; jj >= 0 && is_road(i, jj); jj--)\n        if (!visible[i][jj]) { visible[i][jj] = true; visible_count++; }\n    for (int jj = j + 1; jj < N && is_road(i, jj); jj++)\n        if (!visible[i][jj]) { visible[i][jj] = true; visible_count++; }\n    for (int ii = i - 1; ii >= 0 && is_road(ii, j); ii--)\n        if (!visible[ii][j]) { visible[ii][j] = true; visible_count++; }\n    for (int ii = i + 1; ii < N && is_road(ii, j); ii++)\n        if (!visible[ii][j]) { visible[ii][j] = true; visible_count++; }\n}\n\nint count_new_visible(int i, int j) {\n    int cnt = !visible[i][j];\n    for (int jj = j - 1; jj >= 0 && is_road(i, jj); jj--) cnt += !visible[i][jj];\n    for (int jj = j + 1; jj < N && is_road(i, jj); jj++) cnt += !visible[i][jj];\n    for (int ii = i - 1; ii >= 0 && is_road(ii, j); ii--) cnt += !visible[ii][j];\n    for (int ii = i + 1; ii < N && is_road(ii, j); ii++) cnt += !visible[ii][j];\n    return cnt;\n}\n\npair<vector<vector<int>>, vector<vector<pair<int,int>>>> dijkstra(int si, int sj) {\n    vector<vector<int>> dist(N, vector<int>(N, INT_MAX));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1,-1}));\n    priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;\n    dist[si][sj] = 0; pq.push({0, si, sj});\n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top(); pq.pop();\n        if (d > dist[i][j]) continue;\n        for (int k = 0; k < 4; k++) {\n            int ni = i + dx[k], nj = j + dy[k];\n            if (is_road(ni, nj)) {\n                int c = grid[ni][nj] - '0';\n                if (dist[i][j] + c < dist[ni][nj]) {\n                    dist[ni][nj] = dist[i][j] + c;\n                    parent[ni][nj] = {i, j};\n                    pq.push({dist[ni][nj], ni, nj});\n                }\n            }\n        }\n    }\n    return {dist, parent};\n}\n\nstring get_path(int i1, int j1, int i2, int j2, vector<vector<pair<int,int>>>& parent) {\n    string path;\n    int ci = i2, cj = j2;\n    while (ci != i1 || cj != j1) {\n        auto [pi, pj] = parent[ci][cj];\n        for (int k = 0; k < 4; k++) if (pi + dx[k] == ci && pj + dy[k] == cj) { path += dir_char[k]; break; }\n        ci = pi; cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(nullptr);\n    cin >> N >> si >> sj;\n    grid.resize(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    \n    int total_roads = 0;\n    for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (is_road(i, j)) total_roads++;\n    \n    visible.assign(N, vector<bool>(N, false));\n    int cur_i = si, cur_j = sj;\n    string result;\n    mark_visible(cur_i, cur_j);\n    \n    while (visible_count < total_roads) {\n        auto [dist, parent] = dijkstra(cur_i, cur_j);\n        int best_i = -1, best_j = -1; double best_score = -1;\n        for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) {\n            if (dist[i][j] == INT_MAX || dist[i][j] == 0) continue;\n            int nv = count_new_visible(i, j);\n            if (nv == 0) continue;\n            double score = (double)nv / dist[i][j];\n            if (score > best_score) { best_score = score; best_i = i; best_j = j; }\n        }\n        if (best_i == -1) break;\n        string path = get_path(cur_i, cur_j, best_i, best_j, parent);\n        result += path;\n        int ti = cur_i, tj = cur_j;\n        for (char c : path) {\n            if (c == 'U') ti--; else if (c == 'D') ti++; else if (c == 'L') tj--; else tj++;\n            mark_visible(ti, tj);\n        }\n        cur_i = best_i; cur_j = best_j;\n    }\n    \n    if (cur_i != si || cur_j != sj) {\n        auto [dist, parent] = dijkstra(cur_i, cur_j);\n        result += get_path(cur_i, cur_j, si, sj, parent);\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    vector<vector<int>> deps(N), rdeps(N);\n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        deps[v].push_back(u);\n        rdeps[u].push_back(v);\n    }\n    \n    vector<int> taskStatus(N, -1), memberStatus(M, -1), memberStartDay(M, 0);\n    vector<vector<double>> skillEst(M, vector<double>(K, 25.0));\n    \n    auto estimateTime = [&](int task, int member) -> double {\n        double w = 0;\n        for (int k = 0; k < K; k++)\n            w += max(0.0, (double)d[task][k] - skillEst[member][k]);\n        return max(1.0, w);\n    };\n    \n    vector<int> urgency(N, 1);\n    for (int i = N - 1; i >= 0; i--)\n        for (int v : rdeps[i])\n            urgency[i] += urgency[v];\n    \n    for (int day = 1; ; day++) {\n        vector<int> availTasks;\n        for (int i = 0; i < N; i++) {\n            if (taskStatus[i] != -1) continue;\n            bool ok = true;\n            for (int dep : deps[i])\n                if (taskStatus[dep] != 1) { ok = false; break; }\n            if (ok) availTasks.push_back(i);\n        }\n        \n        sort(availTasks.begin(), availTasks.end(), [&](int a, int b) {\n            return urgency[a] > urgency[b];\n        });\n        \n        vector<int> freeMembers;\n        for (int j = 0; j < M; j++)\n            if (memberStatus[j] == -1) freeMembers.push_back(j);\n        \n        vector<pair<int, int>> assignments;\n        for (int task : availTasks) {\n            if (freeMembers.empty()) break;\n            int bestIdx = 0;\n            double bestTime = estimateTime(task, freeMembers[0]);\n            for (int i = 1; i < (int)freeMembers.size(); i++) {\n                double t = estimateTime(task, freeMembers[i]);\n                if (t < bestTime) { bestTime = t; bestIdx = i; }\n            }\n            int member = freeMembers[bestIdx];\n            assignments.push_back({member + 1, task + 1});\n            taskStatus[task] = 0;\n            memberStatus[member] = task;\n            memberStartDay[member] = day;\n            freeMembers.erase(freeMembers.begin() + bestIdx);\n        }\n        \n        cout << assignments.size();\n        for (auto& [a, b] : assignments) cout << \" \" << a << \" \" << b;\n        cout << \"\\n\";\n        cout.flush();\n        \n        int n; cin >> n;\n        if (n == -1) break;\n        \n        for (int i = 0; i < n; i++) {\n            int f; cin >> f; f--;\n            int task = memberStatus[f];\n            int timeTaken = day - memberStartDay[f] + 1;\n            taskStatus[task] = 1;\n            memberStatus[f] = -1;\n            \n            if (timeTaken == 1) {\n                for (int k = 0; k < K; k++)\n                    skillEst[f][k] = max(skillEst[f][k], (double)d[task][k]);\n            } else {\n                double currW = 0;\n                for (int k = 0; k < K; k++)\n                    currW += max(0.0, (double)d[task][k] - skillEst[f][k]);\n                if (currW > 0.5) {\n                    double ratio = timeTaken / currW;\n                    for (int k = 0; k < K; k++) {\n                        double gap = d[task][k] - skillEst[f][k];\n                        if (gap > 0) skillEst[f][k] = d[task][k] - gap * ratio;\n                    }\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1000, M = 50, CX = 400, CY = 400;\nint ordA[N], ordB[N], ordC[N], ordD[N];\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\ninline int manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\npair<vector<pair<int,bool>>, int> buildGreedyRoute(const vector<int>& selected) {\n    vector<pair<int, bool>> events;\n    events.reserve(2 * M);\n    vector<bool> picked(N, false), delivered(N, false);\n    int cx = CX, cy = CY, totalCost = 0;\n    \n    for (int i = 0; i < 2 * M; i++) {\n        int best = -1, bestDist = INT_MAX;\n        bool isDelivery = false;\n        \n        for (int idx : selected) {\n            if (!picked[idx]) {\n                int d = manhattan(cx, cy, ordA[idx], ordB[idx]);\n                if (d < bestDist) { bestDist = d; best = idx; isDelivery = false; }\n            } else if (!delivered[idx]) {\n                int d = manhattan(cx, cy, ordC[idx], ordD[idx]);\n                if (d < bestDist) { bestDist = d; best = idx; isDelivery = true; }\n            }\n        }\n        \n        totalCost += bestDist;\n        if (isDelivery) { cx = ordC[best]; cy = ordD[best]; delivered[best] = true; }\n        else { cx = ordA[best]; cy = ordB[best]; picked[best] = true; }\n        events.push_back({best, isDelivery});\n    }\n    totalCost += manhattan(cx, cy, CX, CY);\n    return {events, totalCost};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    auto startTime = chrono::steady_clock::now();\n    for (int i = 0; i < N; i++) cin >> ordA[i] >> ordB[i] >> ordC[i] >> ordD[i];\n    \n    auto elapsed = [&]() {\n        return chrono::duration<double>(chrono::steady_clock::now() - startTime).count();\n    };\n    \n    vector<pair<int, int>> orderedByCenter(N);\n    for (int i = 0; i < N; i++) {\n        int d = manhattan(CX, CY, ordA[i], ordB[i]) + manhattan(CX, CY, ordC[i], ordD[i]);\n        orderedByCenter[i] = {d, i};\n    }\n    sort(orderedByCenter.begin(), orderedByCenter.end());\n    \n    vector<int> selected(M), unselected(N - M);\n    for (int i = 0; i < M; i++) selected[i] = orderedByCenter[i].second;\n    for (int i = 0; i < N - M; i++) unselected[i] = orderedByCenter[M + i].second;\n    \n    auto [bestEvents, bestCost] = buildGreedyRoute(selected);\n    vector<int> bestSelected = selected;\n    int currentCost = bestCost;\n    double temp = 3000.0;\n    \n    while (elapsed() < 1.85) {\n        int selIdx = rng() % M;\n        int unselIdx = rng() % (N - M);\n        \n        swap(selected[selIdx], unselected[unselIdx]);\n        auto [events, cost] = buildGreedyRoute(selected);\n        \n        int delta = cost - currentCost;\n        bool accept = delta < 0 || exp(-delta / temp) > (rng() % 10000) / 10000.0;\n        \n        if (accept) {\n            currentCost = cost;\n            if (cost < bestCost) {\n                bestCost = cost;\n                bestSelected = selected;\n                bestEvents = events;\n            }\n        } else {\n            swap(selected[selIdx], unselected[unselIdx]);\n        }\n        temp *= 0.99995;\n    }\n    \n    cout << M;\n    for (int i = 0; i < M; i++) cout << \" \" << (bestSelected[i] + 1);\n    cout << \"\\n\" << (2 * M + 2) << \" \" << CX << \" \" << CY;\n    for (const auto& [idx, isDel] : bestEvents) {\n        if (isDel) cout << \" \" << ordC[idx] << \" \" << ordD[idx];\n        else cout << \" \" << ordA[idx] << \" \" << ordB[idx];\n    }\n    cout << \" \" << CX << \" \" << CY << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass UnionFind {\n    vector<int> parent, rank_;\npublic:\n    UnionFind(int n) : parent(n), rank_(n, 0) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    int find(int x) {\n        if (parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    bool unite(int x, int y) {\n        int px = find(x), py = find(y);\n        if (px == py) return false;\n        if (rank_[px] < rank_[py]) swap(px, py);\n        parent[py] = px;\n        if (rank_[px] == rank_[py]) rank_[px]++;\n        return true;\n    }\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 400, M = 1995;\n    \n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<int> u(M), v(M), d(M);\n    for (int i = 0; i < M; i++) {\n        cin >> u[i] >> v[i];\n        double dx = x[u[i]] - x[v[i]];\n        double dy = y[u[i]] - y[v[i]];\n        d[i] = (int)round(sqrt(dx * dx + dy * dy));\n    }\n    \n    UnionFind uf(N);\n    int components = N;\n    \n    for (int i = 0; i < M; i++) {\n        int l;\n        cin >> l;\n        \n        int pu = uf.find(u[i]);\n        int pv = uf.find(v[i]);\n        \n        bool already_connected = (pu == pv);\n        double ratio = (double)l / d[i];\n        \n        bool adopt = false;\n        \n        if (!already_connected) {\n            int useful_remaining = 0;\n            int same_pair_remaining = 0;\n            for (int j = i + 1; j < M; j++) {\n                int uj = uf.find(u[j]);\n                int vj = uf.find(v[j]);\n                if (uj != vj) {\n                    useful_remaining++;\n                    if ((uj == pu && vj == pv) || (uj == pv && vj == pu)) {\n                        same_pair_remaining++;\n                    }\n                }\n            }\n            \n            int needed = components - 1;\n            \n            if (useful_remaining < needed * 2) {\n                adopt = true;\n            } else {\n                double k = same_pair_remaining;\n                double expected_min = 1.0 + 2.0 / (k + 2);\n                double threshold = expected_min + 0.2;\n                \n                if (ratio <= threshold || same_pair_remaining == 0) {\n                    adopt = true;\n                }\n            }\n        }\n        \n        if (adopt) {\n            uf.unite(u[i], v[i]);\n            components--;\n        }\n        \n        cout << (adopt ? 1 : 0) << \"\\n\" << flush;\n    }\n    \n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<array<int,3>> pets;\nvector<array<int,2>> humans;\nbool blocked[32][32];\n\nbool pet_at(int x, int y) {\n    for (auto& p : pets) if (p[0] == x && p[1] == y) return true;\n    return false;\n}\n\nbool pet_adjacent(int x, int y) {\n    int dx[] = {0, -1, 1, 0, 0}, dy[] = {0, 0, 0, -1, 1};\n    for (int d = 0; d < 5; d++) if (pet_at(x+dx[d], y+dy[d])) return true;\n    return false;\n}\n\nbool can_place(int x, int y) {\n    if (x < 1 || x > 30 || y < 1 || y > 30 || blocked[x][y]) return false;\n    for (auto& h : humans) if (h[0] == x && h[1] == y) return false;\n    return !pet_adjacent(x, y);\n}\n\nbool passable(int x, int y) {\n    return x >= 1 && x <= 30 && y >= 1 && y <= 30 && !blocked[x][y];\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N; pets.resize(N);\n    for (int i = 0; i < N; i++) cin >> pets[i][0] >> pets[i][1] >> pets[i][2];\n    cin >> M; humans.resize(M);\n    for (int i = 0; i < M; i++) cin >> humans[i][0] >> humans[i][1];\n    \n    set<pair<int,int>> target;\n    for (int i = 1; i <= 30; i++) {\n        for (int c : {7, 14, 21, 28}) {\n            target.insert({i, c});\n            target.insert({c, i});\n        }\n    }\n    \n    int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};\n    char wc[] = {'u', 'd', 'l', 'r'}, mc[] = {'U', 'D', 'L', 'R'};\n    \n    for (int turn = 0; turn < 300; turn++) {\n        string action(M, '.');\n        \n        for (int i = 0; i < M; i++) {\n            int hx = humans[i][0], hy = humans[i][1];\n            int best = -1, bestd = -1;\n            \n            for (int d = 0; d < 4; d++) {\n                int nx = hx + dx[d], ny = hy + dy[d];\n                if (can_place(nx, ny)) {\n                    int sc = target.count({nx, ny}) ? 100 : 1;\n                    if (sc > best) { best = sc; bestd = d; }\n                }\n            }\n            \n            if (bestd >= 0) {\n                action[i] = wc[bestd];\n            } else {\n                int minD = INT_MAX, moveD = -1;\n                for (auto& [tx, ty] : target) {\n                    if (blocked[tx][ty]) continue;\n                    int dist = abs(hx-tx) + abs(hy-ty);\n                    if (dist > 0 && dist < minD) minD = dist;\n                }\n                for (int d = 0; d < 4; d++) {\n                    int nx = hx + dx[d], ny = hy + dy[d];\n                    if (!passable(nx, ny) || pet_at(nx, ny)) continue;\n                    for (auto& [tx, ty] : target) {\n                        if (blocked[tx][ty]) continue;\n                        if (abs(nx-tx) + abs(ny-ty) < minD) {\n                            minD = abs(nx-tx) + abs(ny-ty);\n                            moveD = d;\n                        }\n                    }\n                }\n                if (moveD >= 0) action[i] = mc[moveD];\n            }\n        }\n        \n        cout << action << \"\\n\" << flush;\n        \n        for (int i = 0; i < M; i++) {\n            char a = action[i];\n            for (int d = 0; d < 4; d++) {\n                if (a == wc[d]) blocked[humans[i][0]+dx[d]][humans[i][1]+dy[d]] = true;\n                if (a == mc[d]) { humans[i][0] += dx[d]; humans[i][1] += dy[d]; }\n            }\n        }\n        \n        for (int i = 0; i < N; i++) {\n            string s; cin >> s;\n            for (char c : s) {\n                if (c == 'U') pets[i][0]--;\n                else if (c == 'D') pets[i][0]++;\n                else if (c == 'L') pets[i][1]--;\n                else if (c == 'R') pets[i][1]++;\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N = 20;\nint si, sj, ti, tj;\ndouble p;\nbool hwall[20][19];\nbool vwall[19][20];\n\nbool canMove(int i, int j, char dir) {\n    if (dir == 'U') return i > 0 && !vwall[i-1][j];\n    if (dir == 'D') return i < 19 && !vwall[i][j];\n    if (dir == 'L') return j > 0 && !hwall[i][j-1];\n    if (dir == 'R') return j < 19 && !hwall[i][j];\n    return false;\n}\n\npair<int,int> doMove(int i, int j, char dir) {\n    if (!canMove(i, j, dir)) return {i, j};\n    if (dir == 'U') return {i-1, j};\n    if (dir == 'D') return {i+1, j};\n    if (dir == 'L') return {i, j-1};\n    if (dir == 'R') return {i, j+1};\n    return {i, j};\n}\n\ndouble evaluate(const string& s) {\n    vector<vector<double>> prob(N, vector<double>(N, 0));\n    prob[si][sj] = 1.0;\n    double expectedScore = 0;\n    for (int t = 1; t <= (int)s.size(); t++) {\n        char dir = s[t-1];\n        vector<vector<double>> newProb(N, vector<double>(N, 0));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (prob[i][j] < 1e-15) continue;\n                auto [ni, nj] = doMove(i, j, dir);\n                if (ni == ti && nj == tj) expectedScore += (1-p) * prob[i][j] * (401 - t);\n                else newProb[ni][nj] += (1-p) * prob[i][j];\n                newProb[i][j] += p * prob[i][j];\n            }\n        }\n        prob = newProb;\n    }\n    return expectedScore;\n}\n\nstring bfsWithOrder(vector<char>& order) {\n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1,-1}));\n    vector<vector<char>> fromDir(N, vector<char>(N, ' '));\n    queue<pair<int,int>> q;\n    q.push({si, sj});\n    dist[si][sj] = 0;\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        for (char d : order) {\n            auto [ni, nj] = doMove(i, j, d);\n            if (ni == i && nj == j) continue;\n            if (dist[ni][nj] == -1) {\n                dist[ni][nj] = dist[i][j] + 1;\n                parent[ni][nj] = {i, j};\n                fromDir[ni][nj] = d;\n                q.push({ni, nj});\n            }\n        }\n    }\n    string path;\n    int ci = ti, cj = tj;\n    while (ci != si || cj != sj) {\n        path += fromDir[ci][cj];\n        auto [pi, pj] = parent[ci][cj];\n        ci = pi; cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nmt19937 rng(42);\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    auto startTime = chrono::steady_clock::now();\n    cin >> si >> sj >> ti >> tj >> p;\n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < 19; j++) hwall[i][j] = (s[j] == '1');\n    }\n    for (int i = 0; i < 19; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) vwall[i][j] = (s[j] == '1');\n    }\n    string best;\n    double bestScore = -1;\n    vector<char> order = {'U', 'D', 'L', 'R'};\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - startTime).count() > 1800) break;\n        shuffle(order.begin(), order.end(), rng);\n        string path = bfsWithOrder(order);\n        int pathLen = path.size();\n        for (int rep = 1; rep * pathLen <= 200; rep++) {\n            string result;\n            for (char c : path) for (int i = 0; i < rep; i++) result += c;\n            double score = evaluate(result);\n            if (score > bestScore) { bestScore = score; best = result; }\n        }\n    }\n    cout << best << endl;\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nint tiles[N][N];\nint rotation[N][N];\n\nconst int di[] = {0, -1, 0, 1};\nconst int dj[] = {-1, 0, 1, 0};\n\nconst int to_arr[8][4] = {\n    {1, 0, -1, -1}, {3, -1, -1, 0}, {-1, -1, 3, 2}, {-1, 2, 1, -1},\n    {1, 0, 3, 2}, {3, 2, 1, 0}, {2, -1, 0, -1}, {-1, 3, -1, 1},\n};\n\ninline int getState(int i, int j) {\n    int t = tiles[i][j], r = rotation[i][j];\n    if (t < 4) return (t + r) % 4;\n    if (t < 6) return 4 + (t - 4 + r) % 2;\n    return 6 + (t - 6 + r) % 2;\n}\n\nint traceLoop(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd, length = 0;\n    do {\n        int state = getState(i, j);\n        int d2 = to_arr[state][d];\n        if (d2 == -1) return 0;\n        length++;\n        if (length > 4 * N * N) return 0;\n        i += di[d2]; j += dj[d2];\n        if ((unsigned)i >= N || (unsigned)j >= N) return 0;\n        d = (d2 + 2) % 4;\n    } while (i != si || j != sj || d != sd);\n    return length;\n}\n\npair<int, int> computeTopTwoLoops() {\n    static bool visited[N][N][4];\n    memset(visited, 0, sizeof(visited));\n    int top1 = 0, top2 = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int state = getState(i, j);\n            for (int d = 0; d < 4; d++) {\n                if (to_arr[state][d] == -1 || visited[i][j][d]) continue;\n                int len = traceLoop(i, j, d);\n                if (len > 0) {\n                    if (len > top1) { top2 = top1; top1 = len; }\n                    else if (len > top2) { top2 = len; }\n                    int ci = i, cj = j, cd = d;\n                    do {\n                        visited[ci][cj][cd] = true;\n                        int st = getState(ci, cj);\n                        int d2 = to_arr[st][cd];\n                        ci += di[d2]; cj += dj[d2];\n                        cd = (d2 + 2) % 4;\n                    } while (ci != i || cj != j || cd != d);\n                }\n            }\n        }\n    }\n    return {top1, top2};\n}\n\nint best_rotation[N][N];\nlong long best_score;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = s[j] - '0';\n            rotation[i][j] = 0;\n        }\n    }\n    \n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    \n    auto [l1, l2] = computeTopTwoLoops();\n    best_score = (long long)l1 * l2;\n    memcpy(best_rotation, rotation, sizeof(rotation));\n    long long current_score = best_score;\n    \n    const double TIME_LIMIT = 1.9;\n    \n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start_time).count();\n        if (elapsed > TIME_LIMIT) break;\n        \n        double T = 1000.0 * pow(0.0001, elapsed / TIME_LIMIT);\n        \n        int i = rng() % N, j = rng() % N;\n        int old_rot = rotation[i][j];\n        int new_rot = (old_rot + 1 + rng() % 3) % 4;\n        \n        rotation[i][j] = new_rot;\n        auto [nl1, nl2] = computeTopTwoLoops();\n        long long new_score = (long long)nl1 * nl2;\n        \n        double delta = (double)(new_score - current_score);\n        if (delta >= 0 || uniform_real_distribution<double>(0, 1)(rng) < exp(delta / T)) {\n            current_score = new_score;\n            if (new_score > best_score) {\n                best_score = new_score;\n                memcpy(best_rotation, rotation, sizeof(rotation));\n            }\n        } else {\n            rotation[i][j] = old_rot;\n        }\n    }\n    \n    string result;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            result += ('0' + best_rotation[i][j]);\n    cout << result << endl;\n    \n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dc_char[] = {'U', 'D', 'L', 'R'};\n\nint hexChar(char c) {\n    return (c >= '0' && c <= '9') ? c - '0' : c - 'a' + 10;\n}\n\nint calcScore(const vector<vector<int>>& board) {\n    vector<vector<int>> adj(N * N);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (board[i][j] == 0) continue;\n            if (i + 1 < N && board[i+1][j] != 0 && (board[i][j] & 8) && (board[i+1][j] & 2)) {\n                adj[i*N+j].push_back((i+1)*N+j);\n                adj[(i+1)*N+j].push_back(i*N+j);\n            }\n            if (j + 1 < N && board[i][j+1] != 0 && (board[i][j] & 4) && (board[i][j+1] & 1)) {\n                adj[i*N+j].push_back(i*N+j+1);\n                adj[i*N+j+1].push_back(i*N+j);\n            }\n        }\n    }\n    vector<bool> vis(N * N, false);\n    int maxTree = 0;\n    for (int s = 0; s < N * N; s++) {\n        if (vis[s] || board[s/N][s%N] == 0) continue;\n        int cnt = 0, edges = 0;\n        queue<int> q; q.push(s); vis[s] = true;\n        while (!q.empty()) {\n            int u = q.front(); q.pop(); cnt++;\n            edges += adj[u].size();\n            for (int v : adj[u]) if (!vis[v]) { vis[v] = true; q.push(v); }\n        }\n        if (edges / 2 == cnt - 1) maxTree = max(maxTree, cnt);\n    }\n    return maxTree;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    int er, ec;\n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) {\n            board[i][j] = hexChar(s[j]);\n            if (board[i][j] == 0) { er = i; ec = j; }\n        }\n    }\n    \n    string best, cur;\n    int bestScore = calcScore(board), curScore = bestScore;\n    auto bestBoard = board; int bestEr = er, bestEc = ec;\n    \n    mt19937 rng(42);\n    auto start = chrono::steady_clock::now();\n    \n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count() < 2800) {\n        if (cur.size() >= (size_t)T || bestScore >= N * N - 1) break;\n        \n        vector<int> valid;\n        for (int d = 0; d < 4; d++) {\n            int nr = er + dr[d], nc = ec + dc[d];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N) valid.push_back(d);\n        }\n        int d = valid[rng() % valid.size()];\n        int nr = er + dr[d], nc = ec + dc[d];\n        \n        swap(board[er][ec], board[nr][nc]);\n        cur += dc_char[d];\n        int newScore = calcScore(board);\n        \n        double temp = 1.0 - (double)cur.size() / T;\n        bool accept = newScore > curScore || (rng() % 1000 < 100 * temp);\n        \n        if (accept) {\n            er = nr; ec = nc; curScore = newScore;\n            if (curScore > bestScore || (curScore == bestScore && cur.size() < best.size())) {\n                bestScore = curScore; best = cur;\n                bestBoard = board; bestEr = er; bestEc = ec;\n            }\n        } else {\n            cur.pop_back();\n            swap(board[er][ec], board[nr][nc]);\n        }\n        \n        if (cur.size() > T / 2 && rng() % 100 < 5) {\n            board = bestBoard; er = bestEr; ec = bestEc;\n            cur = best; curScore = bestScore;\n        }\n    }\n    \n    cout << best << endl;\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nint N, K;\nvector<int> a(10);\nvector<pair<ll, ll>> berries;\nvector<array<ll, 4>> cuts;\n\ninline int side(ll x1, ll y1, ll x2, ll y2, ll px, ll py) {\n    __int128 cross = (__int128)(x2 - x1) * (py - y1) - (__int128)(y2 - y1) * (px - x1);\n    if (cross > 0) return 1;\n    if (cross < 0) return -1;\n    return 0;\n}\n\nint calcScore() {\n    unordered_map<uint64_t, int> pieceCount;\n    int numCuts = cuts.size();\n    \n    for (int i = 0; i < N; i++) {\n        uint64_t sig = 0;\n        bool onLine = false;\n        for (int j = 0; j < numCuts; j++) {\n            int s = side(cuts[j][0], cuts[j][1], cuts[j][2], cuts[j][3], \n                        berries[i].first, berries[i].second);\n            if (s == 0) { onLine = true; break; }\n            if (s == 1) sig |= (1ULL << j);\n        }\n        if (!onLine) pieceCount[sig]++;\n    }\n    \n    vector<int> b(11, 0);\n    for (auto& [sig, cnt] : pieceCount) {\n        if (cnt >= 1 && cnt <= 10) b[cnt]++;\n    }\n    \n    int total = 0;\n    for (int d = 1; d <= 10; d++) total += min(a[d-1], b[d]);\n    return total;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> K;\n    for (int i = 0; i < 10; i++) cin >> a[i];\n    \n    berries.resize(N);\n    for (int i = 0; i < N; i++) cin >> berries[i].first >> berries[i].second;\n    \n    mt19937_64 rng(42);\n    \n    auto randLine = [&]() -> array<ll, 4> {\n        ll px = (ll)(rng() % 20001) - 10000;\n        ll py = (ll)(rng() % 20001) - 10000;\n        ll qx = (ll)(rng() % 20001) - 10000;\n        ll qy = (ll)(rng() % 20001) - 10000;\n        while (px == qx && py == qy) { qx = (ll)(rng() % 20001) - 10000; qy = (ll)(rng() % 20001) - 10000; }\n        return {px, py, qx, qy};\n    };\n    \n    auto lineThrough = [&](int i, int j) -> array<ll, 4> {\n        ll dx = berries[j].first - berries[i].first;\n        ll dy = berries[j].second - berries[i].second;\n        ll mx = (berries[i].first + berries[j].first) / 2;\n        ll my = (berries[i].second + berries[j].second) / 2;\n        return {mx - dy, my + dx, mx + dy, my - dx};\n    };\n    \n    int numCuts = min(K, 64);\n    for (int i = 0; i < numCuts; i++) cuts.push_back(randLine());\n    \n    int bestScore = calcScore();\n    auto bestCuts = cuts;\n    \n    auto start = chrono::steady_clock::now();\n    \n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration_cast<chrono::milliseconds>(now - start).count();\n        if (elapsed > 2800) break;\n        \n        double temp = 50.0 * pow(0.01, elapsed / 2800.0);\n        int moveType = rng() % 10;\n        \n        if (moveType < 7 && !cuts.empty()) {\n            int idx = rng() % cuts.size();\n            auto oldCut = cuts[idx];\n            cuts[idx] = (rng() % 2 == 0) ? randLine() : lineThrough(rng() % N, rng() % N);\n            \n            int newScore = calcScore();\n            if (newScore > bestScore || (double)(rng() % 1000000) / 1000000.0 < exp((newScore - bestScore) / temp)) {\n                if (newScore > bestScore) { bestScore = newScore; bestCuts = cuts; }\n            } else cuts[idx] = oldCut;\n        } else if (moveType < 9 && cuts.size() < (size_t)min(K, 64)) {\n            cuts.push_back((rng() % 2 == 0) ? randLine() : lineThrough(rng() % N, rng() % N));\n            int newScore = calcScore();\n            if (newScore > bestScore || (double)(rng() % 1000000) / 1000000.0 < exp((newScore - bestScore) / temp)) {\n                if (newScore > bestScore) { bestScore = newScore; bestCuts = cuts; }\n            } else cuts.pop_back();\n        } else if (cuts.size() > 10) {\n            int idx = rng() % cuts.size();\n            auto oldCut = cuts[idx];\n            cuts.erase(cuts.begin() + idx);\n            int newScore = calcScore();\n            if (newScore > bestScore || (double)(rng() % 1000000) / 1000000.0 < exp((newScore - bestScore) / temp)) {\n                if (newScore > bestScore) { bestScore = newScore; bestCuts = cuts; }\n            } else cuts.insert(cuts.begin() + idx, oldCut);\n        }\n    }\n    \n    cuts = bestCuts;\n    cout << cuts.size() << \"\\n\";\n    for (auto& c : cuts) cout << c[0] << \" \" << c[1] << \" \" << c[2] << \" \" << c[3] << \"\\n\";\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, c;\nset<pair<int,int>> dots;\nset<tuple<int,int,int,int>> usedSegs;\nvector<array<int, 8>> ops;\n\nbool inGrid(int x, int y) { return x >= 0 && x < N && y >= 0 && y < N; }\nlong long wt(int x, int y) { return (long long)(x-c)*(x-c) + (long long)(y-c)*(y-c) + 1; }\n\nvoid addSeg(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g == 0) return;\n    dx /= g; dy /= g;\n    for (int i = 0; i < g; i++) {\n        int a = x1+i*dx, b = y1+i*dy, e = a+dx, f = b+dy;\n        if (a > e || (a == e && b > f)) { swap(a,e); swap(b,f); }\n        usedSegs.insert({a,b,e,f});\n    }\n}\n\nbool segUsed(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g == 0) return false;\n    dx /= g; dy /= g;\n    for (int i = 0; i < g; i++) {\n        int a = x1+i*dx, b = y1+i*dy, e = a+dx, f = b+dy;\n        if (a > e || (a == e && b > f)) { swap(a,e); swap(b,f); }\n        if (usedSegs.count({a,b,e,f})) return true;\n    }\n    return false;\n}\n\nbool dotOnSeg(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g <= 1) return false;\n    dx /= g; dy /= g;\n    for (int i = 1; i < g; i++)\n        if (dots.count({x1+i*dx, y1+i*dy})) return true;\n    return false;\n}\n\nbool tryAdd(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (!inGrid(x1,y1) || !inGrid(x3,y3) || dots.count({x1,y1})) return false;\n    if (!dots.count({x2,y2}) || !dots.count({x3,y3}) || !dots.count({x4,y4})) return false;\n    if ((x2==x3&&y2==y3) || (x2==x4&&y2==y4) || (x3==x4&&y3==y4)) return false;\n    if (x1==x2&&y1==y2) return false;\n    if (dotOnSeg(x1,y1,x2,y2) || dotOnSeg(x2,y2,x3,y3) || dotOnSeg(x3,y3,x4,y4) || dotOnSeg(x4,y4,x1,y1)) return false;\n    if (segUsed(x1,y1,x2,y2) || segUsed(x2,y2,x3,y3) || segUsed(x3,y3,x4,y4) || segUsed(x4,y4,x1,y1)) return false;\n    \n    dots.insert({x1,y1});\n    addSeg(x1,y1,x2,y2); addSeg(x2,y2,x3,y3); addSeg(x3,y3,x4,y4); addSeg(x4,y4,x1,y1);\n    ops.push_back({x1,y1,x2,y2,x3,y3,x4,y4});\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    c = (N-1) / 2;\n    for (int i = 0; i < M; i++) { int x, y; cin >> x >> y; dots.insert({x, y}); }\n    \n    auto tstart = chrono::steady_clock::now();\n    mt19937 rng(42);\n    \n    while (chrono::duration<double>(chrono::steady_clock::now() - tstart).count() < 4.5) {\n        vector<pair<int,int>> dl(dots.begin(), dots.end());\n        shuffle(dl.begin(), dl.end(), rng);\n        \n        long long bestW = -1; array<int,8> best;\n        for (int i = 0; i < (int)dl.size(); i++) {\n            for (int j = 0; j < (int)dl.size(); j++) {\n                if (i == j) continue;\n                auto [x2, y2] = dl[i]; auto [x4, y4] = dl[j];\n                \n                auto check = [&](int x1, int y1, int x3, int y3) {\n                    if (inGrid(x1,y1) && !dots.count({x1,y1}) && wt(x1,y1) > bestW) {\n                        if (inGrid(x3,y3) && dots.count({x3,y3})) {\n                            best = {x1,y1,x2,y2,x3,y3,x4,y4}; bestW = wt(x1,y1);\n                        }\n                    }\n                };\n                \n                check(x4, y2, x2, y4); // axis-aligned\n                \n                int s1 = x2-y2, s2 = x4+y4;\n                if ((s1+s2)%2==0) check((s1+s2)/2, (s2-s1)/2, x2+x4-(s1+s2)/2, y2+y4-(s2-s1)/2);\n                \n                s1 = x2+y2; s2 = x4-y4;\n                if ((s1+s2)%2==0) check((s1+s2)/2, (s1-s2)/2, x2+x4-(s1+s2)/2, y2+y4-(s1-s2)/2);\n            }\n        }\n        if (bestW < 0 || !tryAdd(best[0],best[1],best[2],best[3],best[4],best[5],best[6],best[7])) break;\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto& op : ops) {\n        for (int i = 0; i < 8; i++) cout << op[i] << \" \\n\"[i==7];\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 10;\nint grid[N][N], backup[N][N];\n\nvoid place(int p, int flavor) {\n    int cnt = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] == 0) {\n                if (++cnt == p) { grid[i][j] = flavor; return; }\n            }\n        }\n    }\n}\n\nvoid tilt(char dir) {\n    if (dir == 'F') {\n        for (int j = 0; j < N; j++) {\n            int w = 0;\n            for (int i = 0; i < N; i++) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[w++][j] = v; }\n        }\n    } else if (dir == 'B') {\n        for (int j = 0; j < N; j++) {\n            int w = N - 1;\n            for (int i = N - 1; i >= 0; i--) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[w--][j] = v; }\n        }\n    } else if (dir == 'L') {\n        for (int i = 0; i < N; i++) {\n            int w = 0;\n            for (int j = 0; j < N; j++) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[i][w++] = v; }\n        }\n    } else {\n        for (int i = 0; i < N; i++) {\n            int w = N - 1;\n            for (int j = N - 1; j >= 0; j--) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[i][w--] = v; }\n        }\n    }\n}\n\nlong long calcScore() {\n    bool vis[N][N] = {};\n    long long sum = 0;\n    int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] && !vis[i][j]) {\n                int f = grid[i][j], sz = 0;\n                queue<pair<int,int>> q; q.push({i, j}); vis[i][j] = true;\n                while (!q.empty()) {\n                    auto [x, y] = q.front(); q.pop(); sz++;\n                    for (int d = 0; d < 4; d++) {\n                        int nx = x + dx[d], ny = y + dy[d];\n                        if (nx >= 0 && nx < N && ny >= 0 && ny < N && !vis[nx][ny] && grid[nx][ny] == f) {\n                            vis[nx][ny] = true; q.push({nx, ny});\n                        }\n                    }\n                }\n                sum += (long long)sz * sz;\n            }\n        }\n    }\n    return sum;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int f[101];\n    for (int t = 1; t <= 100; t++) cin >> f[t];\n    \n    memset(grid, 0, sizeof(grid));\n    \n    for (int t = 1; t <= 100; t++) {\n        int p; cin >> p;\n        place(p, f[t]);\n        \n        char bestDir = 'F';\n        long long bestScore = -1;\n        memcpy(backup, grid, sizeof(grid));\n        \n        for (char dir : {'F', 'B', 'L', 'R'}) {\n            memcpy(grid, backup, sizeof(grid));\n            tilt(dir);\n            long long score = calcScore();\n            if (score > bestScore) { bestScore = score; bestDir = dir; }\n        }\n        \n        memcpy(grid, backup, sizeof(grid));\n        tilt(bestDir);\n        cout << bestDir << '\\n' << flush;\n    }\n    \n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\ndouble eps;\n\nvector<int> get_sorted_degrees(const string& s) {\n    vector<int> deg(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 (s[idx++] == '1') {\n                deg[i]++;\n                deg[j]++;\n            }\n        }\n    }\n    sort(deg.begin(), deg.end());\n    return deg;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    cin >> M >> eps;\n    double safe_eps = max(eps, 1e-9);\n    \n    // Choose N based on M and eps\n    // Need enough vertices to distinguish M graphs with noise\n    double factor = 1.0 / max(0.1, 1.0 - 2.0 * safe_eps);\n    N = (int)ceil(sqrt(2.0 * M * factor * 1.5)) + 5;\n    if (eps > 0.25) N += 15;\n    if (eps > 0.35) N += 10;\n    N = max(N, 10);\n    N = min(N, 100);\n    \n    cout << N << \"\\n\";\n    \n    int total = N * (N - 1) / 2;\n    \n    vector<string> G(M);\n    vector<vector<double>> expected_deg(M);\n    \n    for (int i = 0; i < M; i++) {\n        string s(total, '0');\n        // Spread edge count linearly from 0 to total\n        long long edges = (M > 1) ? ((long long)i * total / (M - 1)) : 0;\n        for (int e = 0; e < edges; e++) {\n            s[e] = '1';\n        }\n        G[i] = s;\n        \n        // Compute expected degree sequence after noise transformation\n        vector<int> deg = get_sorted_degrees(s);\n        expected_deg[i].resize(N);\n        for (int j = 0; j < N; j++) {\n            // E[d'] = d*(1-2*eps) + (N-1)*eps\n            expected_deg[i][j] = deg[j] * (1.0 - 2.0 * safe_eps) + (N - 1) * safe_eps;\n        }\n        \n        cout << s << \"\\n\";\n    }\n    cout.flush();\n    \n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n        \n        vector<int> deg_h = get_sorted_degrees(H);\n        \n        int best = 0;\n        double best_score = 1e18;\n        \n        for (int i = 0; i < M; i++) {\n            // L2 distance between observed and expected degree sequences\n            double score = 0;\n            for (int j = 0; j < N; j++) {\n                double diff = deg_h[j] - expected_deg[i][j];\n                score += diff * diff;\n            }\n            if (score < best_score) {\n                best_score = score;\n                best = i;\n            }\n        }\n        \n        cout << best << \"\\n\";\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, D, K;\nvector<array<int,3>> edges;\nvector<vector<pair<int,int>>> adj;\nvector<vector<int>> adjEdge;\nmt19937 rng(42);\nconst long long INF = 1e9;\n\nvector<long long> dijkstra(int src, int excludeEdge) {\n    vector<long long> dist(N, INF);\n    priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> pq;\n    dist[src] = 0;\n    pq.push({0, src});\n    while (!pq.empty()) {\n        auto [d, u] = pq.top(); pq.pop();\n        if (d > dist[u]) continue;\n        for (size_t i = 0; i < adj[u].size(); i++) {\n            if ((int)adjEdge[u][i] == excludeEdge) continue;\n            auto [v, w] = adj[u][i];\n            if (dist[u] + w < dist[v]) {\n                dist[v] = dist[u] + w;\n                pq.push({dist[v], v});\n            }\n        }\n    }\n    return dist;\n}\n\nvector<long long> dijkstraMask(int src, const vector<bool>& excl) {\n    vector<long long> dist(N, INF);\n    priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> pq;\n    dist[src] = 0;\n    pq.push({0, src});\n    while (!pq.empty()) {\n        auto [d, u] = pq.top(); pq.pop();\n        if (d > dist[u]) continue;\n        for (size_t i = 0; i < adj[u].size(); i++) {\n            if (excl[adjEdge[u][i]]) continue;\n            auto [v, w] = adj[u][i];\n            if (dist[u] + w < dist[v]) {\n                dist[v] = dist[u] + w;\n                pq.push({dist[v], v});\n            }\n        }\n    }\n    return dist;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    auto start = chrono::steady_clock::now();\n    \n    cin >> N >> M >> D >> K;\n    edges.resize(M); adj.resize(N); adjEdge.resize(N);\n    \n    for (int i = 0; i < M; i++) {\n        int u, v, w; cin >> u >> v >> w; u--; v--;\n        edges[i] = {u, v, w};\n        adj[u].push_back({v, w}); adj[v].push_back({u, w});\n        adjEdge[u].push_back(i); adjEdge[v].push_back(i);\n    }\n    for (int i = 0; i < N; i++) { int x, y; cin >> x >> y; }\n    \n    vector<long long> crit(M);\n    for (int e = 0; e < M; e++) {\n        auto dist = dijkstra(edges[e][0], e);\n        crit[e] = dist[edges[e][1]] - edges[e][2];\n    }\n    \n    vector<int> order(M); iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) { return crit[a] > crit[b]; });\n    \n    vector<int> assign(M);\n    vector<int> cnt(D + 1, 0);\n    for (int e : order) {\n        int best = 1;\n        for (int d = 2; d <= D; d++) if (cnt[d] < K && cnt[d] < cnt[best]) best = d;\n        assign[e] = best; cnt[best]++;\n    }\n    \n    vector<int> samples(min(40, N));\n    iota(samples.begin(), samples.end(), 0);\n    shuffle(samples.begin(), samples.end(), rng);\n    \n    vector<vector<long long>> origDist(samples.size());\n    for (size_t i = 0; i < samples.size(); i++) origDist[i] = dijkstra(samples[i], -1);\n    \n    auto eval = [&]() {\n        double tot = 0;\n        for (int d = 1; d <= D; d++) {\n            vector<bool> excl(M);\n            for (int e = 0; e < M; e++) if (assign[e] == d) excl[e] = true;\n            for (size_t i = 0; i < samples.size(); i++) {\n                auto dist = dijkstraMask(samples[i], excl);\n                for (int v = 0; v < N; v++) if (v != samples[i])\n                    tot += min(dist[v], INF) - origDist[i][v];\n            }\n        }\n        return tot;\n    };\n    \n    double cur = eval();\n    double temp = 1e8;\n    \n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > 5.5) break;\n        \n        int e1 = rng() % M, e2 = rng() % M;\n        if (assign[e1] == assign[e2]) continue;\n        \n        int d1 = assign[e1], d2 = assign[e2];\n        if (cnt[d1] - 1 + 1 > K || cnt[d2] - 1 + 1 > K) continue;\n        \n        swap(assign[e1], assign[e2]);\n        double nv = eval();\n        \n        if (nv < cur || (rng() % 1000000) < 1000000 * exp((cur - nv) / temp)) {\n            cur = nv;\n        } else {\n            swap(assign[e1], assign[e2]);\n        }\n        temp *= 0.99999;\n    }\n    \n    for (int i = 0; i < M; i++) cout << assign[i] << \" \\n\"[i == M-1];\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nint D;\nstring f[2][15], r[2][15];\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D;\n    for (int i = 0; i < 2; i++) {\n        for (int k = 0; k < D; k++) cin >> f[i][k];\n        for (int k = 0; k < D; k++) cin >> r[i][k];\n    }\n    \n    vector<int> b[2];\n    for (int i = 0; i < 2; i++) b[i].assign(D * D * D, 0);\n    \n    int n = 0;\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    auto valid = [&](int i, int x, int y, int z) {\n        return f[i][z][x] == '1' && r[i][z][y] == '1';\n    };\n    \n    auto idx = [&](int x, int y, int z) { return x * D * D + y * D + z; };\n    \n    // Step 1: Find shared cells (valid in both) and create shared blocks\n    for (int x = 0; x < D; x++) {\n        for (int y = 0; y < D; y++) {\n            for (int z = 0; z < D; z++) {\n                if (valid(0, x, y, z) && valid(1, x, y, z) && b[0][idx(x,y,z)] == 0) {\n                    n++;\n                    queue<tuple<int,int,int>> q;\n                    q.push({x, y, z});\n                    b[0][idx(x,y,z)] = b[1][idx(x,y,z)] = n;\n                    while (!q.empty()) {\n                        auto [cx, cy, cz] = q.front();\n                        q.pop();\n                        for (int d = 0; d < 6; d++) {\n                            int nx = cx + dx[d], ny = cy + dy[d], nz = cz + dz[d];\n                            if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D) {\n                                if (valid(0, nx, ny, nz) && valid(1, nx, ny, nz) && b[0][idx(nx,ny,nz)] == 0) {\n                                    b[0][idx(nx,ny,nz)] = b[1][idx(nx,ny,nz)] = n;\n                                    q.push({nx, ny, nz});\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    // Step 2: Handle remaining cells unique to each arrangement\n    for (int i = 0; i < 2; i++) {\n        for (int x = 0; x < D; x++) {\n            for (int y = 0; y < D; y++) {\n                for (int z = 0; z < D; z++) {\n                    if (valid(i, x, y, z) && b[i][idx(x,y,z)] == 0) {\n                        n++;\n                        queue<tuple<int,int,int>> q;\n                        q.push({x, y, z});\n                        b[i][idx(x,y,z)] = n;\n                        while (!q.empty()) {\n                            auto [cx, cy, cz] = q.front();\n                            q.pop();\n                            for (int d = 0; d < 6; d++) {\n                                int nx = cx + dx[d], ny = cy + dy[d], nz = cz + dz[d];\n                                if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D) {\n                                    if (valid(i, nx, ny, nz) && b[i][idx(nx,ny,nz)] == 0) {\n                                        b[i][idx(nx,ny,nz)] = n;\n                                        q.push({nx, ny, nz});\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    // Output\n    cout << n << \"\\n\";\n    for (int i = 0; i < 2; i++) {\n        for (int j = 0; j < D * D * D; j++) {\n            if (j) cout << \" \";\n            cout << b[i][j];\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, K;\nvector<pair<int,int>> V, R;\nvector<tuple<int,int,long long>> E;\nvector<vector<pair<int,int>>> adj;\nvector<vector<double>> distVR;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    V.resize(N); R.resize(K); E.resize(M); adj.resize(N);\n    \n    for(int i = 0; i < N; i++) cin >> V[i].first >> V[i].second;\n    for(int j = 0; j < M; j++) {\n        int u, v; long long w;\n        cin >> u >> v >> w; u--; v--;\n        E[j] = {u, v, w};\n        adj[u].push_back({v, j});\n        adj[v].push_back({u, j});\n    }\n    for(int k = 0; k < K; k++) cin >> R[k].first >> R[k].second;\n    \n    distVR.resize(N, vector<double>(K));\n    for(int i = 0; i < N; i++)\n        for(int k = 0; k < K; k++) {\n            double dx = V[i].first - R[k].first, dy = V[i].second - R[k].second;\n            distVR[i][k] = sqrt(dx*dx + dy*dy);\n        }\n    \n    // Compute shortest paths from vertex 0\n    vector<long long> dist0(N, LLONG_MAX/2);\n    vector<int> parent(N, -1), parentEdge(N, -1);\n    priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> pq;\n    dist0[0] = 0; pq.push({0, 0});\n    while(!pq.empty()) {\n        auto [d, u] = pq.top(); pq.pop();\n        if(d > dist0[u]) continue;\n        for(auto [v, eid] : adj[u]) {\n            long long w = get<2>(E[eid]);\n            if(dist0[u] + w < dist0[v]) {\n                dist0[v] = dist0[u] + w;\n                parent[v] = u; parentEdge[v] = eid;\n                pq.push({dist0[v], v});\n            }\n        }\n    }\n    \n    // Assign residents considering both broadcast cost and reachability\n    vector<int> P(N, 0);\n    vector<int> assignment(K);\n    \n    for(int k = 0; k < K; k++) {\n        int best = -1; double bestCost = 1e18;\n        for(int i = 0; i < N; i++) {\n            if(distVR[i][k] > 5000) continue;\n            // Cost: broadcast cost + amortized network cost\n            double cost = distVR[i][k] * distVR[i][k] + dist0[i] * 0.01;\n            if(cost < bestCost) { bestCost = cost; best = i; }\n        }\n        assignment[k] = best;\n    }\n    \n    for(int k = 0; k < K; k++) {\n        int v = assignment[k];\n        P[v] = max(P[v], (int)ceil(distVR[v][k] - 1e-9));\n    }\n    \n    // Build tree\n    set<int> active;\n    for(int i = 0; i < N; i++) if(P[i] > 0) active.insert(i);\n    \n    vector<int> B(M, 0);\n    for(int v : active) {\n        int cur = v;\n        while(cur != 0 && parentEdge[cur] != -1) {\n            B[parentEdge[cur]] = 1;\n            cur = parent[cur];\n        }\n    }\n    \n    // Activate intermediate vertices on tree (they're reachable, might help)\n    set<int> treeVerts;\n    treeVerts.insert(0);\n    for(int v : active) {\n        int cur = v;\n        while(cur != -1) { treeVerts.insert(cur); cur = parent[cur]; }\n    }\n    \n    // Try using tree vertices to reduce costs\n    for(int iter = 0; iter < 50; iter++) {\n        bool improved = false;\n        for(int k = 0; k < K; k++) {\n            int curV = assignment[k];\n            for(int v : treeVerts) {\n                if(v == curV || distVR[v][k] > 5000) continue;\n                int newR = (int)ceil(distVR[v][k] - 1e-9);\n                int oldR = (int)ceil(distVR[curV][k] - 1e-9);\n                if(newR < oldR && newR <= 5000) {\n                    assignment[k] = v;\n                    improved = true;\n                }\n            }\n        }\n        if(!improved) break;\n        \n        fill(P.begin(), P.end(), 0);\n        for(int k = 0; k < K; k++) {\n            int v = assignment[k];\n            P[v] = max(P[v], (int)ceil(distVR[v][k] - 1e-9));\n        }\n    }\n    \n    // Output\n    for(int i = 0; i < N; i++) cout << P[i] << \" \\n\"[i==N-1];\n    for(int j = 0; j < M; j++) cout << B[j] << \" \\n\"[j==M-1];\n    \n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nint b[N][N];\nvector<tuple<int, int, int, int>> ops;\n\nvoid do_swap(int x1, int y1, int x2, int y2) {\n    ops.push_back({x1, y1, x2, y2});\n    swap(b[x1][y1], b[x2][y2]);\n}\n\nvoid sift_down(int x, int y) {\n    while (x < N - 1) {\n        // Find the child with minimum value\n        int min_child_y = (b[x + 1][y + 1] < b[x + 1][y]) ? (y + 1) : y;\n        // If parent is larger than min child, swap and continue\n        if (b[x][y] > b[x + 1][min_child_y]) {\n            do_swap(x, y, x + 1, min_child_y);\n            x = x + 1;\n            y = min_child_y;\n        } else {\n            break;\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int x = 0; x < N; x++) {\n        for (int y = 0; y <= x; y++) {\n            cin >> b[x][y];\n        }\n    }\n    \n    // Build min-heap by sifting down from second-to-last tier upward\n    for (int x = N - 2; x >= 0; x--) {\n        for (int y = 0; y <= x; y++) {\n            sift_down(x, y);\n        }\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto& [x1, y1, x2, y2] : ops) {\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, ex, ey;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nvector<vector<int>> grid;\n\nvector<pair<int,int>> getReachable(bool findContainers) {\n    vector<pair<int,int>> result;\n    vector<vector<bool>> vis(D, vector<bool>(D, false));\n    queue<pair<int,int>> q;\n    q.push({ex, ey});\n    vis[ex][ey] = true;\n    \n    while (!q.empty()) {\n        auto [x, y] = q.front(); q.pop();\n        \n        if (findContainers && grid[x][y] >= 0) {\n            result.push_back({x, y});\n            continue;\n        }\n        if (!findContainers && grid[x][y] == -1 && !(x == ex && y == ey)) {\n            result.push_back({x, y});\n        }\n        if (grid[x][y] >= 0) continue;\n        \n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx >= 0 && nx < D && ny >= 0 && ny < D && !vis[nx][ny] && grid[nx][ny] != -2) {\n                vis[nx][ny] = true;\n                q.push({nx, ny});\n            }\n        }\n    }\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D >> N;\n    ex = 0; ey = (D - 1) / 2;\n    grid.assign(D, vector<int>(D, -1));\n    \n    for (int i = 0; i < N; i++) {\n        int x, y; cin >> x >> y;\n        grid[x][y] = -2;\n    }\n    \n    int total = D * D - 1 - N;\n    \n    vector<pair<int,int>> bfsOrder;\n    map<pair<int,int>, int> posToIdx;\n    {\n        vector<vector<bool>> vis(D, vector<bool>(D, false));\n        queue<pair<int,int>> q;\n        q.push({ex, ey});\n        vis[ex][ey] = true;\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            if (grid[x][y] == -1 && !(x == ex && y == ey)) {\n                posToIdx[{x, y}] = bfsOrder.size();\n                bfsOrder.push_back({x, y});\n            }\n            for (int d = 0; d < 4; d++) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !vis[nx][ny] && grid[nx][ny] != -2) {\n                    vis[nx][ny] = true;\n                    q.push({nx, ny});\n                }\n            }\n        }\n    }\n    \n    for (int d = 0; d < total; d++) {\n        int t; cin >> t;\n        auto reach = getReachable(false);\n        \n        int targetIdx = total - 1 - t;\n        pair<int,int> best = reach[0];\n        int bestDist = abs(posToIdx[best] - targetIdx);\n        for (auto& pos : reach) {\n            int dist = abs(posToIdx[pos] - targetIdx);\n            if (dist < bestDist || (dist == bestDist && posToIdx[pos] > posToIdx[best])) {\n                bestDist = dist;\n                best = pos;\n            }\n        }\n        \n        grid[best.first][best.second] = t;\n        cout << best.first << \" \" << best.second << \"\\n\";\n        cout.flush();\n    }\n    \n    for (int i = 0; i < total; i++) {\n        auto reach = getReachable(true);\n        pair<int,int> best = reach[0];\n        for (auto& pos : reach) {\n            if (grid[pos.first][pos.second] < grid[best.first][best.second]) {\n                best = pos;\n            }\n        }\n        cout << best.first << \" \" << best.second << \"\\n\";\n        grid[best.first][best.second] = -1;\n    }\n    \n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint n, m;\nint dx[] = {0, 0, 1, -1};\nint dy[] = {1, -1, 0, 0};\n\nset<pair<int,int>> getAdj(vector<vector<int>>& g) {\n    set<pair<int,int>> adj;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            int c = g[i][j];\n            if (i == 0 || i == n-1 || j == 0 || j == n-1) {\n                int a = min(0, c), b = max(0, c);\n                if (a != b) adj.insert({a, b});\n            }\n            for (int d = 0; d < 4; d++) {\n                int ni = i + dx[d], nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = g[ni][nj];\n                    if (c != nc) {\n                        int a = min(c, nc), b = max(c, nc);\n                        adj.insert({a, b});\n                    }\n                }\n            }\n        }\n    }\n    return adj;\n}\n\nbool isConnected(vector<vector<int>>& g, int c) {\n    if (c == 0) return true;\n    int si = -1, sj = -1, cnt = 0;\n    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) {\n        if (g[i][j] == c) { if (si < 0) { si = i; sj = j; } cnt++; }\n    }\n    if (cnt == 0) return true;\n    queue<pair<int,int>> q;\n    vector<vector<bool>> vis(n, vector<bool>(n, false));\n    q.push({si, sj}); vis[si][sj] = true;\n    int found = 1;\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        for (int d = 0; d < 4; d++) {\n            int ni = i + dx[d], nj = j + dy[d];\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n && !vis[ni][nj] && g[ni][nj] == c) {\n                vis[ni][nj] = true; found++; q.push({ni, nj});\n            }\n        }\n    }\n    return found == cnt;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> n >> m;\n    vector<vector<int>> grid(n, vector<int>(n));\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < n; j++)\n            cin >> grid[i][j];\n    \n    auto origAdj = getAdj(grid);\n    vector<vector<int>> best = grid;\n    int bestScore = 0;\n    \n    // Try greedy shrinking - change cells to 0 when safe\n    auto tryGrid = grid;\n    for (int iter = 0; iter < 5; iter++) {\n        vector<pair<int,int>> cells;\n        for (int i = 0; i < n; i++) for (int j = 0; j < n; j++)\n            if (tryGrid[i][j] != 0) cells.push_back({i, j});\n        \n        shuffle(cells.begin(), cells.end(), mt19937(iter * 12345));\n        \n        for (auto [i, j] : cells) {\n            int old = tryGrid[i][j];\n            tryGrid[i][j] = 0;\n            \n            auto newAdj = getAdj(tryGrid);\n            bool valid = (newAdj == origAdj);\n            if (valid) {\n                for (int c = 1; c <= m && valid; c++)\n                    if (!isConnected(tryGrid, c)) valid = false;\n            }\n            \n            if (!valid) tryGrid[i][j] = old;\n        }\n        \n        int score = 0;\n        for (int i = 0; i < n; i++) for (int j = 0; j < n; j++)\n            if (tryGrid[i][j] == 0) score++;\n        \n        if (score > bestScore) {\n            bestScore = score;\n            best = tryGrid;\n        }\n    }\n    \n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cout << best[i][j];\n            if (j < n-1) cout << \" \";\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, D, Q;\nint query_count = 0;\n\nchar query(const vector<int>& L, const vector<int>& R) {\n    cout << L.size() << \" \" << R.size();\n    for (int x : L) cout << \" \" << x;\n    for (int x : R) cout << \" \" << x;\n    cout << \"\\n\";\n    cout.flush();\n    char c;\n    cin >> c;\n    query_count++;\n    return c;\n}\n\nvector<int> items;\n\nvoid merge_sort(int l, int r) {\n    if (r - l <= 1) return;\n    int m = (l + r) / 2;\n    merge_sort(l, m);\n    merge_sort(m, r);\n    \n    vector<int> left(items.begin() + l, items.begin() + m);\n    vector<int> right(items.begin() + m, items.begin() + r);\n    \n    int i = 0, j = 0, k = l;\n    while (i < (int)left.size() && j < (int)right.size()) {\n        if (query_count >= Q) {\n            while (i < (int)left.size()) items[k++] = left[i++];\n            while (j < (int)right.size()) items[k++] = right[j++];\n            return;\n        }\n        char c = query({left[i]}, {right[j]});\n        if (c != '>') items[k++] = left[i++];\n        else items[k++] = right[j++];\n    }\n    while (i < (int)left.size()) items[k++] = left[i++];\n    while (j < (int)right.size()) items[k++] = right[j++];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> D >> Q;\n    \n    items.resize(N);\n    iota(items.begin(), items.end(), 0);\n    merge_sort(0, N);\n    \n    // Estimate weights using remaining queries\n    vector<double> w(N);\n    for (int i = 0; i < N; i++) w[i] = i + 1;\n    \n    for (int j = N - 1; j >= N / 2 && query_count + 10 < Q; j--) {\n        int lo = 1, hi = j;\n        while (lo < hi && query_count < Q - N) {\n            int mid = (lo + hi) / 2;\n            vector<int> L, R = {items[j]};\n            for (int t = 0; t < mid; t++) L.push_back(items[t]);\n            char c = query(L, R);\n            if (c == '>' || c == '=') hi = mid;\n            else lo = mid + 1;\n        }\n        double sum = 0;\n        for (int t = 0; t < lo; t++) sum += w[t];\n        w[j] = sum;\n    }\n    \n    // Greedy assignment\n    vector<double> set_weight(D, 0);\n    vector<int> assignment(N);\n    \n    for (int i = N - 1; i >= 0; i--) {\n        int best = 0;\n        for (int j = 1; j < D; j++)\n            if (set_weight[j] < set_weight[best]) best = j;\n        assignment[items[i]] = best;\n        set_weight[best] += w[i];\n    }\n    \n    while (query_count < Q) query({items[0]}, {items[1]});\n    \n    for (int i = 0; i < N; i++)\n        cout << assignment[i] << \" \\n\"[i == N - 1];\n    \n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::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    vector<int> pos(n + 1);\n    \n    for (int i = 0; i < m; i++) {\n        int h = n / m;\n        for (int j = 0; j < h; j++) {\n            int x;\n            cin >> x;\n            stacks[i].push_back(x);\n            pos[x] = i;\n        }\n    }\n    \n    vector<pair<int, int>> ops;\n    \n    for (int v = 1; v <= n; v++) {\n        int stack_id = pos[v];\n        \n        int idx = 0;\n        while (stacks[stack_id][idx] != v) idx++;\n        \n        if (idx < (int)stacks[stack_id].size() - 1) {\n            int move_start = idx + 1;\n            int bottom_box = stacks[stack_id][move_start];\n            \n            int max_moving = 0;\n            for (int j = move_start; j < (int)stacks[stack_id].size(); j++) {\n                max_moving = max(max_moving, stacks[stack_id][j]);\n            }\n            \n            int best_dest = -1;\n            int best_score = INT_MIN;\n            \n            for (int i = 0; i < m; i++) {\n                if (i == stack_id) continue;\n                \n                int score = 0;\n                \n                if (stacks[i].empty()) {\n                    score = 400;\n                } else {\n                    int top = stacks[i].back();\n                    score = top;\n                    if (top > max_moving) {\n                        score += 300;\n                    }\n                }\n                \n                score -= (int)stacks[i].size();\n                \n                if (score > best_score) {\n                    best_score = score;\n                    best_dest = i;\n                }\n            }\n            \n            ops.push_back({bottom_box, best_dest + 1});\n            \n            for (int j = move_start; j < (int)stacks[stack_id].size(); j++) {\n                int box = stacks[stack_id][j];\n                stacks[best_dest].push_back(box);\n                pos[box] = best_dest;\n            }\n            stacks[stack_id].resize(move_start);\n        }\n        \n        ops.push_back({v, 0});\n        stacks[stack_id].pop_back();\n    }\n    \n    for (auto& [a, b] : ops) {\n        cout << a << \" \" << b << \"\\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 dirChar[] = {'R', 'D', 'L', 'U'};\n\nbool canMove(int i, int j, int dir) {\n    int ni = i + di[dir];\n    int nj = j + dj[dir];\n    if (ni < 0 || ni >= N || nj < 0 || nj >= N) return false;\n    \n    if (dir == 0) return v[i][j] == '0';\n    else if (dir == 1) return h[i][j] == '0';\n    else if (dir == 2) return j > 0 && v[i][j-1] == '0';\n    else return i > 0 && h[i-1][j] == '0';\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> 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++) {\n        cin >> h[i];\n    }\n    for (int i = 0; i < N; i++) {\n        cin >> v[i];\n    }\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n        }\n    }\n    \n    // Compute subtree sums via BFS from (0,0)\n    vector<vector<long long>> subtreeSum(N, vector<long long>(N, 0));\n    vector<vector<int>> parent(N, vector<int>(N, -1));\n    vector<vector<int>> depth(N, vector<int>(N, -1));\n    \n    queue<pair<int,int>> q;\n    q.push({0, 0});\n    depth[0][0] = 0;\n    vector<pair<int,int>> order;\n    \n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        order.push_back({i, j});\n        subtreeSum[i][j] = d[i][j];\n        for (int dir = 0; dir < 4; dir++) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && depth[ni][nj] == -1 && canMove(i, j, dir)) {\n                depth[ni][nj] = depth[i][j] + 1;\n                parent[ni][nj] = (dir + 2) % 4;\n                q.push({ni, nj});\n            }\n        }\n    }\n    \n    // Compute subtree sums bottom-up\n    for (int idx = order.size() - 1; idx >= 0; idx--) {\n        auto [i, j] = order[idx];\n        if (parent[i][j] != -1) {\n            int pi = i + di[parent[i][j]];\n            int pj = j + dj[parent[i][j]];\n            subtreeSum[pi][pj] += subtreeSum[i][j];\n        }\n    }\n    \n    // DFS with priority based on subtree sums\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    string path;\n    \n    function<void(int, int)> dfs = [&](int i, int j) {\n        visited[i][j] = true;\n        \n        vector<pair<long long,int>> children;\n        for (int dir = 0; dir < 4; dir++) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj] && canMove(i, j, dir)) {\n                children.push_back({subtreeSum[ni][nj], dir});\n            }\n        }\n        // Visit highest subtree sum first (becomes internal node, visited more)\n        sort(children.rbegin(), children.rend());\n        \n        for (auto [sum, dir] : children) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (!visited[ni][nj]) {\n                path += dirChar[dir];\n                dfs(ni, nj);\n                path += dirChar[(dir + 2) % 4];\n            }\n        }\n    };\n    \n    dfs(0, 0);\n    cout << path << endl;\n    \n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nint overlap(const string& a, const string& b) {\n    int maxOv = min((int)a.length(), (int)b.length());\n    for (int ov = maxOv; ov >= 1; ov--) {\n        if (a.substr(a.length() - ov) == b.substr(0, ov)) {\n            return ov;\n        }\n    }\n    return 0;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, si, sj;\n    cin >> N >> M >> si >> sj;\n    \n    vector<string> A(N);\n    map<char, vector<pair<int,int>>> charPos;\n    for (int i = 0; i < N; i++) {\n        cin >> A[i];\n        for (int j = 0; j < N; j++) {\n            charPos[A[i][j]].push_back({i, j});\n        }\n    }\n    \n    vector<string> t(M);\n    for (int i = 0; i < M; i++) {\n        cin >> t[i];\n    }\n    \n    // Greedy superstring construction\n    vector<string> remaining = t;\n    \n    while (remaining.size() > 1) {\n        int bestOv = -1;\n        int bestI = -1, bestJ = -1;\n        \n        for (int i = 0; i < (int)remaining.size(); i++) {\n            for (int j = 0; j < (int)remaining.size(); j++) {\n                if (i != j) {\n                    int ov = overlap(remaining[i], remaining[j]);\n                    if (ov > bestOv) {\n                        bestOv = ov;\n                        bestI = i;\n                        bestJ = j;\n                    }\n                }\n            }\n        }\n        \n        string merged = remaining[bestI] + remaining[bestJ].substr(bestOv);\n        \n        vector<string> newRemaining;\n        for (int k = 0; k < (int)remaining.size(); k++) {\n            if (k != bestI && k != bestJ) {\n                if (merged.find(remaining[k]) == string::npos) {\n                    newRemaining.push_back(remaining[k]);\n                }\n            }\n        }\n        newRemaining.push_back(merged);\n        remaining = newRemaining;\n    }\n    \n    string superstring = remaining[0];\n    \n    // Type the superstring using nearest neighbor\n    int curI = si, curJ = sj;\n    \n    for (char c : superstring) {\n        int bestDist = INT_MAX;\n        int bI = -1, bJ = -1;\n        for (auto [i, j] : charPos[c]) {\n            int dist = abs(i - curI) + abs(j - curJ);\n            if (dist < bestDist) {\n                bestDist = dist;\n                bI = i;\n                bJ = j;\n            }\n        }\n        cout << bI << \" \" << bJ << \"\\n\";\n        curI = bI;\n        curJ = bJ;\n    }\n    \n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\ndouble eps;\nvector<vector<pair<int,int>>> shapes;\nvector<vector<int>> grid;\n\nint queryDrill(int i, int j) {\n    cout << \"q 1 \" << i << \" \" << j << \"\\n\" << flush;\n    int v; cin >> v;\n    grid[i][j] = v;\n    return v;\n}\n\nint queryDivine(const vector<pair<int,int>>& cells) {\n    cout << \"q \" << cells.size();\n    for (auto& [i, j] : cells) cout << \" \" << i << \" \" << j;\n    cout << \"\\n\" << flush;\n    int v; cin >> v;\n    return v;\n}\n\nint submit(const set<pair<int,int>>& oil) {\n    cout << \"a \" << oil.size();\n    for (auto& [i, j] : oil) cout << \" \" << i << \" \" << j;\n    cout << \"\\n\" << flush;\n    int r; cin >> r;\n    return r;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> eps;\n    shapes.resize(M);\n    for (int m = 0; m < M; m++) {\n        int d; cin >> d;\n        shapes[m].resize(d);\n        for (int i = 0; i < d; i++) {\n            cin >> shapes[m][i].first >> shapes[m][i].second;\n        }\n    }\n    \n    grid.assign(N, vector<int>(N, -1));\n    set<pair<int,int>> has_oil;\n    \n    // When eps is small, use row divination first\n    vector<int> rowEstimate(N, -1);\n    if (eps <= 0.1) {\n        for (int i = 0; i < N; i++) {\n            vector<pair<int,int>> row;\n            for (int j = 0; j < N; j++) row.push_back({i, j});\n            int est = queryDivine(row);\n            rowEstimate[i] = est;\n        }\n    }\n    \n    // Drill cells - prioritize rows with higher estimates\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    if (eps <= 0.1) {\n        sort(order.begin(), order.end(), [&](int a, int b) {\n            return rowEstimate[a] > rowEstimate[b];\n        });\n    }\n    \n    for (int i : order) {\n        for (int j = 0; j < N; j++) {\n            int v = queryDrill(i, j);\n            if (v > 0) has_oil.insert({i, j});\n        }\n    }\n    \n    submit(has_oil);\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    for (int d = 0; d < D; d++) {\n        long long total = 0;\n        for (int k = 0; k < N; k++) {\n            total += a[d][k];\n        }\n        if (total == 0) total = 1;\n        \n        vector<int> y(N + 1);\n        y[0] = 0;\n        y[N] = W;\n        \n        long long cum = 0;\n        for (int k = 0; k < N - 1; k++) {\n            cum += a[d][k];\n            y[k + 1] = (int)(cum * W / total);\n            if (y[k + 1] <= y[k]) y[k + 1] = y[k] + 1;\n        }\n        \n        // Ensure validity from the end (each strip must have positive height)\n        for (int k = N - 1; k >= 1; k--) {\n            if (y[k] >= y[k + 1]) y[k] = y[k + 1] - 1;\n        }\n        \n        for (int k = 0; k < N; k++) {\n            cout << y[k] << \" 0 \" << y[k + 1] << \" \" << W << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long P = 998244353;\nint N, M, K;\nvector<vector<long long>> a_init;\nvector<array<array<long long, 3>, 3>> stamps;\n\nlong long eval(const vector<tuple<int,int,int>>& ops) {\n    auto a = a_init;\n    for (auto& [m, p, q] : ops) {\n        for (int i = 0; i < 3; i++)\n            for (int j = 0; j < 3; j++)\n                a[p+i][q+j] = (a[p+i][q+j] + stamps[m][i][j]) % P;\n    }\n    long long score = 0;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            score += a[i][j];\n    return score;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    cin >> N >> M >> K;\n    a_init.assign(N, vector<long long>(N));\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            cin >> a_init[i][j];\n            a_init[i][j] %= P;\n        }\n    \n    stamps.resize(M);\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    vector<tuple<int,int,int>> best_ops;\n    auto a = a_init;\n    for (int op = 0; op < K; op++) {\n        long long best_gain = 0;\n        int bm = -1, bp = -1, bq = -1;\n        for (int m = 0; m < M; m++)\n            for (int p = 0; p <= N-3; p++)\n                for (int q = 0; q <= N-3; q++) {\n                    long long gain = 0;\n                    for (int i = 0; i < 3; i++)\n                        for (int j = 0; j < 3; j++)\n                            gain += (a[p+i][q+j] + stamps[m][i][j]) % P - a[p+i][q+j];\n                    if (gain > best_gain) { best_gain = gain; bm = m; bp = p; bq = q; }\n                }\n        if (bm == -1) break;\n        for (int i = 0; i < 3; i++)\n            for (int j = 0; j < 3; j++)\n                a[bp+i][bq+j] = (a[bp+i][bq+j] + stamps[bm][i][j]) % P;\n        best_ops.push_back({bm, bp, bq});\n    }\n    \n    long long best_score = eval(best_ops);\n    mt19937 rng(42);\n    auto cur_ops = best_ops;\n    long long cur_score = best_score;\n    \n    auto start = chrono::steady_clock::now();\n    while (chrono::duration<double>(chrono::steady_clock::now() - start).count() < 1.9) {\n        double t = 1.0 - chrono::duration<double>(chrono::steady_clock::now() - start).count() / 1.9;\n        double temp = t * t * 5e7;\n        \n        auto new_ops = cur_ops;\n        int act = rng() % 3;\n        if (act == 0 && !new_ops.empty()) {\n            new_ops.erase(new_ops.begin() + rng() % new_ops.size());\n        } else if (act == 1 && new_ops.size() < (size_t)K) {\n            new_ops.push_back({(int)(rng()%M), (int)(rng()%(N-2)), (int)(rng()%(N-2))});\n        } else if (!new_ops.empty()) {\n            int idx = rng() % new_ops.size();\n            new_ops[idx] = {(int)(rng()%M), (int)(rng()%(N-2)), (int)(rng()%(N-2))};\n        }\n        \n        long long new_score = eval(new_ops);\n        if (new_score > cur_score || (temp > 0 && exp((new_score-cur_score)/temp) > (rng()%1000000)/1e6)) {\n            cur_ops = new_ops;\n            cur_score = new_score;\n            if (cur_score > best_score) { best_score = cur_score; best_ops = cur_ops; }\n        }\n    }\n    \n    cout << best_ops.size() << \"\\n\";\n    for (auto& [m,p,q] : best_ops) cout << m << \" \" << p << \" \" << q << \"\\n\";\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 5;\nint A[N][N];\nint grid[N][N];\nint cr[N], cc[N], hold[N];\nint next_in[N];\nstring ans[N];\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n; cin >> n;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            cin >> A[i][j];\n    \n    memset(grid, -1, sizeof(grid));\n    memset(hold, -1, sizeof(hold));\n    memset(next_in, 0, sizeof(next_in));\n    for (int i = 0; i < N; i++) { cr[i] = i; cc[i] = 0; }\n    \n    for (int t = 0; t < 5000; t++) {\n        // Step 1: Bring in 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 c = 0; c < N; c++)\n                    if (cr[c] == i && cc[c] == 0 && hold[c] != -1)\n                        blocked = true;\n                if (!blocked) grid[i][0] = A[i][next_in[i]++];\n            }\n        }\n        \n        // Decide moves\n        char moves[N];\n        for (int c = 0; c < N; c++) moves[c] = '.';\n        \n        for (int c = 0; c < N; c++) {\n            int r = cr[c], col = cc[c];\n            \n            if (hold[c] == -1) {\n                if (grid[r][col] != -1) {\n                    moves[c] = 'P';\n                } else if (col > 0) {\n                    moves[c] = 'L';\n                }\n            } else {\n                int target_row = hold[c] / N;\n                if (col < N-1) {\n                    bool can_move = (c == 0 || grid[r][col+1] == -1);\n                    if (can_move) moves[c] = 'R';\n                } else {\n                    moves[c] = 'Q';\n                }\n            }\n        }\n        \n        // Step 2: Execute moves\n        for (int c = 0; c < N; c++) {\n            char m = moves[c];\n            if (m == 'P') {\n                hold[c] = grid[cr[c]][cc[c]];\n                grid[cr[c]][cc[c]] = -1;\n            } else if (m == 'Q') {\n                grid[cr[c]][cc[c]] = hold[c];\n                hold[c] = -1;\n            } else if (m == 'R') cc[c]++;\n            else if (m == 'L') cc[c]--;\n            else if (m == 'U') cr[c]--;\n            else if (m == 'D') cr[c]++;\n        }\n        \n        // Step 3: Dispatch\n        for (int i = 0; i < N; i++) grid[i][N-1] = -1;\n        \n        for (int c = 0; c < N; c++) ans[c] += moves[c];\n        \n        // Check if done\n        bool done = true;\n        for (int i = 0; i < N; i++) if (next_in[i] < N) done = false;\n        for (int c = 0; c < N; c++) if (hold[c] != -1) done = false;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] != -1) done = false;\n        if (done) break;\n    }\n    \n    // Trim trailing dots\n    size_t maxlen = 0;\n    for (int i = 0; i < N; i++) maxlen = max(maxlen, ans[i].size());\n    \n    while (maxlen > 1) {\n        bool all_dot = true;\n        for (int i = 0; i < N; i++) {\n            if (ans[i].size() >= maxlen && ans[i][maxlen-1] != '.') all_dot = false;\n        }\n        if (!all_dot) break;\n        maxlen--;\n        for (int i = 0; i < N; i++)\n            if (ans[i].size() > maxlen) ans[i].resize(maxlen);\n    }\n    \n    for (int i = 0; i < N; i++) cout << ans[i] << \"\\n\";\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<vector<int>> h;\nvector<string> ops;\nint cx = 0, cy = 0;\nint load = 0;\n\nvoid move_one(char dir) {\n    ops.push_back(string(1, dir));\n    if (dir == 'U') cx--;\n    else if (dir == 'D') cx++;\n    else if (dir == 'L') cy--;\n    else if (dir == 'R') cy++;\n}\n\nvoid move_to(int tx, int ty) {\n    while (cx < tx) move_one('D');\n    while (cx > tx) move_one('U');\n    while (cy < ty) move_one('R');\n    while (cy > ty) move_one('L');\n}\n\nvoid do_load(int d) {\n    if (d <= 0) return;\n    ops.push_back(\"+\" + to_string(d));\n    load += d;\n    h[cx][cy] -= d;\n}\n\nvoid do_unload(int d) {\n    if (d <= 0) return;\n    ops.push_back(\"-\" + to_string(d));\n    load -= d;\n    h[cx][cy] += d;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    h.resize(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    while (true) {\n        int si = -1, sj = -1, best_dist = INT_MAX;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (h[i][j] > 0) {\n                    int dist = abs(i - cx) + abs(j - cy);\n                    if (dist < best_dist) {\n                        best_dist = dist;\n                        si = i;\n                        sj = j;\n                    }\n                }\n            }\n        }\n        \n        if (si == -1) break;\n        \n        move_to(si, sj);\n        do_load(h[cx][cy]);\n        \n        while (load > 0) {\n            int ti = -1, tj = -1;\n            best_dist = INT_MAX;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h[i][j] < 0) {\n                        int dist = abs(i - cx) + abs(j - cy);\n                        if (dist < best_dist) {\n                            best_dist = dist;\n                            ti = i;\n                            tj = j;\n                        }\n                    }\n                }\n            }\n            \n            if (ti == -1) break;\n            \n            move_to(ti, tj);\n            do_unload(min(load, -h[cx][cy]));\n        }\n    }\n    \n    for (const auto& op : ops) {\n        cout << op << \"\\n\";\n    }\n    \n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \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, 0));\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    for (int t = 0; t < T; t++) {\n        // Find max value for each criterion\n        vector<int> maxVal(M, -1);\n        for (int l = 0; l < M; l++) {\n            for (int i = 0; i < seed_count; i++) {\n                maxVal[l] = max(maxVal[l], X[i][l]);\n            }\n        }\n        \n        // Calculate score for each seed (bonus for having max values)\n        vector<pair<double, int>> seed_scores(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            double score = 0;\n            for (int l = 0; l < M; l++) {\n                if (X[i][l] == maxVal[l]) {\n                    score += 1000;\n                }\n                score += X[i][l];\n            }\n            seed_scores[i] = {score, i};\n        }\n        \n        sort(seed_scores.begin(), seed_scores.end(), greater<pair<double, int>>());\n        \n        vector<int> selected(N * N);\n        for (int i = 0; i < N * N; i++) {\n            selected[i] = seed_scores[i].second;\n        }\n        \n        auto getValue = [&](int idx) {\n            int total = 0;\n            for (int l = 0; l < M; l++) total += X[idx][l];\n            return total;\n        };\n        \n        sort(selected.begin(), selected.end(), [&](int a, int b) {\n            return getValue(a) > getValue(b);\n        });\n        \n        vector<pair<int, int>> pos_order;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                pos_order.push_back({i, j});\n            }\n        }\n        \n        double cx = (N - 1) / 2.0;\n        double cy = (N - 1) / 2.0;\n        sort(pos_order.begin(), pos_order.end(), [&](auto& a, auto& b) {\n            double da = abs(a.first - cx) + abs(a.second - cy);\n            double db = abs(b.first - cx) + abs(b.second - cy);\n            if (da != db) return da < db;\n            if (a.first != b.first) return a.first < b.first;\n            return a.second < b.second;\n        });\n        \n        vector<vector<int>> A(N, vector<int>(N, -1));\n        for (int i = 0; i < N * N; i++) {\n            A[pos_order[i].first][pos_order[i].second] = selected[i];\n        }\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << A[i][j];\n                if (j < N - 1) cout << \" \";\n                else cout << \"\\n\";\n            }\n        }\n        cout.flush();\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\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, V;\nint rx, ry, dir; // root pos and fingertip direction (0=R,1=D,2=L,3=U)\nconst int DX[] = {0, 1, 0, -1};\nconst int DY[] = {1, 0, -1, 0};\n\npair<int,int> fingertip() { return {rx + DX[dir], ry + DY[dir]}; }\nbool valid(int x, int y) { return x >= 0 && x < N && y >= 0 && y < N; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> V;\n    vector<string> grid(N), target(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    for (int i = 0; i < N; i++) cin >> target[i];\n    \n    cout << \"2\\n0 1\\n0 0\\n\";\n    rx = ry = dir = 0;\n    \n    set<pair<int,int>> pickup, drop;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] == '1' && target[i][j] == '0') pickup.insert({i, j});\n            if (target[i][j] == '1' && grid[i][j] == '0') drop.insert({i, j});\n        }\n    \n    vector<string> ops;\n    bool holding = false;\n    \n    auto output = [&](char m, char r, char a) {\n        string s; s += m; s += r; s += '.'; s += a;\n        ops.push_back(s);\n    };\n    \n    auto navigate = [&](set<pair<int,int>>& targets, bool is_pickup) {\n        while (!targets.empty() && ops.size() < 95000) {\n            auto [fx, fy] = fingertip();\n            if (valid(fx, fy) && targets.count({fx, fy})) {\n                output('.', '.', 'P');\n                targets.erase({fx, fy});\n                return true;\n            }\n            \n            pair<int,int> best; int best_d = INT_MAX;\n            for (auto& p : targets) {\n                int d = abs(p.first - fx) + abs(p.second - fy);\n                if (d < best_d) { best_d = d; best = p; }\n            }\n            \n            int tx = best.first, ty = best.second;\n            int dx = tx - rx, dy = ty - ry;\n            char m = '.', r = '.';\n            \n            if (abs(dx) + abs(dy) == 1) {\n                int want = (dx == 0 && dy == 1) ? 0 : (dx == 1 && dy == 0) ? 1 : \n                           (dx == 0 && dy == -1) ? 2 : 3;\n                if (want != dir) {\n                    r = ((dir + 1) % 4 == want) ? 'R' : 'L';\n                    dir = (r == 'R') ? (dir + 1) % 4 : (dir + 3) % 4;\n                }\n            } else {\n                auto [fx2, fy2] = fingertip();\n                if (fx2 < tx && valid(rx + 1, ry)) { m = 'D'; rx++; }\n                else if (fx2 > tx && valid(rx - 1, ry)) { m = 'U'; rx--; }\n                else if (fy2 < ty && valid(rx, ry + 1)) { m = 'R'; ry++; }\n                else if (fy2 > ty && valid(rx, ry - 1)) { m = 'L'; ry--; }\n                else {\n                    // Need to reposition - just try any valid move\n                    if (valid(rx + 1, ry)) { m = 'D'; rx++; }\n                    else if (valid(rx - 1, ry)) { m = 'U'; rx--; }\n                    else if (valid(rx, ry + 1)) { m = 'R'; ry++; }\n                    else if (valid(rx, ry - 1)) { m = 'L'; ry--; }\n                }\n            }\n            output(m, r, '.');\n        }\n        return false;\n    };\n    \n    while (ops.size() < 95000) {\n        if (!holding) {\n            if (pickup.empty()) break;\n            if (navigate(pickup, true)) holding = true;\n            else break;\n        } else {\n            if (drop.empty()) break;\n            if (navigate(drop, false)) holding = false;\n            else break;\n        }\n    }\n    \n    for (auto& op : ops) cout << op << \"\\n\";\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::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    for (int i = 0; i < N; i++)\n        cin >> sardine[i].first >> sardine[i].second;\n    \n    vector<int> xs, ys;\n    for (auto& p : mackerel) { xs.push_back(p.first); ys.push_back(p.second); }\n    for (auto& p : sardine) { xs.push_back(p.first); ys.push_back(p.second); }\n    \n    sort(xs.begin(), xs.end()); xs.erase(unique(xs.begin(), xs.end()), xs.end());\n    sort(ys.begin(), ys.end()); ys.erase(unique(ys.begin(), ys.end()), ys.end());\n    \n    int nx = xs.size(), ny = ys.size();\n    map<int, int> x_idx, y_idx;\n    for (int i = 0; i < nx; i++) x_idx[xs[i]] = i;\n    for (int i = 0; i < ny; i++) y_idx[ys[i]] = i;\n    \n    vector<vector<pair<int, int>>> points_by_y(ny);\n    for (auto& p : mackerel)\n        points_by_y[y_idx[p.second]].emplace_back(x_idx[p.first], 1);\n    for (auto& p : sardine)\n        points_by_y[y_idx[p.second]].emplace_back(x_idx[p.first], -1);\n    \n    int best_score = 0;\n    int best_x1i = 0, best_y1i = 0, best_x2i = 0, best_y2i = 0;\n    \n    int y_step = max(1, ny / 80);\n    \n    for (int y1 = 0; y1 < ny; y1 += y_step) {\n        vector<int> col_sum(nx, 0);\n        \n        for (int y2 = y1; y2 < ny; y2++) {\n            for (auto& [xi, val] : points_by_y[y2])\n                col_sum[xi] += val;\n            \n            int cur_sum = 0, max_sum = 0;\n            int cur_start = 0, best_start = 0, best_end = 0;\n            for (int x = 0; x < nx; x++) {\n                cur_sum += col_sum[x];\n                if (cur_sum > max_sum) {\n                    max_sum = cur_sum;\n                    best_start = cur_start;\n                    best_end = x;\n                }\n                if (cur_sum < 0) {\n                    cur_sum = 0;\n                    cur_start = x + 1;\n                }\n            }\n            \n            if (max_sum > best_score) {\n                best_score = max_sum;\n                best_x1i = best_start;\n                best_x2i = best_end;\n                best_y1i = y1;\n                best_y2i = y2;\n            }\n        }\n    }\n    \n    int best_x1 = best_x1i < nx ? xs[best_x1i] : 0;\n    int best_x2 = best_x2i < nx ? xs[best_x2i] : 1;\n    int best_y1 = best_y1i < ny ? ys[best_y1i] : 0;\n    int best_y2 = best_y2i < ny ? ys[best_y2i] : 1;\n    \n    if (best_score == 0) {\n        best_x1 = 0; best_y1 = 0;\n        best_x2 = 1; best_y2 = 1;\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\nint N, T;\nlong long sigma;\nvector<long long> w, h;\n\nstruct PlacedRect { long long x1, y1, x2, y2; int id; };\n\ntuple<long long, long long> simulate(const vector<tuple<int,int,char,int>>& ops) {\n    vector<PlacedRect> placed;\n    long long W = 0, H = 0;\n    for (auto& [p, r, d, b] : ops) {\n        long long rw = w[p], rh = h[p];\n        if (r) swap(rw, rh);\n        long long x = 0, y = 0;\n        if (d == 'U') {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n            for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n        } else {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n            for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n        }\n        placed.push_back({x, y, x + rw, y + rh, p});\n        W = max(W, x + rw); H = max(H, y + rh);\n    }\n    return {W, H};\n}\n\nmt19937 rng(42);\n\nvector<tuple<int,int,char,int>> genGreedy() {\n    vector<tuple<int,int,char,int>> ops;\n    vector<PlacedRect> placed;\n    long long curW = 0, curH = 0;\n    for (int i = 0; i < N; i++) {\n        long long best = LLONG_MAX; tuple<int,char,int> bc = {0,'U',-1};\n        for (int r = 0; r < 2; r++) for (char d : {'U','L'}) for (int b = -1; b < i; b++) {\n            long long rw = w[i], rh = h[i]; if (r) swap(rw, rh);\n            long long x = 0, y = 0;\n            if (d == 'U') {\n                if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n                for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n            } else {\n                if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n                for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n            }\n            long long sc = max(curW, x+rw) + max(curH, y+rh);\n            if (sc < best) { best = sc; bc = {r, d, b}; }\n        }\n        auto [r, d, b] = bc;\n        long long rw = w[i], rh = h[i]; if (r) swap(rw, rh);\n        long long x = 0, y = 0;\n        if (d == 'U') {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n            for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n        } else {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n            for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n        }\n        placed.push_back({x, y, x+rw, y+rh, i}); curW = max(curW, x+rw); curH = max(curH, y+rh);\n        ops.push_back({i, r, d, b});\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> mutate(vector<tuple<int,int,char,int>> ops) {\n    for (int i = 0; i < N; i++) if (rng() % 4 == 0) {\n        auto& [p, r, d, b] = ops[i];\n        int choice = rng() % 3;\n        if (choice == 0) r = 1 - r;\n        else if (choice == 1) d = (d == 'U') ? 'L' : 'U';\n        else if (i > 0) b = (int)(rng() % (i + 1)) - 1;\n    }\n    return ops;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> T >> sigma;\n    w.resize(N); h.resize(N);\n    for (int i = 0; i < N; i++) cin >> w[i] >> h[i];\n    \n    auto bestOps = genGreedy();\n    auto [bw, bh] = simulate(bestOps);\n    long long bestSim = bw + bh;\n    \n    vector<vector<tuple<int,int,char,int>>> candidates;\n    candidates.push_back(bestOps);\n    \n    for (int iter = 0; iter < 5000 && (int)candidates.size() < T; iter++) {\n        auto ops = mutate(bestOps);\n        auto [sw, sh] = simulate(ops);\n        if (sw + sh < bestSim * 1.1) {\n            candidates.push_back(ops);\n            if (sw + sh < bestSim) { bestSim = sw + sh; bestOps = ops; }\n        }\n    }\n    \n    while ((int)candidates.size() < T) candidates.push_back(mutate(bestOps));\n    \n    for (int t = 0; t < T; t++) {\n        auto& ops = candidates[t % candidates.size()];\n        cout << ops.size() << \"\\n\";\n        for (auto& [p, r, d, b] : ops) cout << p << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        cout.flush();\n        long long W, H; 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<int> parent_arr;\nvector<int> depth_arr;\n\nvoid dfs(int u) {\n    // Sort neighbors by descending beauty - visit high beauty first to place them deep\n    vector<pair<int, int>> neighbors;\n    for (int v : adj[u]) {\n        if (depth_arr[v] == -1) {\n            neighbors.push_back({-A[v], v}); // negative for descending sort\n        }\n    }\n    sort(neighbors.begin(), neighbors.end());\n    \n    for (auto& [neg_beauty, v] : neighbors) {\n        if (depth_arr[v] == -1 && depth_arr[u] < H) {\n            parent_arr[v] = u;\n            depth_arr[v] = depth_arr[u] + 1;\n            dfs(v);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> H;\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    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    parent_arr.resize(N, -1);\n    depth_arr.resize(N, -1);\n    \n    // Sort vertices by ascending beauty - low beauty vertices become roots first\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return A[a] < A[b];\n    });\n    \n    // Build trees using DFS from low-beauty roots\n    for (int start : order) {\n        if (depth_arr[start] != -1) continue;\n        \n        depth_arr[start] = 0;\n        parent_arr[start] = -1;\n        dfs(start);\n    }\n    \n    // Output\n    for (int i = 0; i < N; i++) {\n        cout << parent_arr[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<string> board;\nvector<pair<char,int>> ops;\n\nvoid L(int r) { ops.push_back({'L', r}); for (int j = 0; j < N-1; j++) board[r][j] = board[r][j+1]; board[r][N-1] = '.'; }\nvoid R(int r) { ops.push_back({'R', r}); for (int j = N-1; j > 0; j--) board[r][j] = board[r][j-1]; board[r][0] = '.'; }\nvoid U(int c) { ops.push_back({'U', c}); for (int i = 0; i < N-1; i++) board[i][c] = board[i+1][c]; board[N-1][c] = '.'; }\nvoid D(int c) { ops.push_back({'D', c}); for (int i = N-1; i > 0; i--) board[i][c] = board[i-1][c]; board[0][c] = '.'; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    board.resize(N);\n    for (int i = 0; i < N; i++) cin >> board[i];\n    \n    auto count_oni = [&]() {\n        int c = 0;\n        for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (board[i][j] == 'x') c++;\n        return c;\n    };\n    \n    while (count_oni() > 0) {\n        double best_ratio = 1e18;\n        int best_type = -1, best_idx = -1, best_dist = -1;\n        \n        auto consider = [&](int type, int idx, int dist, int cnt) {\n            if (cnt == 0) return;\n            double ratio = (double)(2 * dist) / cnt;\n            if (ratio < best_ratio) { best_ratio = ratio; best_type = type; best_idx = idx; best_dist = dist; }\n        };\n        \n        for (int j = 0; j < N; j++) {\n            int first_fuku = N;\n            for (int i = 0; i < N; i++) if (board[i][j] == 'o') { first_fuku = i; break; }\n            int last_oni = -1, cnt = 0;\n            for (int i = 0; i < first_fuku; i++) if (board[i][j] == 'x') { last_oni = i; cnt++; }\n            if (cnt > 0) consider(0, j, last_oni + 1, cnt);\n        }\n        \n        for (int j = 0; j < N; j++) {\n            int last_fuku = -1;\n            for (int i = N-1; i >= 0; i--) if (board[i][j] == 'o') { last_fuku = i; break; }\n            int first_oni = N, cnt = 0;\n            for (int i = N-1; i > last_fuku; i--) if (board[i][j] == 'x') { first_oni = i; cnt++; }\n            if (cnt > 0) consider(1, j, N - first_oni, cnt);\n        }\n        \n        for (int i = 0; i < N; i++) {\n            int first_fuku = N;\n            for (int j = 0; j < N; j++) if (board[i][j] == 'o') { first_fuku = j; break; }\n            int last_oni = -1, cnt = 0;\n            for (int j = 0; j < first_fuku; j++) if (board[i][j] == 'x') { last_oni = j; cnt++; }\n            if (cnt > 0) consider(2, i, last_oni + 1, cnt);\n        }\n        \n        for (int i = 0; i < N; i++) {\n            int last_fuku = -1;\n            for (int j = N-1; j >= 0; j--) if (board[i][j] == 'o') { last_fuku = j; break; }\n            int first_oni = N, cnt = 0;\n            for (int j = N-1; j > last_fuku; j--) if (board[i][j] == 'x') { first_oni = j; cnt++; }\n            if (cnt > 0) consider(3, i, N - first_oni, cnt);\n        }\n        \n        if (best_type == 0) { for (int t = 0; t < best_dist; t++) U(best_idx); for (int t = 0; t < best_dist; t++) D(best_idx); }\n        else if (best_type == 1) { for (int t = 0; t < best_dist; t++) D(best_idx); for (int t = 0; t < best_dist; t++) U(best_idx); }\n        else if (best_type == 2) { for (int t = 0; t < best_dist; t++) L(best_idx); for (int t = 0; t < best_dist; t++) R(best_idx); }\n        else { for (int t = 0; t < best_dist; t++) R(best_idx); for (int t = 0; t < best_dist; t++) L(best_idx); }\n    }\n    \n    for (auto& [d, p] : ops) cout << d << \" \" << p << \"\\n\";\n    \n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, L;\nvector<int> T;\n\nlong long simulate(const vector<int>& a, const vector<int>& b, vector<int>& t) {\n    fill(t.begin(), t.end(), 0);\n    int x = 0;\n    for (int week = 0; week < L; week++) {\n        t[x]++;\n        x = (t[x] & 1) ? a[x] : b[x];\n    }\n    long long error = 0;\n    for (int i = 0; i < N; i++) {\n        error += abs(t[i] - T[i]);\n    }\n    return error;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> L;\n    T.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> T[i];\n    }\n    \n    vector<int> a(N), b(N);\n    mt19937 rng(42);\n    \n    // Build weighted list for biased sampling\n    vector<int> weighted;\n    for (int i = 0; i < N; i++) {\n        int cnt = max(1, T[i] / 500);\n        for (int j = 0; j < cnt; j++) weighted.push_back(i);\n    }\n    \n    // Initialize: circular\n    for (int i = 0; i < N; i++) {\n        a[i] = (i + 1) % N;\n        b[i] = (i + 1) % N;\n    }\n    \n    vector<int> t(N);\n    long long best_error = simulate(a, b, t);\n    vector<int> best_a = a, best_b = b;\n    long long cur_error = best_error;\n    \n    auto start = chrono::steady_clock::now();\n    double time_limit = 1.85;\n    \n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > time_limit) break;\n        \n        double progress = elapsed / time_limit;\n        double temp = 5000.0 * pow(0.0001, progress);\n        \n        int i = rng() % N;\n        int choice = rng() % 2;\n        int old_val = (choice == 0) ? a[i] : b[i];\n        int new_val;\n        if (rng() % 3 == 0) {\n            new_val = rng() % N;\n        } else {\n            new_val = weighted[rng() % weighted.size()];\n        }\n        \n        if (choice == 0) a[i] = new_val;\n        else b[i] = new_val;\n        \n        long long new_error = simulate(a, b, t);\n        \n        double delta = (double)(new_error - cur_error);\n        if (delta <= 0 || (temp > 0 && exp(-delta / temp) > (double)(rng() % 100000) / 100000.0)) {\n            cur_error = new_error;\n            if (new_error < best_error) {\n                best_error = new_error;\n                best_a = a;\n                best_b = b;\n            }\n        } else {\n            if (choice == 0) a[i] = old_val;\n            else b[i] = old_val;\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 queries_used = 0;\n\nvector<pair<int,int>> query(vector<int> cities) {\n    cout << \"? \" << cities.size();\n    for (int c : cities) cout << \" \" << c;\n    cout << endl;\n    \n    vector<pair<int,int>> edges;\n    for (size_t i = 0; i + 1 < cities.size(); i++) {\n        int a, b;\n        cin >> a >> b;\n        edges.emplace_back(a, b);\n    }\n    queries_used++;\n    return edges;\n}\n\nint main() {\n    ios::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++) cin >> G[i];\n    \n    vector<double> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        x[i] = (lx + rx) / 2.0;\n        y[i] = (ly + ry) / 2.0;\n    }\n    \n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return x[a] + y[a] < x[b] + y[b];\n    });\n    \n    vector<vector<int>> groups(M);\n    int idx = 0;\n    for (int i = 0; i < M; i++) {\n        for (int j = 0; j < G[i]; j++) {\n            groups[i].push_back(order[idx++]);\n        }\n    }\n    \n    vector<vector<pair<int,int>>> edges(M);\n    \n    for (int k = 0; k < M; k++) {\n        int g = groups[k].size();\n        if (g == 1) continue;\n        \n        vector<pair<int,int>> all_edges;\n        \n        for (int i = 0; i < g - 1 && queries_used < Q; ) {\n            int end = min(i + L, g);\n            if (end - i >= 2) {\n                vector<int> subset(groups[k].begin() + i, groups[k].begin() + end);\n                auto e = query(subset);\n                all_edges.insert(all_edges.end(), e.begin(), e.end());\n                i += max(1, end - i - 1);\n            } else break;\n        }\n        \n        map<int, int> city_to_local;\n        for (int i = 0; i < g; i++) city_to_local[groups[k][i]] = i;\n        \n        vector<int> parent(g);\n        iota(parent.begin(), parent.end(), 0);\n        function<int(int)> find = [&](int x) -> int {\n            return parent[x] == x ? x : parent[x] = find(parent[x]);\n        };\n        \n        for (auto& e : all_edges) {\n            int u = city_to_local[e.first];\n            int v = city_to_local[e.second];\n            if (find(u) != find(v)) {\n                parent[find(u)] = find(v);\n                edges[k].push_back(e);\n            }\n        }\n        \n        for (int i = 0; i + 1 < g && (int)edges[k].size() < g - 1; i++) {\n            int u = i, v = i + 1;\n            if (find(u) != find(v)) {\n                parent[find(u)] = find(v);\n                edges[k].push_back({groups[k][u], groups[k][v]});\n            }\n        }\n    }\n    \n    cout << \"!\" << endl;\n    for (int k = 0; k < M; k++) {\n        for (int c : groups[k]) cout << c << \" \";\n        cout << \"\\n\";\n        for (auto& e : edges[k]) {\n            cout << e.first << \" \" << e.second << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc046":"#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<pair<int, int>> targets(M);\n    for (int i = 0; i < M; i++) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n    \n    vector<string> actions;\n    int curR = targets[0].first, curC = targets[0].second;\n    \n    for (int i = 1; i < M; i++) {\n        int tR = targets[i].first, tC = targets[i].second;\n        \n        int moveCost = abs(tR - curR) + abs(tC - curC);\n        int bestCost = moveCost;\n        int bestStrategy = 0;\n        \n        // Strategy 1: Move to column, slide up (target at row 0)\n        if (tR == 0 && curR > 0) {\n            int cost = abs(tC - curC) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 1; }\n        }\n        \n        // Strategy 2: Move to column, slide down (target at row N-1)\n        if (tR == N - 1 && curR < N - 1) {\n            int cost = abs(tC - curC) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 2; }\n        }\n        \n        // Strategy 3: Move to row, slide left (target at col 0)\n        if (tC == 0 && curC > 0) {\n            int cost = abs(tR - curR) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 3; }\n        }\n        \n        // Strategy 4: Move to row, slide right (target at col N-1)\n        if (tC == N - 1 && curC < N - 1) {\n            int cost = abs(tR - curR) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 4; }\n        }\n        \n        switch (bestStrategy) {\n            case 0:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                break;\n            case 1:\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                actions.push_back(\"S U\");\n                curR = 0;\n                break;\n            case 2:\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                actions.push_back(\"S D\");\n                curR = N - 1;\n                break;\n            case 3:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                actions.push_back(\"S L\");\n                curC = 0;\n                break;\n            case 4:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                actions.push_back(\"S R\");\n                curC = N - 1;\n                break;\n        }\n    }\n    \n    for (const string& action : actions) {\n        cout << action << \"\\n\";\n    }\n    \n    return 0;\n}"},"2":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int W = 10000;\nint n;\nvector<int> px, py, rr;\nint a[201], b[201], c[201], d[201];\n\nbool canExpand(int i, int dir) {\n    int na = a[i], nb = b[i], nc = c[i], nd = d[i];\n    if (dir == 0) na--;\n    else if (dir == 1) nc++;\n    else if (dir == 2) nb--;\n    else nd++;\n    \n    if (na < 0 || nc > W || nb < 0 || nd > W) return false;\n    \n    for (int j = 0; j < n; j++) {\n        if (i == j) continue;\n        if (!(nc <= a[j] || c[j] <= na || nd <= b[j] || d[j] <= nb)) return false;\n    }\n    return true;\n}\n\nvoid expand(int i, int dir) {\n    if (dir == 0) a[i]--;\n    else if (dir == 1) c[i]++;\n    else if (dir == 2) b[i]--;\n    else d[i]++;\n}\n\nlong long area(int i) {\n    return (long long)(c[i] - a[i]) * (d[i] - b[i]);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> n;\n    px.resize(n); py.resize(n); rr.resize(n);\n    \n    for (int i = 0; i < n; i++) {\n        cin >> px[i] >> py[i] >> rr[i];\n        a[i] = px[i]; b[i] = py[i]; c[i] = px[i]+1; d[i] = py[i]+1;\n    }\n    \n    auto start = chrono::high_resolution_clock::now();\n    \n    while (true) {\n        auto now = chrono::high_resolution_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > 4.8) break;\n        \n        bool changed = false;\n        \n        vector<int> order(n);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(), [&](int i, int j) {\n            return rr[i] - area(i) > rr[j] - area(j);\n        });\n        \n        for (int i : order) {\n            for (int dir = 0; dir < 4; dir++) {\n                if (canExpand(i, dir)) {\n                    expand(i, dir);\n                    changed = true;\n                }\n            }\n        }\n        \n        if (!changed) break;\n    }\n    \n    // Shrink rectangles that are too big\n    for (int iter = 0; iter < 1000; iter++) {\n        for (int i = 0; i < n; i++) {\n            if (area(i) <= rr[i]) continue;\n            for (int dir = 0; dir < 4; dir++) {\n                int na = a[i], nb = b[i], nc = c[i], nd = d[i];\n                if (dir == 0) na++;\n                else if (dir == 1) nc--;\n                else if (dir == 2) nb++;\n                else nd--;\n                \n                if (na >= nc || nb >= nd) continue;\n                if (!(na <= px[i] && px[i] < nc && nb <= py[i] && py[i] < nd)) continue;\n                \n                long long newArea = (long long)(nc - na) * (nd - nb);\n                if (newArea >= rr[i]) {\n                    a[i] = na; b[i] = nb; c[i] = nc; d[i] = nd;\n                }\n            }\n        }\n    }\n    \n    for (int i = 0; i < n; i++) {\n        cout << a[i] << \" \" << b[i] << \" \" << c[i] << \" \" << d[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dc[] = {'U', 'D', 'L', 'R'};\n\nint t[N][N], p[N][N];\nint si, sj;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> si >> sj;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            cin >> t[i][j];\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            cin >> p[i][j];\n    \n    struct State {\n        int x, y;\n        int score;\n        bitset<2500> usedTiles;\n        string path;\n    };\n    \n    const int BEAM_WIDTH = 400;\n    \n    vector<State> beam;\n    State init;\n    init.x = si;\n    init.y = sj;\n    init.score = p[si][sj];\n    init.usedTiles.set(t[si][sj]);\n    init.path = \"\";\n    beam.push_back(init);\n    \n    string bestPath = \"\";\n    int bestScore = init.score;\n    \n    auto startTime = chrono::steady_clock::now();\n    \n    while (!beam.empty()) {\n        auto now = chrono::steady_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - startTime).count() > 1900) {\n            for (const auto& state : beam) {\n                if (state.score > bestScore) {\n                    bestScore = state.score;\n                    bestPath = state.path;\n                }\n            }\n            break;\n        }\n        \n        vector<State> nextBeam;\n        nextBeam.reserve(beam.size() * 4);\n        \n        for (const auto& state : beam) {\n            bool canExtend = false;\n            for (int d = 0; d < 4; d++) {\n                int nx = state.x + dx[d];\n                int ny = state.y + dy[d];\n                if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                if (state.usedTiles[t[nx][ny]]) continue;\n                \n                canExtend = true;\n                State newState;\n                newState.x = nx;\n                newState.y = ny;\n                newState.score = state.score + p[nx][ny];\n                newState.usedTiles = state.usedTiles;\n                newState.usedTiles.set(t[nx][ny]);\n                newState.path = state.path + dc[d];\n                nextBeam.push_back(move(newState));\n            }\n            \n            if (!canExtend && state.score > bestScore) {\n                bestScore = state.score;\n                bestPath = state.path;\n            }\n        }\n        \n        if (nextBeam.size() > BEAM_WIDTH) {\n            nth_element(nextBeam.begin(), nextBeam.begin() + BEAM_WIDTH, nextBeam.end(),\n                [](const State& a, const State& b) { return a.score > b.score; });\n            nextBeam.resize(BEAM_WIDTH);\n        }\n        \n        beam = move(nextBeam);\n    }\n    \n    cout << bestPath << endl;\n    \n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\ndouble h[N][N-1], v[N-1][N];\nint h_cnt[N][N-1], v_cnt[N-1][N];\ndouble h_row[N], v_col[N];\nint h_row_cnt[N], v_col_cnt[N];\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    fill(&h[0][0], &h[0][0] + N*(N-1), 5000.0);\n    fill(&v[0][0], &v[0][0] + (N-1)*N, 5000.0);\n    fill(&h_cnt[0][0], &h_cnt[0][0] + N*(N-1), 0);\n    fill(&v_cnt[0][0], &v_cnt[0][0] + (N-1)*N, 0);\n    fill(h_row, h_row + N, 5000.0);\n    fill(v_col, v_col + N, 5000.0);\n    fill(h_row_cnt, h_row_cnt + N, 0);\n    fill(v_col_cnt, v_col_cnt + N, 0);\n    \n    auto getH = [&](int i, int j) {\n        if (h_cnt[i][j] > 0) return h[i][j];\n        if (h_row_cnt[i] > 0) return h_row[i];\n        return 5000.0;\n    };\n    \n    auto getV = [&](int i, int j) {\n        if (v_cnt[i][j] > 0) return v[i][j];\n        if (v_col_cnt[j] > 0) return v_col[j];\n        return 5000.0;\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 idx = [](int i, int j) { return i * N + j; };\n        vector<double> dist(N*N, 1e18);\n        vector<int> prv(N*N, -1);\n        \n        priority_queue<pair<double,int>, vector<pair<double,int>>, greater<>> pq;\n        dist[idx(si, sj)] = 0;\n        pq.push({0, idx(si, sj)});\n        \n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u]) continue;\n            int i = u / N, j = u % N;\n            \n            auto relax = [&](int ni, int nj, double w) {\n                int nu = idx(ni, nj);\n                if (dist[u] + w < dist[nu]) {\n                    dist[nu] = dist[u] + w;\n                    prv[nu] = u;\n                    pq.push({dist[nu], nu});\n                }\n            };\n            \n            if (i > 0) relax(i-1, j, getV(i-1, j));\n            if (i < N-1) relax(i+1, j, getV(i, j));\n            if (j > 0) relax(i, j-1, getH(i, j-1));\n            if (j < N-1) relax(i, j+1, getH(i, j));\n        }\n        \n        string path = \"\";\n        vector<tuple<int, int, int>> edges;\n        \n        int cur = idx(ti, tj);\n        while (prv[cur] != -1) {\n            int ci = cur / N, cj = cur % N;\n            int pi = prv[cur] / N, pj = prv[cur] % N;\n            \n            if (ci < pi) { path += 'U'; edges.emplace_back(1, ci, cj); }\n            else if (ci > pi) { path += 'D'; edges.emplace_back(1, pi, pj); }\n            else if (cj < pj) { path += 'L'; edges.emplace_back(0, ci, cj); }\n            else { path += 'R'; edges.emplace_back(0, pi, pj); }\n            \n            cur = prv[cur];\n        }\n        \n        reverse(path.begin(), path.end());\n        cout << path << \"\\n\" << flush;\n        \n        int feedback;\n        cin >> feedback;\n        \n        double est = 0;\n        for (auto& [t, ei, ej] : edges) {\n            est += (t == 0) ? getH(ei, ej) : getV(ei, ej);\n        }\n        \n        double ratio = feedback / est;\n        \n        for (auto& [t, ei, ej] : edges) {\n            double implied = (t == 0) ? getH(ei, ej) * ratio : getV(ei, ej) * ratio;\n            \n            if (t == 0) {\n                int cnt = ++h_cnt[ei][ej];\n                double alpha = 1.0 / (1.0 + cnt);\n                h[ei][ej] = h[ei][ej] * (1 - alpha) + implied * alpha;\n            } else {\n                int cnt = ++v_cnt[ei][ej];\n                double alpha = 1.0 / (1.0 + cnt);\n                v[ei][ej] = v[ei][ej] * (1 - alpha) + implied * alpha;\n            }\n        }\n        \n        // Update row/column averages\n        for (int i = 0; i < N; i++) {\n            double sum = 0; int cnt = 0;\n            for (int j = 0; j < N-1; j++) {\n                if (h_cnt[i][j] > 0) { sum += h[i][j]; cnt++; }\n            }\n            if (cnt > 0) { h_row[i] = sum / cnt; h_row_cnt[i] = cnt; }\n        }\n        \n        for (int j = 0; j < N; j++) {\n            double sum = 0; int cnt = 0;\n            for (int i = 0; i < N-1; i++) {\n                if (v_cnt[i][j] > 0) { sum += v[i][j]; cnt++; }\n            }\n            if (cnt > 0) { v_col[j] = sum / cnt; v_col_cnt[j] = cnt; }\n        }\n    }\n    \n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n, m;\n    cin >> n >> m;\n    \n    vector<string> strs(m);\n    for(int i = 0; i < m; i++) cin >> strs[i];\n    \n    vector<int> order(m);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return strs[a].size() > strs[b].size();\n    });\n    \n    char grid[N][N];\n    fill(&grid[0][0], &grid[N][0], '.');\n    \n    // Greedy placement with max overlap preference\n    for(int idx : order) {\n        const string& s = strs[idx];\n        int bestR = -1, bestC, bestD, bestOv = -1;\n        \n        for(int r = 0; r < N; r++) {\n            for(int c = 0; c < N; c++) {\n                for(int d = 0; d < 2; d++) {\n                    bool can = true;\n                    int ov = 0;\n                    for(int p = 0; p < (int)s.size() && can; p++) {\n                        int ni = d ? (r + p) % N : r;\n                        int nj = d ? c : (c + p) % N;\n                        if(grid[ni][nj] != '.' && grid[ni][nj] != s[p]) can = false;\n                        if(grid[ni][nj] != '.') ov++;\n                    }\n                    if(can && ov > bestOv) {\n                        bestOv = ov;\n                        bestR = r; bestC = c; bestD = d;\n                    }\n                }\n            }\n        }\n        \n        if(bestR >= 0) {\n            for(int p = 0; p < (int)s.size(); p++) {\n                int ni = bestD ? (bestR + p) % N : bestR;\n                int nj = bestD ? bestC : (bestC + p) % N;\n                grid[ni][nj] = s[p];\n            }\n        }\n    }\n    \n    // Fill remaining cells randomly\n    mt19937 rng(42);\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(grid[i][j] == '.') grid[i][j] = 'A' + rng() % 8;\n        }\n    }\n    \n    // Count function for SA\n    auto countMatched = [&]() {\n        int cnt = 0;\n        for(const auto& s : strs) {\n            bool found = false;\n            for(int r = 0; r < N && !found; r++) {\n                for(int c = 0; c < N && !found; c++) {\n                    for(int d = 0; d < 2 && !found; d++) {\n                        bool ok = true;\n                        for(int p = 0; p < (int)s.size() && ok; p++) {\n                            int ni = d ? (r + p) % N : r;\n                            int nj = d ? c : (c + p) % N;\n                            if(grid[ni][nj] != s[p]) ok = false;\n                        }\n                        if(ok) found = true;\n                    }\n                }\n            }\n            if(found) cnt++;\n        }\n        return cnt;\n    };\n    \n    // Simple SA to improve\n    char bestGrid[N][N];\n    memcpy(bestGrid, grid, sizeof(grid));\n    int bestScore = countMatched();\n    int curScore = bestScore;\n    \n    auto start = chrono::high_resolution_clock::now();\n    double T = 2.0;\n    \n    while(true) {\n        auto now = chrono::high_resolution_clock::now();\n        if(chrono::duration<double>(now - start).count() > 2.7) break;\n        \n        int i = rng() % N, j = rng() % N;\n        char old = grid[i][j];\n        char newc = 'A' + rng() % 8;\n        if(newc == old) continue;\n        \n        grid[i][j] = newc;\n        int newScore = countMatched();\n        \n        if(newScore >= curScore || (rng() & 0xFFFF) < 65536.0 * exp((newScore - curScore) / T)) {\n            curScore = newScore;\n            if(newScore > bestScore) {\n                bestScore = newScore;\n                memcpy(bestGrid, grid, sizeof(grid));\n            }\n        } else {\n            grid[i][j] = old;\n        }\n        T *= 0.9999;\n    }\n    \n    for(int i = 0; i < N; i++) {\n        cout << string(bestGrid[i], bestGrid[i] + N) << '\\n';\n    }\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, si, sj;\nvector<string> grid;\nvector<vector<bool>> visible;\nint visible_count = 0;\n\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir_char[] = {'U', 'D', 'L', 'R'};\n\ninline bool is_road(int i, int j) {\n    return i >= 0 && i < N && j >= 0 && j < N && grid[i][j] != '#';\n}\n\nvoid mark_visible(int i, int j) {\n    if (!visible[i][j]) { visible[i][j] = true; visible_count++; }\n    for (int jj = j - 1; jj >= 0 && is_road(i, jj); jj--)\n        if (!visible[i][jj]) { visible[i][jj] = true; visible_count++; }\n    for (int jj = j + 1; jj < N && is_road(i, jj); jj++)\n        if (!visible[i][jj]) { visible[i][jj] = true; visible_count++; }\n    for (int ii = i - 1; ii >= 0 && is_road(ii, j); ii--)\n        if (!visible[ii][j]) { visible[ii][j] = true; visible_count++; }\n    for (int ii = i + 1; ii < N && is_road(ii, j); ii++)\n        if (!visible[ii][j]) { visible[ii][j] = true; visible_count++; }\n}\n\nint count_new_visible(int i, int j) {\n    int cnt = !visible[i][j];\n    for (int jj = j - 1; jj >= 0 && is_road(i, jj); jj--) cnt += !visible[i][jj];\n    for (int jj = j + 1; jj < N && is_road(i, jj); jj++) cnt += !visible[i][jj];\n    for (int ii = i - 1; ii >= 0 && is_road(ii, j); ii--) cnt += !visible[ii][j];\n    for (int ii = i + 1; ii < N && is_road(ii, j); ii++) cnt += !visible[ii][j];\n    return cnt;\n}\n\npair<vector<vector<int>>, vector<vector<pair<int,int>>>> dijkstra(int si, int sj) {\n    vector<vector<int>> dist(N, vector<int>(N, INT_MAX));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1,-1}));\n    priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;\n    dist[si][sj] = 0; pq.push({0, si, sj});\n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top(); pq.pop();\n        if (d > dist[i][j]) continue;\n        for (int k = 0; k < 4; k++) {\n            int ni = i + dx[k], nj = j + dy[k];\n            if (is_road(ni, nj)) {\n                int c = grid[ni][nj] - '0';\n                if (dist[i][j] + c < dist[ni][nj]) {\n                    dist[ni][nj] = dist[i][j] + c;\n                    parent[ni][nj] = {i, j};\n                    pq.push({dist[ni][nj], ni, nj});\n                }\n            }\n        }\n    }\n    return {dist, parent};\n}\n\nstring get_path(int i1, int j1, int i2, int j2, vector<vector<pair<int,int>>>& parent) {\n    string path;\n    int ci = i2, cj = j2;\n    while (ci != i1 || cj != j1) {\n        auto [pi, pj] = parent[ci][cj];\n        for (int k = 0; k < 4; k++) if (pi + dx[k] == ci && pj + dy[k] == cj) { path += dir_char[k]; break; }\n        ci = pi; cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(nullptr);\n    cin >> N >> si >> sj;\n    grid.resize(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    \n    int total_roads = 0;\n    for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (is_road(i, j)) total_roads++;\n    \n    visible.assign(N, vector<bool>(N, false));\n    int cur_i = si, cur_j = sj;\n    string result;\n    mark_visible(cur_i, cur_j);\n    \n    while (visible_count < total_roads) {\n        auto [dist, parent] = dijkstra(cur_i, cur_j);\n        int best_i = -1, best_j = -1; double best_score = -1;\n        for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) {\n            if (dist[i][j] == INT_MAX || dist[i][j] == 0) continue;\n            int nv = count_new_visible(i, j);\n            if (nv == 0) continue;\n            double score = (double)nv / dist[i][j];\n            if (score > best_score) { best_score = score; best_i = i; best_j = j; }\n        }\n        if (best_i == -1) break;\n        string path = get_path(cur_i, cur_j, best_i, best_j, parent);\n        result += path;\n        int ti = cur_i, tj = cur_j;\n        for (char c : path) {\n            if (c == 'U') ti--; else if (c == 'D') ti++; else if (c == 'L') tj--; else tj++;\n            mark_visible(ti, tj);\n        }\n        cur_i = best_i; cur_j = best_j;\n    }\n    \n    if (cur_i != si || cur_j != sj) {\n        auto [dist, parent] = dijkstra(cur_i, cur_j);\n        result += get_path(cur_i, cur_j, si, sj, parent);\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    vector<vector<int>> deps(N), rdeps(N);\n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        deps[v].push_back(u);\n        rdeps[u].push_back(v);\n    }\n    \n    vector<int> taskStatus(N, -1);\n    vector<int> memberTask(M, -1), memberStartDay(M, 0);\n    \n    // Better initial skill estimate based on generation (L2 norm 20-60, avg ~40)\n    double initSkill = 40.0 / sqrt(K);\n    vector<vector<double>> skillEst(M, vector<double>(K, initSkill));\n    vector<vector<double>> skillLo(M, vector<double>(K, 0.0));\n    \n    auto estimateTime = [&](int task, int member) -> double {\n        double w = 0;\n        for (int k = 0; k < K; k++)\n            w += max(0.0, (double)d[task][k] - skillEst[member][k]);\n        return max(1.0, w);\n    };\n    \n    // Critical path depth\n    vector<int> depth(N, 1);\n    for (int i = N - 1; i >= 0; i--)\n        for (int v : rdeps[i])\n            depth[i] = max(depth[i], depth[v] + 1);\n    \n    // Downstream task count\n    vector<int> downstream(N, 0);\n    for (int i = N - 1; i >= 0; i--) {\n        downstream[i] = (int)rdeps[i].size();\n        for (int v : rdeps[i])\n            downstream[i] += downstream[v];\n    }\n    \n    for (int day = 1; ; day++) {\n        vector<int> availTasks;\n        for (int i = 0; i < N; i++) {\n            if (taskStatus[i] != -1) continue;\n            bool ok = true;\n            for (int dep : deps[i])\n                if (taskStatus[dep] != 1) { ok = false; break; }\n            if (ok) availTasks.push_back(i);\n        }\n        \n        // Priority: depth first, then downstream count\n        sort(availTasks.begin(), availTasks.end(), [&](int a, int b) {\n            if (depth[a] != depth[b]) return depth[a] > depth[b];\n            return downstream[a] > downstream[b];\n        });\n        \n        vector<int> freeMembers;\n        for (int j = 0; j < M; j++)\n            if (memberTask[j] == -1) freeMembers.push_back(j);\n        \n        vector<pair<int, int>> assignments;\n        vector<bool> usedMember(M, false);\n        \n        for (int task : availTasks) {\n            int bestMember = -1;\n            double bestTime = 1e18;\n            for (int member : freeMembers) {\n                if (usedMember[member]) continue;\n                double t = estimateTime(task, member);\n                if (t < bestTime) {\n                    bestTime = t;\n                    bestMember = member;\n                }\n            }\n            if (bestMember == -1) break;\n            \n            usedMember[bestMember] = true;\n            assignments.push_back({bestMember + 1, task + 1});\n            taskStatus[task] = 0;\n            memberTask[bestMember] = task;\n            memberStartDay[bestMember] = day;\n        }\n        \n        cout << assignments.size();\n        for (auto& [a, b] : assignments) cout << \" \" << a << \" \" << b;\n        cout << \"\\n\";\n        cout.flush();\n        \n        int n; cin >> n;\n        if (n == -1) break;\n        \n        for (int i = 0; i < n; i++) {\n            int f; cin >> f; f--;\n            int task = memberTask[f];\n            int timeTaken = day - memberStartDay[f] + 1;\n            taskStatus[task] = 1;\n            memberTask[f] = -1;\n            \n            if (timeTaken == 1) {\n                // High confidence: member skills >= task requirements\n                for (int k = 0; k < K; k++) {\n                    skillLo[f][k] = max(skillLo[f][k], (double)d[task][k]);\n                    skillEst[f][k] = max(skillEst[f][k], (double)d[task][k]);\n                }\n            } else {\n                // w \u2248 timeTaken (noise \u00b13), adjust estimates\n                double wEst = (double)timeTaken;\n                double currW = 0;\n                for (int k = 0; k < K; k++)\n                    currW += max(0.0, (double)d[task][k] - skillEst[f][k]);\n                \n                if (currW > 0.5) {\n                    // Blend factor: if we overestimated skills, reduce them\n                    double factor = wEst / currW;\n                    factor = 0.7 * factor + 0.3; // Smooth adjustment\n                    factor = max(0.5, min(1.8, factor));\n                    \n                    for (int k = 0; k < K; k++) {\n                        double gap = d[task][k] - skillEst[f][k];\n                        if (gap > 0) {\n                            double newSkill = d[task][k] - gap * factor;\n                            skillEst[f][k] = max(skillLo[f][k], newSkill);\n                        }\n                    }\n                } else if (wEst > 3) {\n                    // We thought w\u22480, but time > 3, so skills are overestimated\n                    for (int k = 0; k < K; k++) {\n                        if (d[task][k] > skillLo[f][k]) {\n                            skillEst[f][k] = max(skillLo[f][k], \n                                skillEst[f][k] - wEst / K);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1000, M = 50, CX = 400, CY = 400;\nint ordA[N], ordB[N], ordC[N], ordD[N];\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\ninline int manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\npair<vector<pair<int,bool>>, int> buildGreedyRoute(const vector<int>& selected) {\n    vector<pair<int, bool>> events;\n    events.reserve(2 * M);\n    vector<bool> picked(N, false), delivered(N, false);\n    int cx = CX, cy = CY, totalCost = 0;\n    \n    for (int i = 0; i < 2 * M; i++) {\n        int best = -1, bestDist = INT_MAX;\n        bool isDelivery = false;\n        \n        for (int idx : selected) {\n            if (!picked[idx]) {\n                int d = manhattan(cx, cy, ordA[idx], ordB[idx]);\n                if (d < bestDist) { bestDist = d; best = idx; isDelivery = false; }\n            } else if (!delivered[idx]) {\n                int d = manhattan(cx, cy, ordC[idx], ordD[idx]);\n                if (d < bestDist) { bestDist = d; best = idx; isDelivery = true; }\n            }\n        }\n        \n        totalCost += bestDist;\n        if (isDelivery) { cx = ordC[best]; cy = ordD[best]; delivered[best] = true; }\n        else { cx = ordA[best]; cy = ordB[best]; picked[best] = true; }\n        events.push_back({best, isDelivery});\n    }\n    totalCost += manhattan(cx, cy, CX, CY);\n    return {events, totalCost};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    auto startTime = chrono::steady_clock::now();\n    for (int i = 0; i < N; i++) cin >> ordA[i] >> ordB[i] >> ordC[i] >> ordD[i];\n    \n    auto elapsed = [&]() {\n        return chrono::duration<double>(chrono::steady_clock::now() - startTime).count();\n    };\n    \n    vector<pair<int, int>> orderedByCenter(N);\n    for (int i = 0; i < N; i++) {\n        int d = manhattan(CX, CY, ordA[i], ordB[i]) + manhattan(CX, CY, ordC[i], ordD[i]);\n        orderedByCenter[i] = {d, i};\n    }\n    sort(orderedByCenter.begin(), orderedByCenter.end());\n    \n    vector<int> selected(M), unselected(N - M);\n    for (int i = 0; i < M; i++) selected[i] = orderedByCenter[i].second;\n    for (int i = 0; i < N - M; i++) unselected[i] = orderedByCenter[M + i].second;\n    \n    auto [bestEvents, bestCost] = buildGreedyRoute(selected);\n    vector<int> bestSelected = selected;\n    int currentCost = bestCost;\n    double temp = 3000.0;\n    \n    while (elapsed() < 1.85) {\n        int selIdx = rng() % M;\n        int unselIdx = rng() % (N - M);\n        \n        swap(selected[selIdx], unselected[unselIdx]);\n        auto [events, cost] = buildGreedyRoute(selected);\n        \n        int delta = cost - currentCost;\n        bool accept = delta < 0 || exp(-delta / temp) > (rng() % 10000) / 10000.0;\n        \n        if (accept) {\n            currentCost = cost;\n            if (cost < bestCost) {\n                bestCost = cost;\n                bestSelected = selected;\n                bestEvents = events;\n            }\n        } else {\n            swap(selected[selIdx], unselected[unselIdx]);\n        }\n        temp *= 0.99995;\n    }\n    \n    cout << M;\n    for (int i = 0; i < M; i++) cout << \" \" << (bestSelected[i] + 1);\n    cout << \"\\n\" << (2 * M + 2) << \" \" << CX << \" \" << CY;\n    for (const auto& [idx, isDel] : bestEvents) {\n        if (isDel) cout << \" \" << ordC[idx] << \" \" << ordD[idx];\n        else cout << \" \" << ordA[idx] << \" \" << ordB[idx];\n    }\n    cout << \" \" << CX << \" \" << CY << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass UnionFind {\n    vector<int> parent, rank_;\npublic:\n    UnionFind(int n) : parent(n), rank_(n, 0) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    int find(int x) {\n        if (parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    bool unite(int x, int y) {\n        int px = find(x), py = find(y);\n        if (px == py) return false;\n        if (rank_[px] < rank_[py]) swap(px, py);\n        parent[py] = px;\n        if (rank_[px] == rank_[py]) rank_[px]++;\n        return true;\n    }\n    bool same(int x, int y) {\n        return find(x) == find(y);\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 400, M = 1995;\n    \n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<int> u(M), v(M), d(M);\n    for (int i = 0; i < M; i++) {\n        cin >> u[i] >> v[i];\n        double dx = x[u[i]] - x[v[i]];\n        double dy = y[u[i]] - y[v[i]];\n        d[i] = (int)round(sqrt(dx * dx + dy * dy));\n    }\n    \n    UnionFind uf(N);\n    int components = N;\n    \n    for (int i = 0; i < M; i++) {\n        int l;\n        cin >> l;\n        \n        int pu = uf.find(u[i]);\n        int pv = uf.find(v[i]);\n        \n        bool already_connected = (pu == pv);\n        double ratio = (double)l / d[i];\n        \n        bool adopt = false;\n        \n        if (!already_connected) {\n            int useful_remaining = 0;\n            int same_pair_remaining = 0;\n            for (int j = i + 1; j < M; j++) {\n                int uj = uf.find(u[j]);\n                int vj = uf.find(v[j]);\n                if (uj != vj) {\n                    useful_remaining++;\n                    if ((uj == pu && vj == pv) || (uj == pv && vj == pu)) {\n                        same_pair_remaining++;\n                    }\n                }\n            }\n            \n            int needed = components - 1;\n            \n            if (useful_remaining < needed * 2) {\n                adopt = true;\n            } else {\n                double k = same_pair_remaining;\n                double expected_min = 1.0 + 2.0 / (k + 2);\n                double threshold = expected_min + 0.2;\n                \n                if (ratio <= threshold || same_pair_remaining == 0) {\n                    adopt = true;\n                }\n            }\n        }\n        \n        if (adopt) {\n            uf.unite(u[i], v[i]);\n            components--;\n        }\n        \n        cout << (adopt ? 1 : 0) << \"\\n\" << flush;\n    }\n    \n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<array<int,3>> pets;\nvector<array<int,2>> humans;\nbool blocked[32][32];\n\nbool pet_at(int x, int y) {\n    for (auto& p : pets) if (p[0] == x && p[1] == y) return true;\n    return false;\n}\n\nbool pet_adjacent(int x, int y) {\n    int dx[] = {0, -1, 1, 0, 0}, dy[] = {0, 0, 0, -1, 1};\n    for (int d = 0; d < 5; d++) if (pet_at(x+dx[d], y+dy[d])) return true;\n    return false;\n}\n\nbool can_place(int x, int y) {\n    if (x < 1 || x > 30 || y < 1 || y > 30 || blocked[x][y]) return false;\n    for (auto& h : humans) if (h[0] == x && h[1] == y) return false;\n    return !pet_adjacent(x, y);\n}\n\nbool passable(int x, int y) {\n    return x >= 1 && x <= 30 && y >= 1 && y <= 30 && !blocked[x][y];\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N; pets.resize(N);\n    for (int i = 0; i < N; i++) cin >> pets[i][0] >> pets[i][1] >> pets[i][2];\n    cin >> M; humans.resize(M);\n    for (int i = 0; i < M; i++) cin >> humans[i][0] >> humans[i][1];\n    \n    set<pair<int,int>> target;\n    for (int i = 1; i <= 30; i++) {\n        for (int c : {7, 14, 21, 28}) {\n            target.insert({i, c});\n            target.insert({c, i});\n        }\n    }\n    \n    int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};\n    char wc[] = {'u', 'd', 'l', 'r'}, mc[] = {'U', 'D', 'L', 'R'};\n    \n    for (int turn = 0; turn < 300; turn++) {\n        string action(M, '.');\n        \n        for (int i = 0; i < M; i++) {\n            int hx = humans[i][0], hy = humans[i][1];\n            int best = -1, bestd = -1;\n            \n            for (int d = 0; d < 4; d++) {\n                int nx = hx + dx[d], ny = hy + dy[d];\n                if (can_place(nx, ny)) {\n                    int sc = target.count({nx, ny}) ? 100 : 1;\n                    if (sc > best) { best = sc; bestd = d; }\n                }\n            }\n            \n            if (bestd >= 0) {\n                action[i] = wc[bestd];\n            } else {\n                int minD = INT_MAX, moveD = -1;\n                for (auto& [tx, ty] : target) {\n                    if (blocked[tx][ty]) continue;\n                    int dist = abs(hx-tx) + abs(hy-ty);\n                    if (dist > 0 && dist < minD) minD = dist;\n                }\n                for (int d = 0; d < 4; d++) {\n                    int nx = hx + dx[d], ny = hy + dy[d];\n                    if (!passable(nx, ny) || pet_at(nx, ny)) continue;\n                    for (auto& [tx, ty] : target) {\n                        if (blocked[tx][ty]) continue;\n                        if (abs(nx-tx) + abs(ny-ty) < minD) {\n                            minD = abs(nx-tx) + abs(ny-ty);\n                            moveD = d;\n                        }\n                    }\n                }\n                if (moveD >= 0) action[i] = mc[moveD];\n            }\n        }\n        \n        cout << action << \"\\n\" << flush;\n        \n        for (int i = 0; i < M; i++) {\n            char a = action[i];\n            for (int d = 0; d < 4; d++) {\n                if (a == wc[d]) blocked[humans[i][0]+dx[d]][humans[i][1]+dy[d]] = true;\n                if (a == mc[d]) { humans[i][0] += dx[d]; humans[i][1] += dy[d]; }\n            }\n        }\n        \n        for (int i = 0; i < N; i++) {\n            string s; cin >> s;\n            for (char c : s) {\n                if (c == 'U') pets[i][0]--;\n                else if (c == 'D') pets[i][0]++;\n                else if (c == 'L') pets[i][1]--;\n                else if (c == 'R') pets[i][1]++;\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N = 20;\nint si, sj, ti, tj;\ndouble p;\nbool hwall[20][19];\nbool vwall[19][20];\n\nbool canMove(int i, int j, char dir) {\n    if (dir == 'U') return i > 0 && !vwall[i-1][j];\n    if (dir == 'D') return i < 19 && !vwall[i][j];\n    if (dir == 'L') return j > 0 && !hwall[i][j-1];\n    if (dir == 'R') return j < 19 && !hwall[i][j];\n    return false;\n}\n\npair<int,int> doMove(int i, int j, char dir) {\n    if (!canMove(i, j, dir)) return {i, j};\n    if (dir == 'U') return {i-1, j};\n    if (dir == 'D') return {i+1, j};\n    if (dir == 'L') return {i, j-1};\n    if (dir == 'R') return {i, j+1};\n    return {i, j};\n}\n\ndouble evaluate(const string& s) {\n    if (s.empty() || s.size() > 200) return -1;\n    vector<vector<double>> prob(N, vector<double>(N, 0));\n    prob[si][sj] = 1.0;\n    double expectedScore = 0;\n    for (int t = 1; t <= (int)s.size(); t++) {\n        char dir = s[t-1];\n        vector<vector<double>> newProb(N, vector<double>(N, 0));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (prob[i][j] < 1e-18) continue;\n                auto [ni, nj] = doMove(i, j, dir);\n                if (ni == ti && nj == tj) {\n                    expectedScore += (1-p) * prob[i][j] * (401 - t);\n                } else {\n                    newProb[ni][nj] += (1-p) * prob[i][j];\n                }\n                newProb[i][j] += p * prob[i][j];\n            }\n        }\n        prob = newProb;\n    }\n    return expectedScore;\n}\n\nstring bfsWithOrder(vector<char>& order) {\n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1,-1}));\n    vector<vector<char>> fromDir(N, vector<char>(N, ' '));\n    queue<pair<int,int>> q;\n    q.push({si, sj});\n    dist[si][sj] = 0;\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        for (char d : order) {\n            auto [ni, nj] = doMove(i, j, d);\n            if (ni == i && nj == j) continue;\n            if (dist[ni][nj] == -1) {\n                dist[ni][nj] = dist[i][j] + 1;\n                parent[ni][nj] = {i, j};\n                fromDir[ni][nj] = d;\n                q.push({ni, nj});\n            }\n        }\n    }\n    string path;\n    int ci = ti, cj = tj;\n    while (ci != si || cj != sj) {\n        path += fromDir[ci][cj];\n        auto [pi, pj] = parent[ci][cj];\n        ci = pi; cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nmt19937 rng(12345);\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    auto startTime = chrono::steady_clock::now();\n    \n    cin >> si >> sj >> ti >> tj >> p;\n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < 19; j++) hwall[i][j] = (s[j] == '1');\n    }\n    for (int i = 0; i < 19; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) vwall[i][j] = (s[j] == '1');\n    }\n    \n    string best;\n    double bestScore = -1;\n    vector<char> order = {'U', 'D', 'L', 'R'};\n    \n    auto updateBest = [&](const string& s) {\n        if (s.size() > 200) return;\n        double score = evaluate(s);\n        if (score > bestScore) {\n            bestScore = score;\n            best = s;\n        }\n    };\n    \n    while (true) {\n        auto now = chrono::steady_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - startTime).count() > 1850) break;\n        \n        shuffle(order.begin(), order.end(), rng);\n        string path = bfsWithOrder(order);\n        int pathLen = path.size();\n        \n        // Strategy 1: Uniform repetition of each move\n        for (int rep = 1; rep * pathLen <= 200; rep++) {\n            string result;\n            for (char c : path) {\n                for (int i = 0; i < rep; i++) result += c;\n            }\n            updateBest(result);\n        }\n        \n        // Strategy 2: Repeat entire path multiple times\n        for (int rep = 1; rep * pathLen <= 200; rep++) {\n            string result;\n            for (int i = 0; i < rep; i++) result += path;\n            updateBest(result);\n        }\n        \n        // Strategy 3: Wall-aware repetition\n        int ci = si, cj = sj;\n        for (int baseRep = 1; baseRep <= 10; baseRep++) {\n            string result;\n            ci = si; cj = sj;\n            for (char c : path) {\n                auto [ni, nj] = doMove(ci, cj, c);\n                bool safeAfter = !canMove(ni, nj, c);\n                int reps = safeAfter ? baseRep + 2 : baseRep;\n                for (int i = 0; i < reps && result.size() < 200; i++) result += c;\n                ci = ni; cj = nj;\n            }\n            updateBest(result);\n        }\n        \n        // Strategy 4: Combine path and move repetition\n        for (int pathRep = 1; pathRep <= 5; pathRep++) {\n            for (int moveRep = 1; moveRep * pathLen * pathRep <= 200 && moveRep <= 5; moveRep++) {\n                string result;\n                for (int pr = 0; pr < pathRep; pr++) {\n                    for (char c : path) {\n                        for (int mr = 0; mr < moveRep; mr++) result += c;\n                    }\n                }\n                updateBest(result);\n            }\n        }\n    }\n    \n    cout << best << endl;\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nint tiles[N][N];\nint rotation[N][N];\n\nconst int di[] = {0, -1, 0, 1};\nconst int dj[] = {-1, 0, 1, 0};\n\nconst int to_arr[8][4] = {\n    {1, 0, -1, -1}, {3, -1, -1, 0}, {-1, -1, 3, 2}, {-1, 2, 1, -1},\n    {1, 0, 3, 2}, {3, 2, 1, 0}, {2, -1, 0, -1}, {-1, 3, -1, 1},\n};\n\ninline int getState(int i, int j) {\n    int t = tiles[i][j], r = rotation[i][j];\n    if (t < 4) return (t + r) % 4;\n    if (t < 6) return 4 + (t - 4 + r) % 2;\n    return 6 + (t - 6 + r) % 2;\n}\n\nint traceLoop(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd, length = 0;\n    do {\n        int state = getState(i, j);\n        int d2 = to_arr[state][d];\n        if (d2 == -1) return 0;\n        length++;\n        if (length > 4 * N * N) return 0;\n        i += di[d2]; j += dj[d2];\n        if ((unsigned)i >= N || (unsigned)j >= N) return 0;\n        d = (d2 + 2) % 4;\n    } while (i != si || j != sj || d != sd);\n    return length;\n}\n\npair<int, int> computeTopTwoLoops() {\n    static bool visited[N][N][4];\n    memset(visited, 0, sizeof(visited));\n    int top1 = 0, top2 = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int state = getState(i, j);\n            for (int d = 0; d < 4; d++) {\n                if (to_arr[state][d] == -1 || visited[i][j][d]) continue;\n                int len = traceLoop(i, j, d);\n                if (len > 0) {\n                    if (len > top1) { top2 = top1; top1 = len; }\n                    else if (len > top2) { top2 = len; }\n                    int ci = i, cj = j, cd = d;\n                    do {\n                        visited[ci][cj][cd] = true;\n                        int st = getState(ci, cj);\n                        int d2 = to_arr[st][cd];\n                        ci += di[d2]; cj += dj[d2];\n                        cd = (d2 + 2) % 4;\n                    } while (ci != i || cj != j || cd != d);\n                }\n            }\n        }\n    }\n    return {top1, top2};\n}\n\nint best_rotation[N][N];\nlong long best_score;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = s[j] - '0';\n            rotation[i][j] = 0;\n        }\n    }\n    \n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    \n    auto [l1, l2] = computeTopTwoLoops();\n    best_score = (long long)l1 * l2;\n    memcpy(best_rotation, rotation, sizeof(rotation));\n    long long current_score = best_score;\n    \n    const double TIME_LIMIT = 1.9;\n    \n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start_time).count();\n        if (elapsed > TIME_LIMIT) break;\n        \n        double T = 1000.0 * pow(0.0001, elapsed / TIME_LIMIT);\n        \n        int i = rng() % N, j = rng() % N;\n        int old_rot = rotation[i][j];\n        int new_rot = (old_rot + 1 + rng() % 3) % 4;\n        \n        rotation[i][j] = new_rot;\n        auto [nl1, nl2] = computeTopTwoLoops();\n        long long new_score = (long long)nl1 * nl2;\n        \n        double delta = (double)(new_score - current_score);\n        if (delta >= 0 || uniform_real_distribution<double>(0, 1)(rng) < exp(delta / T)) {\n            current_score = new_score;\n            if (new_score > best_score) {\n                best_score = new_score;\n                memcpy(best_rotation, rotation, sizeof(rotation));\n            }\n        } else {\n            rotation[i][j] = old_rot;\n        }\n    }\n    \n    string result;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            result += ('0' + best_rotation[i][j]);\n    cout << result << endl;\n    \n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dc_char[] = {'U', 'D', 'L', 'R'};\n\nint hexChar(char c) {\n    return (c >= '0' && c <= '9') ? c - '0' : c - 'a' + 10;\n}\n\nint calcScore(const vector<vector<int>>& board) {\n    vector<vector<int>> adj(N * N);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (board[i][j] == 0) continue;\n            if (i + 1 < N && board[i+1][j] != 0 && (board[i][j] & 8) && (board[i+1][j] & 2)) {\n                adj[i*N+j].push_back((i+1)*N+j);\n                adj[(i+1)*N+j].push_back(i*N+j);\n            }\n            if (j + 1 < N && board[i][j+1] != 0 && (board[i][j] & 4) && (board[i][j+1] & 1)) {\n                adj[i*N+j].push_back(i*N+j+1);\n                adj[i*N+j+1].push_back(i*N+j);\n            }\n        }\n    }\n    vector<bool> vis(N * N, false);\n    int maxTree = 0;\n    for (int s = 0; s < N * N; s++) {\n        if (vis[s] || board[s/N][s%N] == 0) continue;\n        int cnt = 0, edges = 0;\n        queue<int> q; q.push(s); vis[s] = true;\n        while (!q.empty()) {\n            int u = q.front(); q.pop(); cnt++;\n            edges += adj[u].size();\n            for (int v : adj[u]) if (!vis[v]) { vis[v] = true; q.push(v); }\n        }\n        if (edges / 2 == cnt - 1) maxTree = max(maxTree, cnt);\n    }\n    return maxTree;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    int er, ec;\n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) {\n            board[i][j] = hexChar(s[j]);\n            if (board[i][j] == 0) { er = i; ec = j; }\n        }\n    }\n    \n    string best, cur;\n    int bestScore = calcScore(board), curScore = bestScore;\n    auto bestBoard = board; int bestEr = er, bestEc = ec;\n    \n    mt19937 rng(42);\n    auto start = chrono::steady_clock::now();\n    \n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count() < 2800) {\n        if (cur.size() >= (size_t)T || bestScore >= N * N - 1) break;\n        \n        vector<int> valid;\n        for (int d = 0; d < 4; d++) {\n            int nr = er + dr[d], nc = ec + dc[d];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N) valid.push_back(d);\n        }\n        int d = valid[rng() % valid.size()];\n        int nr = er + dr[d], nc = ec + dc[d];\n        \n        swap(board[er][ec], board[nr][nc]);\n        cur += dc_char[d];\n        int newScore = calcScore(board);\n        \n        double temp = 1.0 - (double)cur.size() / T;\n        bool accept = newScore > curScore || (rng() % 1000 < 100 * temp);\n        \n        if (accept) {\n            er = nr; ec = nc; curScore = newScore;\n            if (curScore > bestScore || (curScore == bestScore && cur.size() < best.size())) {\n                bestScore = curScore; best = cur;\n                bestBoard = board; bestEr = er; bestEc = ec;\n            }\n        } else {\n            cur.pop_back();\n            swap(board[er][ec], board[nr][nc]);\n        }\n        \n        if (cur.size() > T / 2 && rng() % 100 < 5) {\n            board = bestBoard; er = bestEr; ec = bestEc;\n            cur = best; curScore = bestScore;\n        }\n    }\n    \n    cout << best << endl;\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nint N, K;\nvector<int> a(10);\nvector<pair<ll, ll>> berries;\nvector<array<ll, 4>> cuts;\n\ninline int side(ll x1, ll y1, ll x2, ll y2, ll px, ll py) {\n    __int128 cross = (__int128)(x2 - x1) * (py - y1) - (__int128)(y2 - y1) * (px - x1);\n    if (cross > 0) return 1;\n    if (cross < 0) return -1;\n    return 0;\n}\n\nint calcScore() {\n    int numCuts = cuts.size();\n    map<vector<int>, int> pieceCount;\n    \n    for (int i = 0; i < N; i++) {\n        vector<int> sig(numCuts);\n        bool onLine = false;\n        for (int j = 0; j < numCuts; j++) {\n            int s = side(cuts[j][0], cuts[j][1], cuts[j][2], cuts[j][3], \n                        berries[i].first, berries[i].second);\n            if (s == 0) { onLine = true; break; }\n            sig[j] = s;\n        }\n        if (!onLine) pieceCount[sig]++;\n    }\n    \n    vector<int> b(11, 0);\n    for (auto& [sig, cnt] : pieceCount) {\n        if (cnt >= 1 && cnt <= 10) b[cnt]++;\n    }\n    \n    int total = 0;\n    for (int d = 1; d <= 10; d++) total += min(a[d-1], b[d]);\n    return total;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> K;\n    for (int i = 0; i < 10; i++) cin >> a[i];\n    \n    berries.resize(N);\n    for (int i = 0; i < N; i++) cin >> berries[i].first >> berries[i].second;\n    \n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    auto randLine = [&]() -> array<ll, 4> {\n        ll px = (ll)(rng() % 20001) - 10000;\n        ll py = (ll)(rng() % 20001) - 10000;\n        ll qx = (ll)(rng() % 20001) - 10000;\n        ll qy = (ll)(rng() % 20001) - 10000;\n        while (px == qx && py == qy) { qx = (ll)(rng() % 20001) - 10000; qy = (ll)(rng() % 20001) - 10000; }\n        return {px, py, qx, qy};\n    };\n    \n    auto perpBisector = [&](int i, int j) -> array<ll, 4> {\n        if (i == j) return randLine();\n        ll dx = berries[j].first - berries[i].first;\n        ll dy = berries[j].second - berries[i].second;\n        ll mx = berries[i].first + berries[j].first;\n        ll my = berries[i].second + berries[j].second;\n        ll px = mx - dy * 1000, py = my + dx * 1000;\n        ll qx = mx + dy * 1000, qy = my - dx * 1000;\n        if (px == qx && py == qy) return randLine();\n        return {px, py, qx, qy};\n    };\n    \n    auto radialLine = [&](double angle) -> array<ll, 4> {\n        ll px = (ll)(cos(angle) * 15000);\n        ll py = (ll)(sin(angle) * 15000);\n        ll qx = -px, qy = -py;\n        if (px == 0) px = 1;\n        if (qx == 0) qx = -1;\n        return {px, py, qx, qy};\n    };\n    \n    int bestScore = 0;\n    vector<array<ll, 4>> bestCuts;\n    \n    auto start = chrono::steady_clock::now();\n    \n    for (int restart = 0; ; restart++) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration_cast<chrono::milliseconds>(now - start).count();\n        if (elapsed > 2850) break;\n        \n        cuts.clear();\n        int numCuts = 20 + rng() % 30;\n        \n        // Initialize with mix of strategies\n        for (int i = 0; i < numCuts; i++) {\n            int strategy = rng() % 3;\n            if (strategy == 0) cuts.push_back(randLine());\n            else if (strategy == 1) cuts.push_back(perpBisector(rng() % N, rng() % N));\n            else cuts.push_back(radialLine((double)(rng() % 1000) / 1000.0 * M_PI * 2));\n        }\n        \n        int curScore = calcScore();\n        if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n        \n        // Local search\n        for (int iter = 0; iter < 500; iter++) {\n            now = chrono::steady_clock::now();\n            elapsed = chrono::duration_cast<chrono::milliseconds>(now - start).count();\n            if (elapsed > 2850) break;\n            \n            double temp = 5.0 * (1.0 - elapsed / 2850.0);\n            int moveType = rng() % 10;\n            \n            if (moveType < 7 && !cuts.empty()) {\n                int idx = rng() % cuts.size();\n                auto oldCut = cuts[idx];\n                int strat = rng() % 3;\n                if (strat == 0) cuts[idx] = randLine();\n                else if (strat == 1) cuts[idx] = perpBisector(rng() % N, rng() % N);\n                else cuts[idx] = radialLine((double)(rng() % 1000) / 1000.0 * M_PI * 2);\n                \n                int newScore = calcScore();\n                if (newScore >= curScore || (double)(rng() % 1000000) / 1000000.0 < exp((newScore - curScore) / max(temp, 0.1))) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else cuts[idx] = oldCut;\n            } else if (moveType < 9 && cuts.size() < (size_t)K) {\n                int strat = rng() % 3;\n                if (strat == 0) cuts.push_back(randLine());\n                else if (strat == 1) cuts.push_back(perpBisector(rng() % N, rng() % N));\n                else cuts.push_back(radialLine((double)(rng() % 1000) / 1000.0 * M_PI * 2));\n                \n                int newScore = calcScore();\n                if (newScore >= curScore || (double)(rng() % 1000000) / 1000000.0 < exp((newScore - curScore) / max(temp, 0.1))) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else cuts.pop_back();\n            } else if (cuts.size() > 5) {\n                int idx = rng() % cuts.size();\n                auto oldCut = cuts[idx];\n                cuts.erase(cuts.begin() + idx);\n                int newScore = calcScore();\n                if (newScore >= curScore || (double)(rng() % 1000000) / 1000000.0 < exp((newScore - curScore) / max(temp, 0.1))) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else cuts.insert(cuts.begin() + idx, oldCut);\n            }\n        }\n    }\n    \n    cout << bestCuts.size() << \"\\n\";\n    for (auto& c : bestCuts) cout << c[0] << \" \" << c[1] << \" \" << c[2] << \" \" << c[3] << \"\\n\";\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, c;\nset<pair<int,int>> dots;\nset<tuple<int,int,int,int>> usedSegs;\nvector<array<int, 8>> ops;\n\nbool inGrid(int x, int y) { return x >= 0 && x < N && y >= 0 && y < N; }\nlong long wt(int x, int y) { return (long long)(x-c)*(x-c) + (long long)(y-c)*(y-c) + 1; }\n\nvoid addSeg(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g == 0) return;\n    dx /= g; dy /= g;\n    for (int i = 0; i < g; i++) {\n        int a = x1+i*dx, b = y1+i*dy, e = a+dx, f = b+dy;\n        if (a > e || (a == e && b > f)) { swap(a,e); swap(b,f); }\n        usedSegs.insert({a,b,e,f});\n    }\n}\n\nbool segUsed(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g == 0) return false;\n    dx /= g; dy /= g;\n    for (int i = 0; i < g; i++) {\n        int a = x1+i*dx, b = y1+i*dy, e = a+dx, f = b+dy;\n        if (a > e || (a == e && b > f)) { swap(a,e); swap(b,f); }\n        if (usedSegs.count({a,b,e,f})) return true;\n    }\n    return false;\n}\n\nbool dotOnSeg(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g <= 1) return false;\n    dx /= g; dy /= g;\n    for (int i = 1; i < g; i++)\n        if (dots.count({x1+i*dx, y1+i*dy})) return true;\n    return false;\n}\n\nbool isValidSide(int dx, int dy) {\n    return (dx == 0 || dy == 0 || abs(dx) == abs(dy));\n}\n\nbool tryAdd(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (!inGrid(x1,y1) || dots.count({x1,y1})) return false;\n    if (!dots.count({x2,y2}) || !dots.count({x3,y3}) || !dots.count({x4,y4})) return false;\n    \n    set<pair<int,int>> corners = {{x1,y1},{x2,y2},{x3,y3},{x4,y4}};\n    if (corners.size() != 4) return false;\n    \n    int v1x = x2-x1, v1y = y2-y1, v2x = x3-x2, v2y = y3-y2;\n    if (v1x*v2x + v1y*v2y != 0) return false;\n    if (!isValidSide(v1x, v1y) || !isValidSide(v2x, v2y)) return false;\n    if (x4 != x1+v2x || y4 != y1+v2y) return false;\n    if (v1x == 0 && v1y == 0) return false;\n    \n    if (dotOnSeg(x1,y1,x2,y2) || dotOnSeg(x2,y2,x3,y3) || \n        dotOnSeg(x3,y3,x4,y4) || dotOnSeg(x4,y4,x1,y1)) return false;\n    if (segUsed(x1,y1,x2,y2) || segUsed(x2,y2,x3,y3) || \n        segUsed(x3,y3,x4,y4) || segUsed(x4,y4,x1,y1)) return false;\n    \n    dots.insert({x1,y1});\n    addSeg(x1,y1,x2,y2); addSeg(x2,y2,x3,y3); \n    addSeg(x3,y3,x4,y4); addSeg(x4,y4,x1,y1);\n    ops.push_back({x1,y1,x2,y2,x3,y3,x4,y4});\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    c = (N-1) / 2;\n    for (int i = 0; i < M; i++) { int x, y; cin >> x >> y; dots.insert({x, y}); }\n    \n    auto tstart = chrono::steady_clock::now();\n    mt19937 rng(42);\n    \n    int failCount = 0;\n    while (chrono::duration<double>(chrono::steady_clock::now() - tstart).count() < 4.5) {\n        vector<pair<int,int>> dl(dots.begin(), dots.end());\n        shuffle(dl.begin(), dl.end(), rng);\n        \n        long long bestW = -1;\n        array<int,8> best;\n        int sz = min((int)dl.size(), 150);\n        \n        for (int i = 0; i < sz && bestW < 0; i++) {\n            for (int j = 0; j < sz; j++) {\n                if (i == j) continue;\n                auto [x2, y2] = dl[i];\n                auto [x3, y3] = dl[j];\n                int vx = x3-x2, vy = y3-y2;\n                \n                // Try perpendicular vectors for p1-p2\n                vector<pair<int,int>> perps;\n                if (vx == 0 || vy == 0) { perps = {{vy, -vx}, {-vy, vx}}; }\n                else if (abs(vx) == abs(vy)) { perps = {{vy, -vx}, {-vy, vx}}; }\n                \n                for (auto [px, py] : perps) {\n                    for (int len = 1; len <= max(N, 61); len++) {\n                        int dx = (px > 0 ? len : (px < 0 ? -len : 0));\n                        int dy = (py > 0 ? len : (py < 0 ? -len : 0));\n                        if (px != 0 && py != 0) { if (abs(px) != abs(py)) continue; }\n                        else if (px == 0) dx = 0;\n                        else dy = 0;\n                        \n                        int x1 = x2 - dx, y1 = y2 - dy;\n                        int x4 = x3 - dx, y4 = y3 - dy;\n                        \n                        if (!inGrid(x1,y1) || !inGrid(x4,y4)) continue;\n                        if (dots.count({x1,y1}) || !dots.count({x4,y4})) continue;\n                        \n                        long long w = wt(x1, y1);\n                        if (w > bestW) { best = {x1,y1,x2,y2,x3,y3,x4,y4}; bestW = w; }\n                    }\n                    for (int len = 1; len <= max(N, 61); len++) {\n                        int dx = (px > 0 ? len : (px < 0 ? -len : 0));\n                        int dy = (py > 0 ? len : (py < 0 ? -len : 0));\n                        if (px != 0 && py != 0) { if (abs(px) != abs(py)) continue; }\n                        else if (px == 0) dx = 0;\n                        else dy = 0;\n                        \n                        int x4 = x3 + dx, y4 = y3 + dy;\n                        int x1 = x2 + dx, y1 = y2 + dy;\n                        \n                        if (!inGrid(x1,y1) || !inGrid(x4,y4)) continue;\n                        if (dots.count({x1,y1}) || !dots.count({x4,y4})) continue;\n                        \n                        long long w = wt(x1, y1);\n                        if (w > bestW) { best = {x1,y1,x2,y2,x3,y3,x4,y4}; bestW = w; }\n                    }\n                }\n            }\n        }\n        \n        if (bestW < 0) { if (++failCount > 50) break; continue; }\n        if (!tryAdd(best[0],best[1],best[2],best[3],best[4],best[5],best[6],best[7])) {\n            if (++failCount > 100) break;\n            continue;\n        }\n        failCount = 0;\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto& op : ops) {\n        for (int i = 0; i < 8; i++) cout << op[i] << \" \\n\"[i==7];\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 10;\n\nstruct State {\n    int grid[N][N];\n    \n    State() { memset(grid, 0, sizeof(grid)); }\n    \n    int countEmpty() const {\n        int cnt = 0;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] == 0) cnt++;\n        return cnt;\n    }\n    \n    void place(int p, int flavor) {\n        int cnt = 0;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] == 0 && ++cnt == p) { grid[i][j] = flavor; return; }\n    }\n    \n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; j++) {\n                int w = 0;\n                for (int i = 0; i < N; i++) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[w++][j] = v; }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; j++) {\n                int w = N - 1;\n                for (int i = N - 1; i >= 0; i--) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[w--][j] = v; }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; i++) {\n                int w = 0;\n                for (int j = 0; j < N; j++) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[i][w++] = v; }\n            }\n        } else {\n            for (int i = 0; i < N; i++) {\n                int w = N - 1;\n                for (int j = N - 1; j >= 0; j--) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[i][w--] = v; }\n            }\n        }\n    }\n    \n    long long calcScore() const {\n        bool vis[N][N] = {};\n        long long sum = 0;\n        int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (grid[i][j] && !vis[i][j]) {\n                    int f = grid[i][j], sz = 0;\n                    queue<pair<int,int>> q; q.push({i, j}); vis[i][j] = true;\n                    while (!q.empty()) {\n                        auto [x, y] = q.front(); q.pop(); sz++;\n                        for (int d = 0; d < 4; d++) {\n                            int nx = x + dx[d], ny = y + dy[d];\n                            if (nx >= 0 && nx < N && ny >= 0 && ny < N && !vis[nx][ny] && grid[nx][ny] == f) {\n                                vis[nx][ny] = true; q.push({nx, ny});\n                            }\n                        }\n                    }\n                    sum += (long long)sz * sz;\n                }\n            }\n        }\n        return sum;\n    }\n};\n\nmt19937 rng(12345);\nconst char dirs[] = {'F', 'B', 'L', 'R'};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int f[101];\n    for (int t = 1; t <= 100; t++) cin >> f[t];\n    \n    State state;\n    \n    for (int t = 1; t <= 100; t++) {\n        int p; cin >> p;\n        state.place(p, f[t]);\n        \n        int depth = min(12, 100 - t);\n        int numSims = 25;\n        \n        char bestDir = 'F';\n        long long bestScore = -1;\n        \n        for (char dir : dirs) {\n            long long totalScore = 0;\n            \n            for (int sim = 0; sim < numSims; sim++) {\n                State s = state;\n                s.tilt(dir);\n                \n                for (int step = 1; step <= depth && t + step <= 100; step++) {\n                    int empty = s.countEmpty();\n                    if (empty == 0) break;\n                    int randPos = (rng() % empty) + 1;\n                    s.place(randPos, f[t + step]);\n                    \n                    // Greedy tilt\n                    char simBest = 'F';\n                    long long simBestScore = -1;\n                    for (char d : dirs) {\n                        State tmp = s;\n                        tmp.tilt(d);\n                        long long sc = tmp.calcScore();\n                        if (sc > simBestScore) { simBestScore = sc; simBest = d; }\n                    }\n                    s.tilt(simBest);\n                }\n                totalScore += s.calcScore();\n            }\n            \n            if (totalScore > bestScore) {\n                bestScore = totalScore;\n                bestDir = dir;\n            }\n        }\n        \n        state.tilt(bestDir);\n        cout << bestDir << '\\n' << flush;\n    }\n    \n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\ndouble eps;\n\nvector<int> get_sorted_degrees(const string& s) {\n    vector<int> deg(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 (s[idx++] == '1') {\n                deg[i]++;\n                deg[j]++;\n            }\n        }\n    }\n    sort(deg.begin(), deg.end());\n    return deg;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    cin >> M >> eps;\n    \n    // Better N selection based on theoretical analysis\n    // Need larger N for higher noise to maintain distinguishability\n    double noise_factor = (eps < 0.001) ? 1.0 : 1.0 / max(0.2, 1.0 - 2.0 * eps);\n    \n    // Base N on M and noise\n    if (eps < 0.01) {\n        N = (int)ceil(sqrt(2.0 * M)) + 2;\n    } else if (eps < 0.05) {\n        N = (int)ceil(sqrt(2.5 * M)) + 4;\n    } else if (eps < 0.15) {\n        N = (int)ceil(sqrt(3.0 * M * noise_factor)) + 8;\n    } else if (eps < 0.25) {\n        N = (int)ceil(sqrt(4.0 * M * noise_factor)) + 15;\n    } else if (eps < 0.35) {\n        N = (int)ceil(sqrt(5.0 * M * noise_factor)) + 25;\n    } else {\n        N = (int)ceil(sqrt(6.0 * M * noise_factor)) + 35;\n    }\n    \n    N = max(N, (int)(2.0 * sqrt(M)));\n    N = max(N, 8);\n    N = min(N, 100);\n    \n    cout << N << \"\\n\";\n    \n    int total = N * (N - 1) / 2;\n    \n    vector<string> G(M);\n    vector<vector<double>> expected_deg(M);\n    \n    // Create M graphs with linearly spaced edge counts\n    for (int i = 0; i < M; i++) {\n        string s(total, '0');\n        long long edges = (M > 1) ? ((long long)i * total / (M - 1)) : 0;\n        \n        // Fill edges in a pattern that creates varied degree distribution\n        int idx = 0;\n        int filled = 0;\n        for (int a = 0; a < N && filled < edges; a++) {\n            for (int b = a + 1; b < N && filled < edges; b++) {\n                int pos = a * (2 * N - a - 1) / 2 + (b - a - 1);\n                s[pos] = '1';\n                filled++;\n            }\n        }\n        \n        G[i] = s;\n        \n        // Compute expected degree sequence after noise\n        vector<int> deg = get_sorted_degrees(s);\n        expected_deg[i].resize(N);\n        double transform = 1.0 - 2.0 * eps;\n        double base = (N - 1) * eps;\n        for (int j = 0; j < N; j++) {\n            expected_deg[i][j] = deg[j] * transform + base;\n        }\n        \n        cout << s << \"\\n\";\n    }\n    cout.flush();\n    \n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n        \n        vector<int> deg_h = get_sorted_degrees(H);\n        \n        int best = 0;\n        double best_score = 1e18;\n        \n        for (int i = 0; i < M; i++) {\n            // Weighted L2 distance - weight more heavily at extremes\n            double score = 0;\n            for (int j = 0; j < N; j++) {\n                double diff = deg_h[j] - expected_deg[i][j];\n                // Weight endpoints more (more informative)\n                double weight = 1.0 + 0.5 * (abs(j - N/2.0) / (N/2.0));\n                score += weight * diff * diff;\n            }\n            \n            if (score < best_score) {\n                best_score = score;\n                best = i;\n            }\n        }\n        \n        cout << best << \"\\n\";\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, D, K;\nvector<array<int,3>> edges;\nvector<vector<pair<int,int>>> adj;\nvector<vector<int>> adjEdge;\nmt19937 rng(42);\nconst long long INF = 1e9;\n\nvector<long long> dijkstraMask(int src, const vector<bool>& excl) {\n    vector<long long> dist(N, INF);\n    priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> pq;\n    dist[src] = 0;\n    pq.push({0, src});\n    while (!pq.empty()) {\n        auto [d, u] = pq.top(); pq.pop();\n        if (d > dist[u]) continue;\n        for (size_t i = 0; i < adj[u].size(); i++) {\n            if (excl[adjEdge[u][i]]) continue;\n            auto [v, w] = adj[u][i];\n            if (dist[u] + w < dist[v]) {\n                dist[v] = dist[u] + w;\n                pq.push({dist[v], v});\n            }\n        }\n    }\n    return dist;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    auto start = chrono::steady_clock::now();\n    \n    cin >> N >> M >> D >> K;\n    edges.resize(M); adj.resize(N); adjEdge.resize(N);\n    \n    for (int i = 0; i < M; i++) {\n        int u, v, w; cin >> u >> v >> w; u--; v--;\n        edges[i] = {u, v, w};\n        adj[u].push_back({v, w}); adj[v].push_back({u, w});\n        adjEdge[u].push_back(i); adjEdge[v].push_back(i);\n    }\n    for (int i = 0; i < N; i++) { int x, y; cin >> x >> y; }\n    \n    vector<bool> noEdge(M, false);\n    vector<long long> crit(M);\n    for (int e = 0; e < M; e++) {\n        noEdge[e] = true;\n        auto dist = dijkstraMask(edges[e][0], noEdge);\n        crit[e] = dist[edges[e][1]] - edges[e][2];\n        noEdge[e] = false;\n    }\n    \n    vector<int> order(M); iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) { return crit[a] > crit[b]; });\n    \n    vector<int> assign(M, 0);\n    vector<int> cnt(D + 1, 0);\n    vector<set<int>> dayVertices(D + 1);\n    \n    for (int e : order) {\n        int u = edges[e][0], v = edges[e][1];\n        int best = 1, bestScore = INT_MAX;\n        for (int d = 1; d <= D; d++) {\n            if (cnt[d] >= K) continue;\n            int conflict = (dayVertices[d].count(u) ? 1 : 0) + (dayVertices[d].count(v) ? 1 : 0);\n            int score = conflict * 10000 + cnt[d];\n            if (score < bestScore) { bestScore = score; best = d; }\n        }\n        assign[e] = best; cnt[best]++;\n        dayVertices[best].insert(u); dayVertices[best].insert(v);\n    }\n    \n    int numSamples = min(60, N);\n    vector<int> samples(N); iota(samples.begin(), samples.end(), 0);\n    shuffle(samples.begin(), samples.end(), rng);\n    samples.resize(numSamples);\n    \n    vector<vector<long long>> origDist(numSamples);\n    for (int i = 0; i < numSamples; i++) origDist[i] = dijkstraMask(samples[i], noEdge);\n    \n    auto evalDay = [&](int d) -> double {\n        vector<bool> excl(M);\n        for (int e = 0; e < M; e++) if (assign[e] == d) excl[e] = true;\n        double tot = 0;\n        for (int i = 0; i < numSamples; i++) {\n            auto dist = dijkstraMask(samples[i], excl);\n            for (int v = 0; v < N; v++) if (v != samples[i])\n                tot += min(dist[v], INF) - origDist[i][v];\n        }\n        return tot;\n    };\n    \n    vector<double> dayCost(D + 1);\n    double cur = 0;\n    for (int d = 1; d <= D; d++) { dayCost[d] = evalDay(d); cur += dayCost[d]; }\n    \n    double bestScore = cur;\n    vector<int> bestAssign = assign;\n    double temp = cur / D / 10;\n    \n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > 5.5) break;\n        \n        int moveType = rng() % 3;\n        \n        if (moveType < 2) {\n            int e1 = rng() % M, e2 = rng() % M;\n            if (assign[e1] == assign[e2]) continue;\n            int d1 = assign[e1], d2 = assign[e2];\n            \n            swap(assign[e1], assign[e2]);\n            double nc1 = evalDay(d1), nc2 = evalDay(d2);\n            double delta = (nc1 + nc2) - (dayCost[d1] + dayCost[d2]);\n            \n            if (delta < 0 || (double)(rng() % 1000000) / 1000000 < exp(-delta / temp)) {\n                dayCost[d1] = nc1; dayCost[d2] = nc2; cur += delta;\n                if (cur < bestScore) { bestScore = cur; bestAssign = assign; }\n            } else { swap(assign[e1], assign[e2]); }\n        } else {\n            int e = rng() % M;\n            int oldD = assign[e], newD = rng() % D + 1;\n            if (newD == oldD || cnt[newD] >= K) continue;\n            \n            assign[e] = newD; cnt[oldD]--; cnt[newD]++;\n            double nc1 = evalDay(oldD), nc2 = evalDay(newD);\n            double delta = (nc1 + nc2) - (dayCost[oldD] + dayCost[newD]);\n            \n            if (delta < 0 || (double)(rng() % 1000000) / 1000000 < exp(-delta / temp)) {\n                dayCost[oldD] = nc1; dayCost[newD] = nc2; cur += delta;\n                if (cur < bestScore) { bestScore = cur; bestAssign = assign; }\n            } else { assign[e] = oldD; cnt[oldD]++; cnt[newD]--; }\n        }\n        temp *= 0.999995;\n    }\n    \n    for (int i = 0; i < M; i++) cout << bestAssign[i] << \" \\n\"[i == M-1];\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nint D;\nstring f[2][15], r[2][15];\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D;\n    for (int i = 0; i < 2; i++) {\n        for (int k = 0; k < D; k++) cin >> f[i][k];\n        for (int k = 0; k < D; k++) cin >> r[i][k];\n    }\n    \n    vector<int> b[2];\n    for (int i = 0; i < 2; i++) b[i].assign(D * D * D, 0);\n    \n    auto idx = [&](int x, int y, int z) { return x * D * D + y * D + z; };\n    \n    // For each arrangement, find minimal cells to cover silhouettes\n    vector<tuple<int,int,int>> cells[2];\n    \n    for (int arr = 0; arr < 2; arr++) {\n        set<int> needFront, needRight;\n        for (int z = 0; z < D; z++) {\n            for (int x = 0; x < D; x++) {\n                if (f[arr][z][x] == '1') needFront.insert(z * D + x);\n            }\n            for (int y = 0; y < D; y++) {\n                if (r[arr][z][y] == '1') needRight.insert(z * D + y);\n            }\n        }\n        \n        // Greedily pick cells that cover the most uncovered constraints\n        while (!needFront.empty() || !needRight.empty()) {\n            int bestX = -1, bestY = -1, bestZ = -1, bestScore = -1;\n            \n            for (int z = 0; z < D; z++) {\n                for (int x = 0; x < D; x++) {\n                    if (f[arr][z][x] != '1') continue;\n                    for (int y = 0; y < D; y++) {\n                        if (r[arr][z][y] != '1') continue;\n                        \n                        int score = 0;\n                        if (needFront.count(z * D + x)) score++;\n                        if (needRight.count(z * D + y)) score++;\n                        \n                        if (score > bestScore) {\n                            bestScore = score;\n                            bestX = x; bestY = y; bestZ = z;\n                        }\n                    }\n                }\n            }\n            \n            if (bestScore <= 0) break;\n            \n            cells[arr].push_back({bestX, bestY, bestZ});\n            needFront.erase(bestZ * D + bestX);\n            needRight.erase(bestZ * D + bestY);\n        }\n    }\n    \n    int n1 = cells[0].size(), n2 = cells[1].size();\n    int n = max(n1, n2);\n    \n    // Assign block numbers - shared unit blocks (1x1x1 all same shape)\n    // Blocks 1..min(n1,n2) are shared, rest are unique\n    for (int i = 0; i < n1; i++) {\n        auto [x, y, z] = cells[0][i];\n        b[0][idx(x, y, z)] = i + 1;\n    }\n    for (int i = 0; i < n2; i++) {\n        auto [x, y, z] = cells[1][i];\n        b[1][idx(x, y, z)] = i + 1;\n    }\n    \n    cout << n << \"\\n\";\n    for (int i = 0; i < 2; i++) {\n        for (int j = 0; j < D * D * D; j++) {\n            if (j) cout << \" \";\n            cout << b[i][j];\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, K;\nvector<pair<int,int>> V, R;\nvector<tuple<int,int,long long>> E;\nvector<vector<pair<int,int>>> adj;\nvector<vector<double>> distVR;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    V.resize(N); R.resize(K); E.resize(M); adj.resize(N);\n    \n    for(int i = 0; i < N; i++) cin >> V[i].first >> V[i].second;\n    for(int j = 0; j < M; j++) {\n        int u, v; long long w;\n        cin >> u >> v >> w; u--; v--;\n        E[j] = {u, v, w};\n        adj[u].push_back({v, j});\n        adj[v].push_back({u, j});\n    }\n    for(int k = 0; k < K; k++) cin >> R[k].first >> R[k].second;\n    \n    distVR.resize(N, vector<double>(K));\n    for(int i = 0; i < N; i++)\n        for(int k = 0; k < K; k++) {\n            double dx = V[i].first - R[k].first, dy = V[i].second - R[k].second;\n            distVR[i][k] = sqrt(dx*dx + dy*dy);\n        }\n    \n    // Compute shortest paths from vertex 0\n    vector<long long> dist0(N, LLONG_MAX/2);\n    vector<int> parent(N, -1), parentEdge(N, -1);\n    priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> pq;\n    dist0[0] = 0; pq.push({0, 0});\n    while(!pq.empty()) {\n        auto [d, u] = pq.top(); pq.pop();\n        if(d > dist0[u]) continue;\n        for(auto [v, eid] : adj[u]) {\n            long long w = get<2>(E[eid]);\n            if(dist0[u] + w < dist0[v]) {\n                dist0[v] = dist0[u] + w;\n                parent[v] = u; parentEdge[v] = eid;\n                pq.push({dist0[v], v});\n            }\n        }\n    }\n    \n    // Assign residents considering both broadcast cost and reachability\n    vector<int> P(N, 0);\n    vector<int> assignment(K);\n    \n    for(int k = 0; k < K; k++) {\n        int best = -1; double bestCost = 1e18;\n        for(int i = 0; i < N; i++) {\n            if(distVR[i][k] > 5000) continue;\n            // Cost: broadcast cost + amortized network cost\n            double cost = distVR[i][k] * distVR[i][k] + dist0[i] * 0.01;\n            if(cost < bestCost) { bestCost = cost; best = i; }\n        }\n        assignment[k] = best;\n    }\n    \n    for(int k = 0; k < K; k++) {\n        int v = assignment[k];\n        P[v] = max(P[v], (int)ceil(distVR[v][k] - 1e-9));\n    }\n    \n    // Build tree\n    set<int> active;\n    for(int i = 0; i < N; i++) if(P[i] > 0) active.insert(i);\n    \n    vector<int> B(M, 0);\n    for(int v : active) {\n        int cur = v;\n        while(cur != 0 && parentEdge[cur] != -1) {\n            B[parentEdge[cur]] = 1;\n            cur = parent[cur];\n        }\n    }\n    \n    // Activate intermediate vertices on tree (they're reachable, might help)\n    set<int> treeVerts;\n    treeVerts.insert(0);\n    for(int v : active) {\n        int cur = v;\n        while(cur != -1) { treeVerts.insert(cur); cur = parent[cur]; }\n    }\n    \n    // Try using tree vertices to reduce costs\n    for(int iter = 0; iter < 50; iter++) {\n        bool improved = false;\n        for(int k = 0; k < K; k++) {\n            int curV = assignment[k];\n            for(int v : treeVerts) {\n                if(v == curV || distVR[v][k] > 5000) continue;\n                int newR = (int)ceil(distVR[v][k] - 1e-9);\n                int oldR = (int)ceil(distVR[curV][k] - 1e-9);\n                if(newR < oldR && newR <= 5000) {\n                    assignment[k] = v;\n                    improved = true;\n                }\n            }\n        }\n        if(!improved) break;\n        \n        fill(P.begin(), P.end(), 0);\n        for(int k = 0; k < K; k++) {\n            int v = assignment[k];\n            P[v] = max(P[v], (int)ceil(distVR[v][k] - 1e-9));\n        }\n    }\n    \n    // Output\n    for(int i = 0; i < N; i++) cout << P[i] << \" \\n\"[i==N-1];\n    for(int j = 0; j < M; j++) cout << B[j] << \" \\n\"[j==M-1];\n    \n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nint b[N][N];\nvector<tuple<int, int, int, int>> ops;\n\nvoid do_swap(int x1, int y1, int x2, int y2) {\n    ops.push_back({x1, y1, x2, y2});\n    swap(b[x1][y1], b[x2][y2]);\n}\n\nvoid sift_down(int x, int y) {\n    while (x < N - 1) {\n        int min_child_y = (b[x + 1][y + 1] < b[x + 1][y]) ? (y + 1) : y;\n        if (b[x][y] > b[x + 1][min_child_y]) {\n            do_swap(x, y, x + 1, min_child_y);\n            x = x + 1;\n            y = min_child_y;\n        } else {\n            break;\n        }\n    }\n}\n\nbool has_violation(int x, int y) {\n    if (x >= N - 1) return false;\n    return b[x][y] > b[x + 1][y] || b[x][y] > b[x + 1][y + 1];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int x = 0; x < N; x++) {\n        for (int y = 0; y <= x; y++) {\n            cin >> b[x][y];\n        }\n    }\n    \n    // Process violations iteratively - prioritize by value (larger values first)\n    bool changed = true;\n    while (changed) {\n        changed = false;\n        // Collect all violations with their values\n        vector<tuple<int, int, int>> violations; // (value, x, y)\n        for (int x = N - 2; x >= 0; x--) {\n            for (int y = 0; y <= x; y++) {\n                if (has_violation(x, y)) {\n                    violations.push_back({b[x][y], x, y});\n                }\n            }\n        }\n        \n        // Sort by value descending (fix larger values first)\n        sort(violations.rbegin(), violations.rend());\n        \n        for (auto& [val, x, y] : violations) {\n            if (has_violation(x, y)) {\n                sift_down(x, y);\n                changed = true;\n            }\n        }\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto& [x1, y1, x2, y2] : ops) {\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, ex, ey;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nvector<vector<int>> grid;\n\nvector<pair<int,int>> getReachable(bool findContainers) {\n    vector<pair<int,int>> result;\n    vector<vector<bool>> vis(D, vector<bool>(D, false));\n    queue<pair<int,int>> q;\n    q.push({ex, ey});\n    vis[ex][ey] = true;\n    \n    while (!q.empty()) {\n        auto [x, y] = q.front(); q.pop();\n        \n        if (findContainers && grid[x][y] >= 0) {\n            result.push_back({x, y});\n            continue;\n        }\n        if (!findContainers && grid[x][y] == -1 && !(x == ex && y == ey)) {\n            result.push_back({x, y});\n        }\n        if (grid[x][y] >= 0) continue;\n        \n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx >= 0 && nx < D && ny >= 0 && ny < D && !vis[nx][ny] && grid[nx][ny] != -2) {\n                vis[nx][ny] = true;\n                q.push({nx, ny});\n            }\n        }\n    }\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D >> N;\n    ex = 0; ey = (D - 1) / 2;\n    grid.assign(D, vector<int>(D, -1));\n    \n    for (int i = 0; i < N; i++) {\n        int x, y; cin >> x >> y;\n        grid[x][y] = -2;\n    }\n    \n    int total = D * D - 1 - N;\n    \n    vector<pair<int,int>> bfsOrder;\n    map<pair<int,int>, int> posToIdx;\n    {\n        vector<vector<bool>> vis(D, vector<bool>(D, false));\n        queue<pair<int,int>> q;\n        q.push({ex, ey});\n        vis[ex][ey] = true;\n        while (!q.empty()) {\n            auto [x, y] = q.front(); q.pop();\n            if (grid[x][y] == -1 && !(x == ex && y == ey)) {\n                posToIdx[{x, y}] = bfsOrder.size();\n                bfsOrder.push_back({x, y});\n            }\n            for (int d = 0; d < 4; d++) {\n                int nx = x + dx[d], ny = y + dy[d];\n                if (nx >= 0 && nx < D && ny >= 0 && ny < D && !vis[nx][ny] && grid[nx][ny] != -2) {\n                    vis[nx][ny] = true;\n                    q.push({nx, ny});\n                }\n            }\n        }\n    }\n    \n    for (int d = 0; d < total; d++) {\n        int t; cin >> t;\n        auto reach = getReachable(false);\n        \n        int targetIdx = total - 1 - t;\n        pair<int,int> best = reach[0];\n        int bestDist = abs(posToIdx[best] - targetIdx);\n        for (auto& pos : reach) {\n            int dist = abs(posToIdx[pos] - targetIdx);\n            if (dist < bestDist || (dist == bestDist && posToIdx[pos] > posToIdx[best])) {\n                bestDist = dist;\n                best = pos;\n            }\n        }\n        \n        grid[best.first][best.second] = t;\n        cout << best.first << \" \" << best.second << \"\\n\";\n        cout.flush();\n    }\n    \n    for (int i = 0; i < total; i++) {\n        auto reach = getReachable(true);\n        pair<int,int> best = reach[0];\n        for (auto& pos : reach) {\n            if (grid[pos.first][pos.second] < grid[best.first][best.second]) {\n                best = pos;\n            }\n        }\n        cout << best.first << \" \" << best.second << \"\\n\";\n        grid[best.first][best.second] = -1;\n    }\n    \n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint n, m;\nint dx[] = {0, 0, 1, -1};\nint dy[] = {1, -1, 0, 0};\n\nset<pair<int,int>> getAdj(vector<vector<int>>& g) {\n    set<pair<int,int>> adj;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            int c = g[i][j];\n            if (i == 0 || i == n-1 || j == 0 || j == n-1) {\n                int a = min(0, c), b = max(0, c);\n                if (a != b) adj.insert({a, b});\n            }\n            for (int d = 0; d < 4; d++) {\n                int ni = i + dx[d], nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = g[ni][nj];\n                    if (c != nc) {\n                        int a = min(c, nc), b = max(c, nc);\n                        adj.insert({a, b});\n                    }\n                }\n            }\n        }\n    }\n    return adj;\n}\n\nbool isConnected(vector<vector<int>>& g, int c) {\n    if (c == 0) return true;\n    int si = -1, sj = -1, cnt = 0;\n    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) {\n        if (g[i][j] == c) { if (si < 0) { si = i; sj = j; } cnt++; }\n    }\n    if (cnt == 0) return true;\n    queue<pair<int,int>> q;\n    vector<vector<bool>> vis(n, vector<bool>(n, false));\n    q.push({si, sj}); vis[si][sj] = true;\n    int found = 1;\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        for (int d = 0; d < 4; d++) {\n            int ni = i + dx[d], nj = j + dy[d];\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n && !vis[ni][nj] && g[ni][nj] == c) {\n                vis[ni][nj] = true; found++; q.push({ni, nj});\n            }\n        }\n    }\n    return found == cnt;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> n >> m;\n    vector<vector<int>> grid(n, vector<int>(n));\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < n; j++)\n            cin >> grid[i][j];\n    \n    auto origAdj = getAdj(grid);\n    vector<vector<int>> best = grid;\n    int bestScore = 0;\n    \n    // Try greedy shrinking - change cells to 0 when safe\n    auto tryGrid = grid;\n    for (int iter = 0; iter < 5; iter++) {\n        vector<pair<int,int>> cells;\n        for (int i = 0; i < n; i++) for (int j = 0; j < n; j++)\n            if (tryGrid[i][j] != 0) cells.push_back({i, j});\n        \n        shuffle(cells.begin(), cells.end(), mt19937(iter * 12345));\n        \n        for (auto [i, j] : cells) {\n            int old = tryGrid[i][j];\n            tryGrid[i][j] = 0;\n            \n            auto newAdj = getAdj(tryGrid);\n            bool valid = (newAdj == origAdj);\n            if (valid) {\n                for (int c = 1; c <= m && valid; c++)\n                    if (!isConnected(tryGrid, c)) valid = false;\n            }\n            \n            if (!valid) tryGrid[i][j] = old;\n        }\n        \n        int score = 0;\n        for (int i = 0; i < n; i++) for (int j = 0; j < n; j++)\n            if (tryGrid[i][j] == 0) score++;\n        \n        if (score > bestScore) {\n            bestScore = score;\n            best = tryGrid;\n        }\n    }\n    \n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cout << best[i][j];\n            if (j < n-1) cout << \" \";\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, D, Q;\nint query_count = 0;\n\nchar query(const vector<int>& L, const vector<int>& R) {\n    cout << L.size() << \" \" << R.size();\n    for (int x : L) cout << \" \" << x;\n    for (int x : R) cout << \" \" << x;\n    cout << \"\\n\";\n    cout.flush();\n    char c;\n    cin >> c;\n    query_count++;\n    return c;\n}\n\nvector<int> items;\n\nvoid merge_sort(int l, int r) {\n    if (r - l <= 1) return;\n    int m = (l + r) / 2;\n    merge_sort(l, m);\n    merge_sort(m, r);\n    \n    vector<int> left(items.begin() + l, items.begin() + m);\n    vector<int> right(items.begin() + m, items.begin() + r);\n    \n    int i = 0, j = 0, k = l;\n    while (i < (int)left.size() && j < (int)right.size()) {\n        if (query_count >= Q) {\n            while (i < (int)left.size()) items[k++] = left[i++];\n            while (j < (int)right.size()) items[k++] = right[j++];\n            return;\n        }\n        char c = query({left[i]}, {right[j]});\n        if (c != '>') items[k++] = left[i++];\n        else items[k++] = right[j++];\n    }\n    while (i < (int)left.size()) items[k++] = left[i++];\n    while (j < (int)right.size()) items[k++] = right[j++];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> D >> Q;\n    \n    items.resize(N);\n    iota(items.begin(), items.end(), 0);\n    merge_sort(0, N);\n    \n    // Estimate weights using remaining queries\n    vector<double> w(N);\n    for (int i = 0; i < N; i++) w[i] = i + 1;\n    \n    for (int j = N - 1; j >= N / 2 && query_count + 10 < Q; j--) {\n        int lo = 1, hi = j;\n        while (lo < hi && query_count < Q - N) {\n            int mid = (lo + hi) / 2;\n            vector<int> L, R = {items[j]};\n            for (int t = 0; t < mid; t++) L.push_back(items[t]);\n            char c = query(L, R);\n            if (c == '>' || c == '=') hi = mid;\n            else lo = mid + 1;\n        }\n        double sum = 0;\n        for (int t = 0; t < lo; t++) sum += w[t];\n        w[j] = sum;\n    }\n    \n    // Greedy assignment\n    vector<double> set_weight(D, 0);\n    vector<int> assignment(N);\n    \n    for (int i = N - 1; i >= 0; i--) {\n        int best = 0;\n        for (int j = 1; j < D; j++)\n            if (set_weight[j] < set_weight[best]) best = j;\n        assignment[items[i]] = best;\n        set_weight[best] += w[i];\n    }\n    \n    while (query_count < Q) query({items[0]}, {items[1]});\n    \n    for (int i = 0; i < N; i++)\n        cout << assignment[i] << \" \\n\"[i == N - 1];\n    \n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::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    vector<int> pos(n + 1);\n    \n    for (int i = 0; i < m; i++) {\n        int h = n / m;\n        for (int j = 0; j < h; j++) {\n            int x;\n            cin >> x;\n            stacks[i].push_back(x);\n            pos[x] = i;\n        }\n    }\n    \n    vector<pair<int, int>> ops;\n    \n    for (int v = 1; v <= n; v++) {\n        int stack_id = pos[v];\n        \n        int idx = 0;\n        while (stacks[stack_id][idx] != v) idx++;\n        \n        if (idx < (int)stacks[stack_id].size() - 1) {\n            int move_start = idx + 1;\n            int bottom_box = stacks[stack_id][move_start];\n            \n            int max_moving = 0;\n            int min_moving = INT_MAX;\n            for (int j = move_start; j < (int)stacks[stack_id].size(); j++) {\n                max_moving = max(max_moving, stacks[stack_id][j]);\n                min_moving = min(min_moving, stacks[stack_id][j]);\n            }\n            \n            int best_dest = -1;\n            int best_score = INT_MIN;\n            \n            for (int i = 0; i < m; i++) {\n                if (i == stack_id) continue;\n                \n                int score = 0;\n                \n                if (stacks[i].empty()) {\n                    // Empty stack - excellent, no re-moves from below\n                    score = n * 2 + 100;\n                } else {\n                    int min_in_dest = INT_MAX;\n                    for (int b : stacks[i]) {\n                        min_in_dest = min(min_in_dest, b);\n                    }\n                    \n                    if (min_in_dest > min_moving) {\n                        // Great! All dest boxes extracted after our min\n                        // Our group won't be moved again due to dest boxes\n                        score = n * 2;\n                    } else {\n                        // We'll be moved when extracting min_in_dest\n                        // Prefer later moves (higher min_in_dest)\n                        score = min_in_dest;\n                    }\n                    \n                    // Bonus if our group integrates well (top > max_moving)\n                    if (stacks[i].back() > max_moving) {\n                        score += 30;\n                    }\n                }\n                \n                // Penalty for tall stacks\n                score -= (int)stacks[i].size() * 2;\n                \n                if (score > best_score) {\n                    best_score = score;\n                    best_dest = i;\n                }\n            }\n            \n            ops.push_back({bottom_box, best_dest + 1});\n            \n            for (int j = move_start; j < (int)stacks[stack_id].size(); j++) {\n                int box = stacks[stack_id][j];\n                stacks[best_dest].push_back(box);\n                pos[box] = best_dest;\n            }\n            stacks[stack_id].resize(move_start);\n        }\n        \n        ops.push_back({v, 0});\n        stacks[stack_id].pop_back();\n    }\n    \n    for (auto& [a, b] : ops) {\n        cout << a << \" \" << b << \"\\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 dirChar[] = {'R', 'D', 'L', 'U'};\n\nbool canMove(int i, int j, int dir) {\n    int ni = i + di[dir];\n    int nj = j + dj[dir];\n    if (ni < 0 || ni >= N || nj < 0 || nj >= N) return false;\n    if (dir == 0) return v[i][j] == '0';\n    else if (dir == 1) return h[i][j] == '0';\n    else if (dir == 2) return j > 0 && v[i][j-1] == '0';\n    else return i > 0 && h[i-1][j] == '0';\n}\n\nlong double evaluate(const string& path) {\n    int L = path.size();\n    vector<vector<int>> lastVisit(N, vector<int>(N, -L));\n    lastVisit[0][0] = 0;\n    \n    long double totalSum = 0;\n    int ci = 0, cj = 0;\n    \n    for (int t = 1; t <= 2 * L; t++) {\n        char c = path[(t - 1) % L];\n        int dir = (c == 'R') ? 0 : (c == 'D') ? 1 : (c == 'L') ? 2 : 3;\n        ci += di[dir]; cj += dj[dir];\n        \n        if (t >= L) {\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (i == ci && j == cj) continue;\n                    totalSum += (long double)d[i][j] * (t - lastVisit[i][j]);\n                }\n            }\n        }\n        lastVisit[ci][cj] = t;\n    }\n    return totalSum / L;\n}\n\nstring generatePath(bool highFirst) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    string path;\n    \n    function<void(int, int)> dfs = [&](int i, int j) {\n        visited[i][j] = true;\n        vector<pair<int, int>> children;\n        for (int dir = 0; dir < 4; dir++) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj] && canMove(i, j, dir)) {\n                children.push_back({d[ni][nj], dir});\n            }\n        }\n        if (highFirst) sort(children.rbegin(), children.rend());\n        else sort(children.begin(), children.end());\n        \n        for (auto [dval, dir] : children) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (!visited[ni][nj]) {\n                path += dirChar[dir];\n                dfs(ni, nj);\n                path += dirChar[(dir + 2) % 4];\n            }\n        }\n    };\n    dfs(0, 0);\n    return path;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> 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    string bestPath;\n    long double bestScore = 1e18;\n    \n    // Try both orderings\n    for (int highFirst = 0; highFirst <= 1; highFirst++) {\n        string path = generatePath(highFirst);\n        long double score = evaluate(path);\n        if (score < bestScore) {\n            bestScore = score;\n            bestPath = path;\n        }\n    }\n    \n    // Try adding extra loops for very high-d cells if we have room\n    int maxLen = 100000;\n    if (bestPath.size() < maxLen - 4 * N) {\n        // Find highest d cell and path to it\n        int maxD = 0, mi = 0, mj = 0;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (d[i][j] > maxD) { maxD = d[i][j]; mi = i; mj = j; }\n        \n        // BFS to find path from (0,0) to (mi,mj)\n        vector<vector<int>> parent(N, vector<int>(N, -1));\n        queue<pair<int,int>> q;\n        q.push({0, 0});\n        parent[0][0] = -2;\n        while (!q.empty()) {\n            auto [i, j] = q.front(); q.pop();\n            if (i == mi && j == mj) break;\n            for (int dir = 0; dir < 4; dir++) {\n                int ni = i + di[dir], nj = j + dj[dir];\n                if (ni >= 0 && ni < N && nj >= 0 && nj < N && parent[ni][nj] == -1 && canMove(i, j, dir)) {\n                    parent[ni][nj] = (dir + 2) % 4;\n                    q.push({ni, nj});\n                }\n            }\n        }\n        \n        string toTarget, fromTarget;\n        int ci = mi, cj = mj;\n        while (ci != 0 || cj != 0) {\n            int pdir = parent[ci][cj];\n            fromTarget += dirChar[pdir];\n            toTarget += dirChar[(pdir + 2) % 4];\n            ci += di[pdir]; cj += dj[pdir];\n        }\n        reverse(toTarget.begin(), toTarget.end());\n        \n        string extraLoop = toTarget + fromTarget;\n        while (bestPath.size() + extraLoop.size() <= maxLen) {\n            string candidate = bestPath + extraLoop;\n            long double score = evaluate(candidate);\n            if (score < bestScore) {\n                bestScore = score;\n                bestPath = candidate;\n            } else break;\n        }\n    }\n    \n    cout << bestPath << endl;\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nint overlap(const string& a, const string& b) {\n    int maxOv = min((int)a.length(), (int)b.length());\n    for (int ov = maxOv; ov >= 1; ov--) {\n        if (a.substr(a.length() - ov) == b.substr(0, ov)) {\n            return ov;\n        }\n    }\n    return 0;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, si, sj;\n    cin >> N >> M >> si >> sj;\n    \n    vector<string> A(N);\n    map<char, vector<pair<int,int>>> charPos;\n    for (int i = 0; i < N; i++) {\n        cin >> A[i];\n        for (int j = 0; j < N; j++) {\n            charPos[A[i][j]].push_back({i, j});\n        }\n    }\n    \n    vector<string> t(M);\n    for (int i = 0; i < M; i++) {\n        cin >> t[i];\n    }\n    \n    // Greedy superstring construction\n    vector<string> remaining = t;\n    \n    while (remaining.size() > 1) {\n        int bestOv = -1;\n        int bestI = -1, bestJ = -1;\n        \n        for (int i = 0; i < (int)remaining.size(); i++) {\n            for (int j = 0; j < (int)remaining.size(); j++) {\n                if (i != j) {\n                    int ov = overlap(remaining[i], remaining[j]);\n                    if (ov > bestOv) {\n                        bestOv = ov;\n                        bestI = i;\n                        bestJ = j;\n                    }\n                }\n            }\n        }\n        \n        string merged = remaining[bestI] + remaining[bestJ].substr(bestOv);\n        \n        vector<string> newRemaining;\n        for (int k = 0; k < (int)remaining.size(); k++) {\n            if (k != bestI && k != bestJ) {\n                if (merged.find(remaining[k]) == string::npos) {\n                    newRemaining.push_back(remaining[k]);\n                }\n            }\n        }\n        newRemaining.push_back(merged);\n        remaining = newRemaining;\n    }\n    \n    string superstring = remaining[0];\n    \n    // Type the superstring using nearest neighbor\n    int curI = si, curJ = sj;\n    \n    for (char c : superstring) {\n        int bestDist = INT_MAX;\n        int bI = -1, bJ = -1;\n        for (auto [i, j] : charPos[c]) {\n            int dist = abs(i - curI) + abs(j - curJ);\n            if (dist < bestDist) {\n                bestDist = dist;\n                bI = i;\n                bJ = j;\n            }\n        }\n        cout << bI << \" \" << bJ << \"\\n\";\n        curI = bI;\n        curJ = bJ;\n    }\n    \n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\ndouble eps;\nvector<vector<pair<int,int>>> shapes;\nvector<vector<int>> grid;\n\nint queryDrill(int i, int j) {\n    cout << \"q 1 \" << i << \" \" << j << \"\\n\" << flush;\n    int v; cin >> v;\n    grid[i][j] = v;\n    return v;\n}\n\nint queryDivine(const vector<pair<int,int>>& cells) {\n    cout << \"q \" << cells.size();\n    for (auto& [i, j] : cells) cout << \" \" << i << \" \" << j;\n    cout << \"\\n\" << flush;\n    int v; cin >> v;\n    return v;\n}\n\nint submit(const set<pair<int,int>>& oil) {\n    cout << \"a \" << oil.size();\n    for (auto& [i, j] : oil) cout << \" \" << i << \" \" << j;\n    cout << \"\\n\" << flush;\n    int r; cin >> r;\n    return r;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> eps;\n    shapes.resize(M);\n    for (int m = 0; m < M; m++) {\n        int d; cin >> d;\n        shapes[m].resize(d);\n        for (int i = 0; i < d; i++) {\n            cin >> shapes[m][i].first >> shapes[m][i].second;\n        }\n    }\n    \n    grid.assign(N, vector<int>(N, -1));\n    set<pair<int,int>> has_oil;\n    \n    // When eps is small, use row divination first\n    vector<int> rowEstimate(N, -1);\n    if (eps <= 0.1) {\n        for (int i = 0; i < N; i++) {\n            vector<pair<int,int>> row;\n            for (int j = 0; j < N; j++) row.push_back({i, j});\n            int est = queryDivine(row);\n            rowEstimate[i] = est;\n        }\n    }\n    \n    // Drill cells - prioritize rows with higher estimates\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    if (eps <= 0.1) {\n        sort(order.begin(), order.end(), [&](int a, int b) {\n            return rowEstimate[a] > rowEstimate[b];\n        });\n    }\n    \n    for (int i : order) {\n        for (int j = 0; j < N; j++) {\n            int v = queryDrill(i, j);\n            if (v > 0) has_oil.insert({i, j});\n        }\n    }\n    \n    submit(has_oil);\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    for (int d = 0; d < D; d++) {\n        vector<int> h(N);\n        int totalH = 0;\n        \n        // Calculate minimum height needed for each reservation\n        for (int k = 0; k < N; k++) {\n            h[k] = (a[d][k] + W - 1) / W;  // ceil(a[k] / W)\n            if (h[k] == 0) h[k] = 1;\n            totalH += h[k];\n        }\n        \n        if (totalH > W) {\n            int excess = totalH - W;\n            \n            // Calculate slack for each: extra area at current height\n            vector<pair<int, int>> slack(N);\n            for (int k = 0; k < N; k++) {\n                slack[k] = {h[k] * W - a[d][k], k};\n            }\n            sort(slack.begin(), slack.end(), greater<pair<int,int>>());\n            \n            // Reduce heights of those with most slack first\n            for (int i = 0; i < N && excess > 0; i++) {\n                int k = slack[i].second;\n                while (h[k] > 1 && excess > 0) {\n                    int newSlack = (h[k] - 1) * W - a[d][k];\n                    if (newSlack >= 0) {\n                        h[k]--;\n                        excess--;\n                    } else {\n                        break;\n                    }\n                }\n            }\n            \n            // If still excess, reduce even with penalties (larger reservations last)\n            for (int k = 0; k < N && excess > 0; k++) {\n                while (h[k] > 1 && excess > 0) {\n                    h[k]--;\n                    excess--;\n                }\n            }\n        } else if (totalH < W) {\n            int extra = W - totalH;\n            // Distribute extra space, prioritizing larger reservations\n            while (extra > 0) {\n                for (int k = N - 1; k >= 0 && extra > 0; k--) {\n                    h[k]++;\n                    extra--;\n                }\n            }\n        }\n        \n        // Output rectangles\n        int y = 0;\n        for (int k = 0; k < N; k++) {\n            cout << y << \" 0 \" << y + h[k] << \" \" << W << \"\\n\";\n            y += h[k];\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long P = 998244353;\nint N, M, K;\nvector<vector<long long>> a_init;\nvector<array<array<long long, 3>, 3>> stamps;\n\nlong long calcScore(const vector<vector<long long>>& a) {\n    long long s = 0;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            s += a[i][j];\n    return s;\n}\n\nvoid applyOp(vector<vector<long long>>& a, int m, int p, int q) {\n    for (int i = 0; i < 3; i++)\n        for (int j = 0; j < 3; j++)\n            a[p+i][q+j] = (a[p+i][q+j] + stamps[m][i][j]) % P;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    cin >> N >> M >> K;\n    a_init.assign(N, vector<long long>(N));\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            cin >> a_init[i][j];\n            a_init[i][j] %= P;\n        }\n    \n    stamps.resize(M);\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    auto start = chrono::steady_clock::now();\n    \n    vector<tuple<int,int,int>> best_ops;\n    long long best_score = calcScore(a_init);\n    \n    mt19937 rng(42);\n    \n    for (int trial = 0; chrono::duration<double>(chrono::steady_clock::now() - start).count() < 1.8; trial++) {\n        vector<tuple<int,int,int>> ops;\n        auto a = a_init;\n        \n        // Greedy with randomness\n        for (int op = 0; op < K; op++) {\n            vector<tuple<long long, int, int, int>> cands;\n            for (int m = 0; m < M; m++)\n                for (int p = 0; p <= N-3; p++)\n                    for (int q = 0; q <= N-3; q++) {\n                        long long gain = 0;\n                        for (int i = 0; i < 3; i++)\n                            for (int j = 0; j < 3; j++)\n                                gain += (a[p+i][q+j] + stamps[m][i][j]) % P - a[p+i][q+j];\n                        if (gain > 0) cands.push_back({gain, m, p, q});\n                    }\n            if (cands.empty()) break;\n            sort(cands.rbegin(), cands.rend());\n            int pick = (trial == 0) ? 0 : rng() % min((int)cands.size(), 2 + trial/2);\n            auto [g, m, p, q] = cands[pick];\n            applyOp(a, m, p, q);\n            ops.push_back({m, p, q});\n        }\n        \n        long long score = calcScore(a);\n        \n        // Local optimization: try replacing each operation\n        for (int iter = 0; iter < 3 && chrono::duration<double>(chrono::steady_clock::now() - start).count() < 1.8; iter++) {\n            bool improved = false;\n            for (int idx = 0; idx < (int)ops.size(); idx++) {\n                auto orig = ops[idx];\n                \n                // Rebuild state without operation idx\n                auto a2 = a_init;\n                for (int k = 0; k < (int)ops.size(); k++)\n                    if (k != idx) {\n                        auto [m,p,q] = ops[k];\n                        applyOp(a2, m, p, q);\n                    }\n                \n                long long bestGain = 0;\n                int bm=-1, bp=-1, bq=-1;\n                for (int m = 0; m < M; m++)\n                    for (int p = 0; p <= N-3; p++)\n                        for (int q = 0; q <= N-3; q++) {\n                            long long gain = 0;\n                            for (int i = 0; i < 3; i++)\n                                for (int j = 0; j < 3; j++)\n                                    gain += (a2[p+i][q+j] + stamps[m][i][j]) % P - a2[p+i][q+j];\n                            if (gain > bestGain) { bestGain = gain; bm=m; bp=p; bq=q; }\n                        }\n                \n                if (bm != -1 && (bm != get<0>(orig) || bp != get<1>(orig) || bq != get<2>(orig))) {\n                    ops[idx] = {bm, bp, bq};\n                    applyOp(a2, bm, bp, bq);\n                    long long ns = calcScore(a2);\n                    if (ns > score) {\n                        score = ns;\n                        a = a2;\n                        improved = true;\n                    } else {\n                        ops[idx] = orig;\n                    }\n                }\n            }\n            \n            // Try adding more operations\n            while (ops.size() < (size_t)K) {\n                long long bestGain = 0;\n                int bm=-1, bp=-1, bq=-1;\n                for (int m = 0; m < M; m++)\n                    for (int p = 0; p <= N-3; p++)\n                        for (int q = 0; q <= N-3; q++) {\n                            long long gain = 0;\n                            for (int i = 0; i < 3; i++)\n                                for (int j = 0; j < 3; j++)\n                                    gain += (a[p+i][q+j] + stamps[m][i][j]) % P - a[p+i][q+j];\n                            if (gain > bestGain) { bestGain = gain; bm=m; bp=p; bq=q; }\n                        }\n                if (bm == -1) break;\n                applyOp(a, bm, bp, bq);\n                ops.push_back({bm, bp, bq});\n                score += bestGain;\n                improved = true;\n            }\n            \n            if (!improved) break;\n        }\n        \n        if (score > best_score) {\n            best_score = score;\n            best_ops = ops;\n        }\n    }\n    \n    cout << best_ops.size() << \"\\n\";\n    for (auto& [m,p,q] : best_ops) cout << m << \" \" << p << \" \" << q << \"\\n\";\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 5;\nint A[N][N];\nint grid[N][N];\nint cr[N], cc[N], hold[N];\nint next_in[N];\nstring ans[N];\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n; cin >> n;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            cin >> A[i][j];\n    \n    memset(grid, -1, sizeof(grid));\n    memset(hold, -1, sizeof(hold));\n    memset(next_in, 0, sizeof(next_in));\n    for (int i = 0; i < N; i++) { cr[i] = i; cc[i] = 0; }\n    \n    for (int t = 0; t < 5000; t++) {\n        // Step 1: Bring in 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 c = 0; c < N; c++)\n                    if (cr[c] == i && cc[c] == 0 && hold[c] != -1)\n                        blocked = true;\n                if (!blocked) grid[i][0] = A[i][next_in[i]++];\n            }\n        }\n        \n        // Decide moves\n        char moves[N];\n        for (int c = 0; c < N; c++) moves[c] = '.';\n        \n        for (int c = 0; c < N; c++) {\n            int r = cr[c], col = cc[c];\n            \n            if (hold[c] == -1) {\n                if (grid[r][col] != -1) {\n                    moves[c] = 'P';\n                } else if (col > 0) {\n                    moves[c] = 'L';\n                }\n            } else {\n                int target_row = hold[c] / N;\n                if (col < N-1) {\n                    bool can_move = (c == 0 || grid[r][col+1] == -1);\n                    if (can_move) moves[c] = 'R';\n                } else {\n                    moves[c] = 'Q';\n                }\n            }\n        }\n        \n        // Step 2: Execute moves\n        for (int c = 0; c < N; c++) {\n            char m = moves[c];\n            if (m == 'P') {\n                hold[c] = grid[cr[c]][cc[c]];\n                grid[cr[c]][cc[c]] = -1;\n            } else if (m == 'Q') {\n                grid[cr[c]][cc[c]] = hold[c];\n                hold[c] = -1;\n            } else if (m == 'R') cc[c]++;\n            else if (m == 'L') cc[c]--;\n            else if (m == 'U') cr[c]--;\n            else if (m == 'D') cr[c]++;\n        }\n        \n        // Step 3: Dispatch\n        for (int i = 0; i < N; i++) grid[i][N-1] = -1;\n        \n        for (int c = 0; c < N; c++) ans[c] += moves[c];\n        \n        // Check if done\n        bool done = true;\n        for (int i = 0; i < N; i++) if (next_in[i] < N) done = false;\n        for (int c = 0; c < N; c++) if (hold[c] != -1) done = false;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] != -1) done = false;\n        if (done) break;\n    }\n    \n    // Trim trailing dots\n    size_t maxlen = 0;\n    for (int i = 0; i < N; i++) maxlen = max(maxlen, ans[i].size());\n    \n    while (maxlen > 1) {\n        bool all_dot = true;\n        for (int i = 0; i < N; i++) {\n            if (ans[i].size() >= maxlen && ans[i][maxlen-1] != '.') all_dot = false;\n        }\n        if (!all_dot) break;\n        maxlen--;\n        for (int i = 0; i < N; i++)\n            if (ans[i].size() > maxlen) ans[i].resize(maxlen);\n    }\n    \n    for (int i = 0; i < N; i++) cout << ans[i] << \"\\n\";\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<vector<int>> h;\nvector<string> ops;\nint cx = 0, cy = 0;\nint load = 0;\n\nvoid move_one(char dir) {\n    ops.push_back(string(1, dir));\n    if (dir == 'U') cx--;\n    else if (dir == 'D') cx++;\n    else if (dir == 'L') cy--;\n    else if (dir == 'R') cy++;\n}\n\nvoid move_to(int tx, int ty) {\n    while (cx < tx) move_one('D');\n    while (cx > tx) move_one('U');\n    while (cy < ty) move_one('R');\n    while (cy > ty) move_one('L');\n}\n\nvoid do_load(int d) {\n    if (d <= 0) return;\n    ops.push_back(\"+\" + to_string(d));\n    load += d;\n    h[cx][cy] -= d;\n}\n\nvoid do_unload(int d) {\n    if (d <= 0) return;\n    ops.push_back(\"-\" + to_string(d));\n    load -= d;\n    h[cx][cy] += d;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    h.resize(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    while (true) {\n        int si = -1, sj = -1, best_dist = INT_MAX;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (h[i][j] > 0) {\n                    int dist = abs(i - cx) + abs(j - cy);\n                    if (dist < best_dist) {\n                        best_dist = dist;\n                        si = i;\n                        sj = j;\n                    }\n                }\n            }\n        }\n        \n        if (si == -1) break;\n        \n        move_to(si, sj);\n        do_load(h[cx][cy]);\n        \n        while (load > 0) {\n            int ti = -1, tj = -1;\n            best_dist = INT_MAX;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h[i][j] < 0) {\n                        int dist = abs(i - cx) + abs(j - cy);\n                        if (dist < best_dist) {\n                            best_dist = dist;\n                            ti = i;\n                            tj = j;\n                        }\n                    }\n                }\n            }\n            \n            if (ti == -1) break;\n            \n            move_to(ti, tj);\n            do_unload(min(load, -h[cx][cy]));\n        }\n    }\n    \n    for (const auto& op : ops) {\n        cout << op << \"\\n\";\n    }\n    \n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \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, 0));\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    for (int t = 0; t < T; t++) {\n        // Find max value for each criterion\n        vector<int> maxVal(M, -1);\n        for (int l = 0; l < M; l++) {\n            for (int i = 0; i < seed_count; i++) {\n                maxVal[l] = max(maxVal[l], X[i][l]);\n            }\n        }\n        \n        // Calculate score for each seed (bonus for having max values)\n        vector<pair<double, int>> seed_scores(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            double score = 0;\n            for (int l = 0; l < M; l++) {\n                if (X[i][l] == maxVal[l]) {\n                    score += 1000;\n                }\n                score += X[i][l];\n            }\n            seed_scores[i] = {score, i};\n        }\n        \n        sort(seed_scores.begin(), seed_scores.end(), greater<pair<double, int>>());\n        \n        vector<int> selected(N * N);\n        for (int i = 0; i < N * N; i++) {\n            selected[i] = seed_scores[i].second;\n        }\n        \n        auto getValue = [&](int idx) {\n            int total = 0;\n            for (int l = 0; l < M; l++) total += X[idx][l];\n            return total;\n        };\n        \n        sort(selected.begin(), selected.end(), [&](int a, int b) {\n            return getValue(a) > getValue(b);\n        });\n        \n        vector<pair<int, int>> pos_order;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                pos_order.push_back({i, j});\n            }\n        }\n        \n        double cx = (N - 1) / 2.0;\n        double cy = (N - 1) / 2.0;\n        sort(pos_order.begin(), pos_order.end(), [&](auto& a, auto& b) {\n            double da = abs(a.first - cx) + abs(a.second - cy);\n            double db = abs(b.first - cx) + abs(b.second - cy);\n            if (da != db) return da < db;\n            if (a.first != b.first) return a.first < b.first;\n            return a.second < b.second;\n        });\n        \n        vector<vector<int>> A(N, vector<int>(N, -1));\n        for (int i = 0; i < N * N; i++) {\n            A[pos_order[i].first][pos_order[i].second] = selected[i];\n        }\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << A[i][j];\n                if (j < N - 1) cout << \" \";\n                else cout << \"\\n\";\n            }\n        }\n        cout.flush();\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\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, V;\nconst int DX[] = {0, 1, 0, -1};\nconst int DY[] = {1, 0, -1, 0};\n\nint rx, ry;\nvector<int> dirs;\nvector<bool> holding;\nint numF;\n\npair<int,int> fingertip(int i) { return {rx + DX[dirs[i]], ry + DY[dirs[i]]}; }\nbool valid(int x, int y) { return x >= 0 && x < N && y >= 0 && y < N; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> V;\n    vector<string> grid(N), target(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    for (int i = 0; i < N; i++) cin >> target[i];\n    \n    numF = min(V - 1, 4);\n    cout << numF + 1 << \"\\n\";\n    for (int i = 1; i <= numF; i++) cout << \"0 1\\n\";\n    cout << \"0 0\\n\";\n    \n    rx = ry = 0;\n    dirs.assign(numF, 0);\n    holding.assign(numF, false);\n    \n    set<pair<int,int>> pickup, dropS;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] == '1' && target[i][j] == '0') pickup.insert({i, j});\n            if (target[i][j] == '1' && grid[i][j] == '0') dropS.insert({i, j});\n        }\n    \n    vector<string> ops;\n    \n    auto makeOp = [&](char mv, vector<char>& rot, vector<char>& act) {\n        string s; s += mv;\n        for (int i = 0; i < numF; i++) s += rot[i];\n        s += '.';\n        for (int i = 0; i < numF; i++) s += act[i];\n        ops.push_back(s);\n    };\n    \n    while (ops.size() < 95000 && (!pickup.empty() || !dropS.empty() || \n           any_of(holding.begin(), holding.end(), [](bool h){return h;}))) {\n        \n        vector<char> rot(numF, '.'), act(numF, '.');\n        bool acted = false;\n        \n        // Try pick/drop at current positions\n        for (int i = 0; i < numF; i++) {\n            auto [fx, fy] = fingertip(i);\n            if (!valid(fx, fy)) continue;\n            if (!holding[i] && pickup.count({fx, fy})) {\n                act[i] = 'P'; pickup.erase({fx, fy}); holding[i] = true; acted = true;\n            } else if (holding[i] && dropS.count({fx, fy})) {\n                act[i] = 'P'; dropS.erase({fx, fy}); holding[i] = false; acted = true;\n            }\n        }\n        if (acted) { makeOp('.', rot, act); continue; }\n        \n        // Find best target for any fingertip\n        int bestDist = INT_MAX, bestF = -1, bestDir = -1;\n        pair<int,int> bestTarget;\n        bool forDrop = false;\n        \n        for (int i = 0; i < numF; i++) {\n            auto& targets = holding[i] ? dropS : pickup;\n            for (auto& t : targets) {\n                for (int d = 0; d < 4; d++) {\n                    int nrx = t.first - DX[d], nry = t.second - DY[d];\n                    if (!valid(nrx, nry)) continue;\n                    int dist = abs(nrx - rx) + abs(nry - ry);\n                    if (dirs[i] != d) dist++;\n                    if (dist < bestDist) {\n                        bestDist = dist; bestF = i; bestDir = d; \n                        bestTarget = t; forDrop = holding[i];\n                    }\n                }\n            }\n        }\n        \n        if (bestF == -1) break;\n        \n        int trx = bestTarget.first - DX[bestDir], tr_y = bestTarget.second - DY[bestDir];\n        char mv = '.';\n        \n        // Move towards target root position\n        if (rx < trx && valid(rx + 1, ry)) { mv = 'D'; rx++; }\n        else if (rx > trx && valid(rx - 1, ry)) { mv = 'U'; rx--; }\n        else if (ry < tr_y && valid(rx, ry + 1)) { mv = 'R'; ry++; }\n        else if (ry > tr_y && valid(rx, ry - 1)) { mv = 'L'; ry--; }\n        \n        // Rotate fingertip towards target direction\n        if (dirs[bestF] != bestDir) {\n            int diff = (bestDir - dirs[bestF] + 4) % 4;\n            if (diff == 1) { rot[bestF] = 'R'; dirs[bestF] = (dirs[bestF] + 1) % 4; }\n            else if (diff == 3) { rot[bestF] = 'L'; dirs[bestF] = (dirs[bestF] + 3) % 4; }\n            else { rot[bestF] = 'R'; dirs[bestF] = (dirs[bestF] + 1) % 4; }\n        }\n        \n        if (mv == '.' && rot[bestF] == '.') {\n            // Stuck - try any move\n            if (valid(rx + 1, ry)) { mv = 'D'; rx++; }\n            else if (valid(rx - 1, ry)) { mv = 'U'; rx--; }\n            else if (valid(rx, ry + 1)) { mv = 'R'; ry++; }\n            else if (valid(rx, ry - 1)) { mv = 'L'; ry--; }\n        }\n        \n        makeOp(mv, rot, act);\n    }\n    \n    for (auto& op : ops) cout << op << \"\\n\";\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::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    for (int i = 0; i < N; i++)\n        cin >> sardine[i].first >> sardine[i].second;\n    \n    vector<int> xs, ys;\n    for (auto& p : mackerel) { xs.push_back(p.first); ys.push_back(p.second); }\n    for (auto& p : sardine) { xs.push_back(p.first); ys.push_back(p.second); }\n    \n    sort(xs.begin(), xs.end()); xs.erase(unique(xs.begin(), xs.end()), xs.end());\n    sort(ys.begin(), ys.end()); ys.erase(unique(ys.begin(), ys.end()), ys.end());\n    \n    int nx = xs.size(), ny = ys.size();\n    map<int, int> x_idx, y_idx;\n    for (int i = 0; i < nx; i++) x_idx[xs[i]] = i;\n    for (int i = 0; i < ny; i++) y_idx[ys[i]] = i;\n    \n    vector<vector<int>> grid(ny + 1, vector<int>(nx + 1, 0));\n    \n    for (auto& p : mackerel)\n        grid[y_idx[p.second] + 1][x_idx[p.first] + 1]++;\n    for (auto& p : sardine)\n        grid[y_idx[p.second] + 1][x_idx[p.first] + 1]--;\n    \n    // Build 2D prefix sum\n    for (int i = 1; i <= ny; i++)\n        for (int j = 1; j <= nx; j++)\n            grid[i][j] += grid[i-1][j] + grid[i][j-1] - grid[i-1][j-1];\n    \n    auto query = [&](int y1, int x1, int y2, int x2) -> int {\n        return grid[y2+1][x2+1] - grid[y1][x2+1] - grid[y2+1][x1] + grid[y1][x1];\n    };\n    \n    int best_score = 0;\n    int bx1 = 0, by1 = 0, bx2 = 0, by2 = 0;\n    \n    mt19937 rng(42);\n    \n    // Random sampling\n    for (int iter = 0; iter < 500000; iter++) {\n        int i1 = rng() % N, i2 = rng() % N;\n        int x1i = x_idx[mackerel[i1].first];\n        int y1i = y_idx[mackerel[i1].second];\n        int x2i = x_idx[mackerel[i2].first];\n        int y2i = y_idx[mackerel[i2].second];\n        \n        if (x1i > x2i) swap(x1i, x2i);\n        if (y1i > y2i) swap(y1i, y2i);\n        \n        int score = query(y1i, x1i, y2i, x2i);\n        if (score > best_score) {\n            best_score = score;\n            bx1 = x1i; by1 = y1i; bx2 = x2i; by2 = y2i;\n        }\n    }\n    \n    // Local search\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int dx1 : {-1, 0, 1}) {\n            for (int dy1 : {-1, 0, 1}) {\n                for (int dx2 : {-1, 0, 1}) {\n                    for (int dy2 : {-1, 0, 1}) {\n                        int nx1 = bx1 + dx1, ny1 = by1 + dy1;\n                        int nx2 = bx2 + dx2, ny2 = by2 + dy2;\n                        if (nx1 < 0 || ny1 < 0 || nx2 >= nx || ny2 >= ny) continue;\n                        if (nx1 > nx2 || ny1 > ny2) continue;\n                        int score = query(ny1, nx1, ny2, nx2);\n                        if (score > best_score) {\n                            best_score = score;\n                            bx1 = nx1; by1 = ny1; bx2 = nx2; by2 = ny2;\n                            improved = true;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    int outx1 = xs[bx1], outy1 = ys[by1];\n    int outx2 = xs[bx2], outy2 = ys[by2];\n    \n    if (best_score == 0) {\n        outx1 = 0; outy1 = 0; outx2 = 1; outy2 = 1;\n    }\n    \n    cout << 4 << \"\\n\";\n    cout << outx1 << \" \" << outy1 << \"\\n\";\n    cout << outx2 << \" \" << outy1 << \"\\n\";\n    cout << outx2 << \" \" << outy2 << \"\\n\";\n    cout << outx1 << \" \" << outy2 << \"\\n\";\n    \n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nlong long sigma;\nvector<long long> w, h;\n\nstruct PlacedRect { long long x1, y1, x2, y2; int id; };\n\ntuple<long long, long long> simulate(const vector<tuple<int,int,char,int>>& ops) {\n    vector<PlacedRect> placed;\n    long long W = 0, H = 0;\n    for (auto& [p, r, d, b] : ops) {\n        long long rw = w[p], rh = h[p];\n        if (r) swap(rw, rh);\n        long long x = 0, y = 0;\n        if (d == 'U') {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n            for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n        } else {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n            for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n        }\n        placed.push_back({x, y, x + rw, y + rh, p});\n        W = max(W, x + rw); H = max(H, y + rh);\n    }\n    return {W, H};\n}\n\nmt19937 rng(12345);\n\nvector<tuple<int,int,char,int>> genGreedy() {\n    vector<tuple<int,int,char,int>> ops;\n    vector<PlacedRect> placed;\n    long long curW = 0, curH = 0;\n    for (int i = 0; i < N; i++) {\n        long long best = LLONG_MAX; tuple<int,char,int> bc = {0,'U',-1};\n        for (int r = 0; r < 2; r++) for (char d : {'U','L'}) for (int b = -1; b < i; b++) {\n            long long rw = w[i], rh = h[i]; if (r) swap(rw, rh);\n            long long x = 0, y = 0;\n            if (d == 'U') {\n                if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n                for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n            } else {\n                if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n                for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n            }\n            long long sc = max(curW, x+rw) + max(curH, y+rh);\n            if (sc < best) { best = sc; bc = {r, d, b}; }\n        }\n        auto [r, d, b] = bc;\n        long long rw = w[i], rh = h[i]; if (r) swap(rw, rh);\n        long long x = 0, y = 0;\n        if (d == 'U') {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n            for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n        } else {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n            for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n        }\n        placed.push_back({x, y, x+rw, y+rh, i}); curW = max(curW, x+rw); curH = max(curH, y+rh);\n        ops.push_back({i, r, d, b});\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> genStrip(char dir, int rotMode) {\n    vector<tuple<int,int,char,int>> ops;\n    for (int i = 0; i < N; i++) {\n        int r = (rotMode == 0) ? 0 : (rotMode == 1) ? 1 : (w[i] > h[i] ? 1 : 0);\n        ops.push_back({i, r, dir, -1});\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> genChain(char dir) {\n    vector<tuple<int,int,char,int>> ops;\n    for (int i = 0; i < N; i++) {\n        int r = (dir == 'U') ? (w[i] < h[i] ? 1 : 0) : (h[i] < w[i] ? 1 : 0);\n        ops.push_back({i, r, dir, i > 0 ? i-1 : -1});\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> mutate(vector<tuple<int,int,char,int>> ops, int intensity = 1) {\n    int numMut = intensity + rng() % (intensity + 2);\n    for (int m = 0; m < numMut; m++) {\n        int i = rng() % N;\n        auto& [p, r, d, b] = ops[i];\n        int choice = rng() % 3;\n        if (choice == 0) r = 1 - r;\n        else if (choice == 1) d = (d == 'U') ? 'L' : 'U';\n        else b = (int)(rng() % (i + 1)) - 1;\n    }\n    return ops;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> T >> sigma;\n    w.resize(N); h.resize(N);\n    for (int i = 0; i < N; i++) cin >> w[i] >> h[i];\n    \n    vector<pair<long long, vector<tuple<int,int,char,int>>>> candidates;\n    \n    auto addCandidate = [&](vector<tuple<int,int,char,int>> ops) {\n        auto [sw, sh] = simulate(ops);\n        candidates.push_back({sw + sh, ops});\n    };\n    \n    addCandidate(genGreedy());\n    addCandidate(genStrip('U', 0));\n    addCandidate(genStrip('U', 1));\n    addCandidate(genStrip('U', 2));\n    addCandidate(genStrip('L', 0));\n    addCandidate(genStrip('L', 1));\n    addCandidate(genStrip('L', 2));\n    addCandidate(genChain('U'));\n    addCandidate(genChain('L'));\n    \n    sort(candidates.begin(), candidates.end());\n    auto bestOps = candidates[0].second;\n    long long bestSim = candidates[0].first;\n    \n    // Hill climbing with simulated annealing\n    for (int iter = 0; iter < 20000 && (int)candidates.size() < T * 2; iter++) {\n        int srcIdx = (rng() % 100 < 70) ? 0 : rng() % min((int)candidates.size(), 5);\n        auto ops = mutate(candidates[srcIdx].second, 1 + iter / 5000);\n        auto [sw, sh] = simulate(ops);\n        long long score = sw + sh;\n        \n        double threshold = bestSim * (1.0 + 0.1 * exp(-iter / 3000.0));\n        if (score <= threshold) {\n            candidates.push_back({score, ops});\n            if (score < bestSim) { \n                bestSim = score; \n                bestOps = ops;\n            }\n        }\n    }\n    \n    sort(candidates.begin(), candidates.end());\n    if ((int)candidates.size() > T) candidates.resize(T);\n    \n    while ((int)candidates.size() < T) {\n        auto ops = mutate(bestOps, 2);\n        auto [sw, sh] = simulate(ops);\n        candidates.push_back({sw + sh, ops});\n    }\n    \n    sort(candidates.begin(), candidates.end());\n    \n    long long bestObserved = LLONG_MAX;\n    int bestObservedIdx = 0;\n    \n    for (int t = 0; t < T; t++) {\n        vector<tuple<int,int,char,int>>* ops;\n        if (t < (int)candidates.size()) {\n            ops = &candidates[t].second;\n        } else {\n            // Generate new mutation based on best observed\n            static vector<tuple<int,int,char,int>> tempOps;\n            tempOps = mutate(candidates[bestObservedIdx].second, 2);\n            ops = &tempOps;\n        }\n        \n        cout << ops->size() << \"\\n\";\n        for (auto& [p, r, d, b] : *ops) cout << p << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        cout.flush();\n        \n        long long W, H; \n        cin >> W >> H;\n        \n        if (W + H < bestObserved) {\n            bestObserved = W + H;\n            bestObservedIdx = t < (int)candidates.size() ? t : bestObservedIdx;\n        }\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<int> parent_arr;\nvector<int> depth_arr;\n\nvoid dfs(int u) {\n    // Sort neighbors by descending beauty - visit high beauty first to place them deep\n    vector<pair<int, int>> neighbors;\n    for (int v : adj[u]) {\n        if (depth_arr[v] == -1) {\n            neighbors.push_back({-A[v], v}); // negative for descending sort\n        }\n    }\n    sort(neighbors.begin(), neighbors.end());\n    \n    for (auto& [neg_beauty, v] : neighbors) {\n        if (depth_arr[v] == -1 && depth_arr[u] < H) {\n            parent_arr[v] = u;\n            depth_arr[v] = depth_arr[u] + 1;\n            dfs(v);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> H;\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    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    parent_arr.resize(N, -1);\n    depth_arr.resize(N, -1);\n    \n    // Sort vertices by ascending beauty - low beauty vertices become roots first\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return A[a] < A[b];\n    });\n    \n    // Build trees using DFS from low-beauty roots\n    for (int start : order) {\n        if (depth_arr[start] != -1) continue;\n        \n        depth_arr[start] = 0;\n        parent_arr[start] = -1;\n        dfs(start);\n    }\n    \n    // Output\n    for (int i = 0; i < N; i++) {\n        cout << parent_arr[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\n\nstruct State {\n    vector<string> board;\n    vector<pair<char,int>> ops;\n    \n    void L(int r) { ops.push_back({'L', r}); for (int j = 0; j < N-1; j++) board[r][j] = board[r][j+1]; board[r][N-1] = '.'; }\n    void R(int r) { ops.push_back({'R', r}); for (int j = N-1; j > 0; j--) board[r][j] = board[r][j-1]; board[r][0] = '.'; }\n    void U(int c) { ops.push_back({'U', c}); for (int i = 0; i < N-1; i++) board[i][c] = board[i+1][c]; board[N-1][c] = '.'; }\n    void D(int c) { ops.push_back({'D', c}); for (int i = N-1; i > 0; i--) board[i][c] = board[i-1][c]; board[0][c] = '.'; }\n    \n    int count_oni() {\n        int c = 0;\n        for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (board[i][j] == 'x') c++;\n        return c;\n    }\n    \n    void apply(int type, int idx, int dist) {\n        if (type == 0) { for (int t = 0; t < dist; t++) U(idx); for (int t = 0; t < dist; t++) D(idx); }\n        else if (type == 1) { for (int t = 0; t < dist; t++) D(idx); for (int t = 0; t < dist; t++) U(idx); }\n        else if (type == 2) { for (int t = 0; t < dist; t++) L(idx); for (int t = 0; t < dist; t++) R(idx); }\n        else { for (int t = 0; t < dist; t++) R(idx); for (int t = 0; t < dist; t++) L(idx); }\n    }\n};\n\nstruct Batch { int type, idx, dist, cnt; };\n\nvector<Batch> get_batches(const vector<string>& board) {\n    vector<Batch> batches;\n    for (int j = 0; j < N; j++) {\n        int first_fuku = N;\n        for (int i = 0; i < N; i++) if (board[i][j] == 'o') { first_fuku = i; break; }\n        int last_oni = -1, cnt = 0;\n        for (int i = 0; i < first_fuku; i++) if (board[i][j] == 'x') { last_oni = i; cnt++; }\n        if (cnt > 0) batches.push_back({0, j, last_oni + 1, cnt});\n        \n        int last_fuku = -1;\n        for (int i = N-1; i >= 0; i--) if (board[i][j] == 'o') { last_fuku = i; break; }\n        int first_oni = N; cnt = 0;\n        for (int i = N-1; i > last_fuku; i--) if (board[i][j] == 'x') { first_oni = i; cnt++; }\n        if (cnt > 0) batches.push_back({1, j, N - first_oni, cnt});\n    }\n    for (int i = 0; i < N; i++) {\n        int first_fuku = N;\n        for (int j = 0; j < N; j++) if (board[i][j] == 'o') { first_fuku = j; break; }\n        int last_oni = -1, cnt = 0;\n        for (int j = 0; j < first_fuku; j++) if (board[i][j] == 'x') { last_oni = j; cnt++; }\n        if (cnt > 0) batches.push_back({2, i, last_oni + 1, cnt});\n        \n        int last_fuku = -1;\n        for (int j = N-1; j >= 0; j--) if (board[i][j] == 'o') { last_fuku = j; break; }\n        int first_oni = N; cnt = 0;\n        for (int j = N-1; j > last_fuku; j--) if (board[i][j] == 'x') { first_oni = j; cnt++; }\n        if (cnt > 0) batches.push_back({3, i, N - first_oni, cnt});\n    }\n    return batches;\n}\n\nvector<pair<char,int>> solve(vector<string> init_board, int strategy, mt19937& rng) {\n    State st;\n    st.board = init_board;\n    \n    while (st.count_oni() > 0) {\n        auto batches = get_batches(st.board);\n        if (batches.empty()) break;\n        \n        int best = -1;\n        double best_score = 1e18;\n        \n        for (int i = 0; i < (int)batches.size(); i++) {\n            auto& b = batches[i];\n            double score;\n            if (strategy == 0) score = (double)(2 * b.dist) / b.cnt;\n            else if (strategy == 1) score = (double)(2 * b.dist) / b.cnt + (rng() % 1000) * 0.0001;\n            else if (strategy == 2) score = (double)(2 * b.dist) / (b.cnt * b.cnt);\n            else if (strategy == 3) score = b.dist;\n            else if (strategy == 4) score = (double)b.dist / b.cnt;\n            else score = (double)(2 * b.dist) / b.cnt - b.cnt * 0.01;\n            \n            if (score < best_score) { best_score = score; best = i; }\n        }\n        \n        st.apply(batches[best].type, batches[best].idx, batches[best].dist);\n    }\n    \n    return st.ops;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    vector<string> board(N);\n    for (int i = 0; i < N; i++) cin >> board[i];\n    \n    mt19937 rng(42);\n    vector<pair<char,int>> best_ops;\n    \n    for (int trial = 0; trial < 200; trial++) {\n        int strategy = (trial < 6) ? trial : 1;\n        auto ops = solve(board, strategy, rng);\n        if (best_ops.empty() || ops.size() < best_ops.size()) {\n            best_ops = ops;\n        }\n    }\n    \n    for (auto& [d, p] : best_ops) cout << d << \" \" << p << \"\\n\";\n    \n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, L;\nvector<int> T;\n\nlong long simulate(const vector<int>& a, const vector<int>& b, vector<int>& t) {\n    fill(t.begin(), t.end(), 0);\n    int x = 0;\n    for (int week = 0; week < L; week++) {\n        t[x]++;\n        x = (t[x] & 1) ? a[x] : b[x];\n    }\n    long long error = 0;\n    for (int i = 0; i < N; i++) {\n        error += abs(t[i] - T[i]);\n    }\n    return error;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> L;\n    T.resize(N);\n    for (int i = 0; i < N; i++) cin >> T[i];\n    \n    mt19937 rng(42);\n    \n    vector<int> weighted;\n    for (int i = 0; i < N; i++) {\n        int cnt = max(1, T[i] / 100);\n        for (int j = 0; j < cnt; j++) weighted.push_back(i);\n    }\n    \n    vector<int> sorted_idx(N);\n    iota(sorted_idx.begin(), sorted_idx.end(), 0);\n    sort(sorted_idx.begin(), sorted_idx.end(), [](int a, int b) { return T[a] > T[b]; });\n    \n    vector<int> best_a(N), best_b(N), t(N);\n    long long global_best = LLONG_MAX;\n    \n    auto start = chrono::steady_clock::now();\n    double time_limit = 1.85;\n    \n    for (int restart = 0; ; restart++) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > time_limit) break;\n        \n        vector<int> a(N), b(N);\n        \n        if (restart == 0) {\n            for (int i = 0; i < N; i++) {\n                a[sorted_idx[i]] = sorted_idx[(i + 1) % N];\n                b[sorted_idx[i]] = sorted_idx[(i + 1) % N];\n            }\n        } else {\n            for (int i = 0; i < N; i++) {\n                a[i] = weighted[rng() % weighted.size()];\n                b[i] = weighted[rng() % weighted.size()];\n            }\n        }\n        \n        long long cur_error = simulate(a, b, t);\n        long long local_best = cur_error;\n        vector<int> local_a = a, local_b = b;\n        \n        double restart_budget = min(0.25, (time_limit - elapsed) * 0.7);\n        double restart_start = elapsed;\n        \n        while (true) {\n            now = chrono::steady_clock::now();\n            elapsed = chrono::duration<double>(now - start).count();\n            if (elapsed > time_limit || elapsed - restart_start > restart_budget) break;\n            \n            double progress = (elapsed - restart_start) / restart_budget;\n            double temp = 2000.0 * pow(0.0001, progress);\n            \n            int i = rng() % N;\n            int old_a = a[i], old_b = b[i];\n            \n            int choice = rng() % 4;\n            if (choice == 0) {\n                a[i] = rng() % N;\n            } else if (choice == 1) {\n                b[i] = rng() % N;\n            } else if (choice == 2) {\n                a[i] = weighted[rng() % weighted.size()];\n            } else {\n                b[i] = weighted[rng() % weighted.size()];\n            }\n            \n            long long new_error = simulate(a, b, t);\n            double delta = new_error - cur_error;\n            \n            if (delta <= 0 || exp(-delta / temp) > (rng() % 1000000) / 1000000.0) {\n                cur_error = new_error;\n                if (new_error < local_best) {\n                    local_best = new_error;\n                    local_a = a;\n                    local_b = b;\n                }\n            } else {\n                a[i] = old_a;\n                b[i] = old_b;\n            }\n        }\n        \n        if (local_best < global_best) {\n            global_best = local_best;\n            best_a = local_a;\n            best_b = local_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 queries_used = 0;\nint Q_limit;\n\nvector<pair<int,int>> query(vector<int> cities) {\n    if (queries_used >= Q_limit || cities.size() < 2) return {};\n    cout << \"? \" << cities.size();\n    for (int c : cities) cout << \" \" << c;\n    cout << endl;\n    \n    vector<pair<int,int>> edges;\n    for (size_t i = 0; i + 1 < cities.size(); i++) {\n        int a, b;\n        cin >> a >> b;\n        edges.emplace_back(a, b);\n    }\n    queries_used++;\n    return edges;\n}\n\ndouble estDist(double x1, double y1, double x2, double y2) {\n    return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));\n}\n\nuint64_t morton(double px, double py) {\n    uint32_t ix = (uint32_t)(px);\n    uint32_t iy = (uint32_t)(py);\n    uint64_t result = 0;\n    for (int i = 0; i < 16; i++) {\n        result |= ((uint64_t)((ix >> i) & 1) << (2 * i));\n        result |= ((uint64_t)((iy >> i) & 1) << (2 * i + 1));\n    }\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    Q_limit = Q;\n    \n    vector<int> G(M);\n    for (int i = 0; i < M; i++) cin >> G[i];\n    \n    vector<double> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        x[i] = (lx + rx) / 2.0;\n        y[i] = (ly + ry) / 2.0;\n    }\n    \n    // Use Morton code for better 2D locality\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return morton(x[a], y[a]) < morton(x[b], y[b]);\n    });\n    \n    vector<vector<int>> groups(M);\n    int idx = 0;\n    for (int i = 0; i < M; i++) {\n        for (int j = 0; j < G[i]; j++) {\n            groups[i].push_back(order[idx++]);\n        }\n    }\n    \n    vector<vector<pair<int,int>>> edges(M);\n    \n    for (int k = 0; k < M; k++) {\n        int g = groups[k].size();\n        if (g == 1) continue;\n        \n        // Sort within group for better query locality\n        sort(groups[k].begin(), groups[k].end(), [&](int a, int b) {\n            return morton(x[a], y[a]) < morton(x[b], y[b]);\n        });\n        \n        vector<pair<int,int>> all_edges;\n        \n        if (g <= L && queries_used < Q) {\n            edges[k] = query(groups[k]);\n        } else {\n            int step = max(1, L - 1);  // Overlap by 1\n            for (int i = 0; i < g && queries_used < Q; i += step) {\n                int end = min(i + L, g);\n                if (end - i >= 2) {\n                    vector<int> subset(groups[k].begin() + i, groups[k].begin() + end);\n                    auto e = query(subset);\n                    all_edges.insert(all_edges.end(), e.begin(), e.end());\n                }\n                if (end >= g) break;\n            }\n            \n            map<int, int> city_to_local;\n            for (int i = 0; i < g; i++) city_to_local[groups[k][i]] = i;\n            \n            vector<int> parent(g);\n            iota(parent.begin(), parent.end(), 0);\n            function<int(int)> find = [&](int u) -> int {\n                return parent[u] == u ? u : parent[u] = find(parent[u]);\n            };\n            \n            // Sort edges by estimated distance for Kruskal\n            sort(all_edges.begin(), all_edges.end(), [&](auto& a, auto& b) {\n                double da = estDist(x[a.first], y[a.first], x[a.second], y[a.second]);\n                double db = estDist(x[b.first], y[b.first], x[b.second], y[b.second]);\n                return da < db;\n            });\n            \n            for (auto& e : all_edges) {\n                int u = city_to_local[e.first];\n                int v = city_to_local[e.second];\n                if (find(u) != find(v)) {\n                    parent[find(u)] = find(v);\n                    edges[k].push_back(e);\n                }\n            }\n            \n            // Fallback: connect components using shortest estimated edges\n            while ((int)edges[k].size() < g - 1) {\n                double best_dist = 1e18;\n                int best_u = -1, best_v = -1;\n                for (int i = 0; i < g; i++) {\n                    for (int j = i + 1; j < g; j++) {\n                        if (find(i) != find(j)) {\n                            double d = estDist(x[groups[k][i]], y[groups[k][i]], \n                                             x[groups[k][j]], y[groups[k][j]]);\n                            if (d < best_dist) {\n                                best_dist = d;\n                                best_u = i;\n                                best_v = j;\n                            }\n                        }\n                    }\n                }\n                if (best_u >= 0) {\n                    parent[find(best_u)] = find(best_v);\n                    edges[k].push_back({groups[k][best_u], groups[k][best_v]});\n                } else break;\n            }\n        }\n    }\n    \n    cout << \"!\" << endl;\n    for (int k = 0; k < M; k++) {\n        for (int c : groups[k]) cout << c << \" \";\n        cout << \"\\n\";\n        for (auto& e : edges[k]) {\n            cout << e.first << \" \" << e.second << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc046":"#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<pair<int, int>> targets(M);\n    for (int i = 0; i < M; i++) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n    \n    vector<string> actions;\n    int curR = targets[0].first, curC = targets[0].second;\n    \n    for (int i = 1; i < M; i++) {\n        int tR = targets[i].first, tC = targets[i].second;\n        \n        int moveCost = abs(tR - curR) + abs(tC - curC);\n        int bestCost = moveCost;\n        int bestStrategy = 0;\n        \n        // Edge target strategies (slide directly to target on edge)\n        if (tR == 0 && curR > 0) {\n            int cost = abs(tC - curC) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 1; }\n        }\n        if (tR == N - 1 && curR < N - 1) {\n            int cost = abs(tC - curC) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 2; }\n        }\n        if (tC == 0 && curC > 0) {\n            int cost = abs(tR - curR) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 3; }\n        }\n        if (tC == N - 1 && curC < N - 1) {\n            int cost = abs(tR - curR) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 4; }\n        }\n        \n        // Slide-first strategies (slide to edge first, then move to target)\n        if (curR > 0) {\n            int cost = 1 + tR + abs(tC - curC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 5; }\n        }\n        if (curR < N - 1) {\n            int cost = 1 + (N - 1 - tR) + abs(tC - curC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 6; }\n        }\n        if (curC > 0) {\n            int cost = 1 + tC + abs(tR - curR);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 7; }\n        }\n        if (curC < N - 1) {\n            int cost = 1 + (N - 1 - tC) + abs(tR - curR);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 8; }\n        }\n        \n        switch (bestStrategy) {\n            case 0:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                break;\n            case 1:\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                actions.push_back(\"S U\"); curR = 0;\n                break;\n            case 2:\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                actions.push_back(\"S D\"); curR = N - 1;\n                break;\n            case 3:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                actions.push_back(\"S L\"); curC = 0;\n                break;\n            case 4:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                actions.push_back(\"S R\"); curC = N - 1;\n                break;\n            case 5:\n                actions.push_back(\"S U\"); curR = 0;\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                break;\n            case 6:\n                actions.push_back(\"S D\"); curR = N - 1;\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                break;\n            case 7:\n                actions.push_back(\"S L\"); curC = 0;\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                break;\n            case 8:\n                actions.push_back(\"S R\"); curC = N - 1;\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                break;\n        }\n    }\n    \n    for (const string& action : actions) {\n        cout << action << \"\\n\";\n    }\n    \n    return 0;\n}"},"4":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int W = 10000;\nint n;\nvector<int> px, py, rr;\nint a[201], b[201], c[201], d[201];\n\nbool canExpand(int i, int dir) {\n    int na = a[i], nb = b[i], nc = c[i], nd = d[i];\n    if (dir == 0) na--;\n    else if (dir == 1) nc++;\n    else if (dir == 2) nb--;\n    else nd++;\n    \n    if (na < 0 || nc > W || nb < 0 || nd > W) return false;\n    \n    for (int j = 0; j < n; j++) {\n        if (i == j) continue;\n        if (!(nc <= a[j] || c[j] <= na || nd <= b[j] || d[j] <= nb)) return false;\n    }\n    return true;\n}\n\nvoid expand(int i, int dir) {\n    if (dir == 0) a[i]--;\n    else if (dir == 1) c[i]++;\n    else if (dir == 2) b[i]--;\n    else d[i]++;\n}\n\nlong long area(int i) {\n    return (long long)(c[i] - a[i]) * (d[i] - b[i]);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> n;\n    px.resize(n); py.resize(n); rr.resize(n);\n    \n    for (int i = 0; i < n; i++) {\n        cin >> px[i] >> py[i] >> rr[i];\n        a[i] = px[i]; b[i] = py[i]; c[i] = px[i]+1; d[i] = py[i]+1;\n    }\n    \n    auto start = chrono::high_resolution_clock::now();\n    \n    while (true) {\n        auto now = chrono::high_resolution_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > 4.8) break;\n        \n        bool changed = false;\n        \n        vector<int> order(n);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(), [&](int i, int j) {\n            return rr[i] - area(i) > rr[j] - area(j);\n        });\n        \n        for (int i : order) {\n            for (int dir = 0; dir < 4; dir++) {\n                if (canExpand(i, dir)) {\n                    expand(i, dir);\n                    changed = true;\n                }\n            }\n        }\n        \n        if (!changed) break;\n    }\n    \n    // Shrink rectangles that are too big\n    for (int iter = 0; iter < 1000; iter++) {\n        for (int i = 0; i < n; i++) {\n            if (area(i) <= rr[i]) continue;\n            for (int dir = 0; dir < 4; dir++) {\n                int na = a[i], nb = b[i], nc = c[i], nd = d[i];\n                if (dir == 0) na++;\n                else if (dir == 1) nc--;\n                else if (dir == 2) nb++;\n                else nd--;\n                \n                if (na >= nc || nb >= nd) continue;\n                if (!(na <= px[i] && px[i] < nc && nb <= py[i] && py[i] < nd)) continue;\n                \n                long long newArea = (long long)(nc - na) * (nd - nb);\n                if (newArea >= rr[i]) {\n                    a[i] = na; b[i] = nb; c[i] = nc; d[i] = nd;\n                }\n            }\n        }\n    }\n    \n    for (int i = 0; i < n; i++) {\n        cout << a[i] << \" \" << b[i] << \" \" << c[i] << \" \" << d[i] << \"\\n\";\n    }\n    \n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dc[] = {'U', 'D', 'L', 'R'};\n\nint t[N][N], p[N][N];\nint si, sj;\nmt19937 rng(42);\n\nint countMoves(int x, int y, const bitset<2500>& used) {\n    int cnt = 0;\n    for (int d = 0; d < 4; d++) {\n        int nx = x + dx[d], ny = y + dy[d];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N && !used[t[nx][ny]]) cnt++;\n    }\n    return cnt;\n}\n\nint countMoves2(int x, int y, const bitset<2500>& used) {\n    int cnt = 0;\n    for (int d = 0; d < 4; d++) {\n        int nx = x + dx[d], ny = y + dy[d];\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N || used[t[nx][ny]]) continue;\n        cnt++;\n        for (int d2 = 0; d2 < 4; d2++) {\n            int nnx = nx + dx[d2], nny = ny + dy[d2];\n            if (nnx >= 0 && nnx < N && nny >= 0 && nny < N && \n                !used[t[nnx][nny]] && t[nnx][nny] != t[nx][ny]) cnt++;\n        }\n    }\n    return cnt;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> si >> sj;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) cin >> t[i][j];\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) cin >> p[i][j];\n    \n    struct State {\n        int x, y, score, priority;\n        bitset<2500> usedTiles;\n        string path;\n    };\n    \n    string bestPath = \"\";\n    int bestScore = 0;\n    auto startTime = chrono::steady_clock::now();\n    \n    const int BEAM_WIDTH = 700;\n    vector<State> beam;\n    State init;\n    init.x = si; init.y = sj;\n    init.score = p[si][sj];\n    init.usedTiles.set(t[si][sj]);\n    init.path = \"\";\n    init.priority = init.score * 1000 + countMoves2(si, sj, init.usedTiles);\n    beam.push_back(init);\n    bestScore = init.score;\n    \n    while (!beam.empty()) {\n        if (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() > 1800) {\n            for (const auto& state : beam) {\n                if (state.score > bestScore) {\n                    bestScore = state.score;\n                    bestPath = state.path;\n                }\n            }\n            break;\n        }\n        \n        vector<State> nextBeam;\n        nextBeam.reserve(beam.size() * 4);\n        \n        for (const auto& state : beam) {\n            bool canExtend = false;\n            for (int d = 0; d < 4; d++) {\n                int nx = state.x + dx[d];\n                int ny = state.y + dy[d];\n                if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                if (state.usedTiles[t[nx][ny]]) continue;\n                \n                canExtend = true;\n                State newState;\n                newState.x = nx; newState.y = ny;\n                newState.score = state.score + p[nx][ny];\n                newState.usedTiles = state.usedTiles;\n                newState.usedTiles.set(t[nx][ny]);\n                newState.path = state.path + dc[d];\n                \n                int futureMoves = countMoves2(nx, ny, newState.usedTiles);\n                newState.priority = newState.score * 1000 + futureMoves * 5;\n                nextBeam.push_back(move(newState));\n            }\n            if (!canExtend && state.score > bestScore) {\n                bestScore = state.score;\n                bestPath = state.path;\n            }\n        }\n        \n        if (nextBeam.size() > BEAM_WIDTH) {\n            nth_element(nextBeam.begin(), nextBeam.begin() + BEAM_WIDTH, nextBeam.end(),\n                [](const State& a, const State& b) { return a.priority > b.priority; });\n            nextBeam.resize(BEAM_WIDTH);\n        }\n        \n        beam = move(nextBeam);\n    }\n    \n    // Random greedy with remaining time\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() < 1950) {\n        int x = si, y = sj;\n        int score = p[si][sj];\n        string path = \"\";\n        bitset<2500> usedTiles;\n        usedTiles.set(t[si][sj]);\n        \n        while (true) {\n            vector<tuple<int, int, int>> moves;\n            for (int d = 0; d < 4; d++) {\n                int nx = x + dx[d];\n                int ny = y + dy[d];\n                if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                if (usedTiles[t[nx][ny]]) continue;\n                bitset<2500> tmpUsed = usedTiles;\n                tmpUsed.set(t[nx][ny]);\n                int fm = countMoves2(nx, ny, tmpUsed);\n                moves.push_back({p[nx][ny] * 100 + fm * 5, d, p[nx][ny]});\n            }\n            if (moves.empty()) break;\n            sort(moves.begin(), moves.end(), greater<tuple<int,int,int>>());\n            \n            int choice = 0;\n            if (moves.size() > 1 && rng() % 100 < 25) {\n                choice = rng() % min((int)moves.size(), 2);\n            }\n            \n            int d = get<1>(moves[choice]);\n            x += dx[d]; y += dy[d];\n            score += p[x][y];\n            usedTiles.set(t[x][y]);\n            path += dc[d];\n        }\n        if (score > bestScore) {\n            bestScore = score;\n            bestPath = path;\n        }\n    }\n    \n    cout << bestPath << endl;\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\ndouble h[N][N-1], v[N-1][N];\nint h_cnt[N][N-1], v_cnt[N-1][N];\ndouble h_row[N], v_col[N];\nint h_row_cnt[N], v_col_cnt[N];\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    fill(&h[0][0], &h[0][0] + N*(N-1), 5000.0);\n    fill(&v[0][0], &v[0][0] + (N-1)*N, 5000.0);\n    fill(&h_cnt[0][0], &h_cnt[0][0] + N*(N-1), 0);\n    fill(&v_cnt[0][0], &v_cnt[0][0] + (N-1)*N, 0);\n    fill(h_row, h_row + N, 5000.0);\n    fill(v_col, v_col + N, 5000.0);\n    fill(h_row_cnt, h_row_cnt + N, 0);\n    fill(v_col_cnt, v_col_cnt + N, 0);\n    \n    auto getH = [&](int i, int j) {\n        if (h_cnt[i][j] > 0) return h[i][j];\n        if (h_row_cnt[i] > 0) return h_row[i];\n        return 5000.0;\n    };\n    \n    auto getV = [&](int i, int j) {\n        if (v_cnt[i][j] > 0) return v[i][j];\n        if (v_col_cnt[j] > 0) return v_col[j];\n        return 5000.0;\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 idx = [](int i, int j) { return i * N + j; };\n        vector<double> dist(N*N, 1e18);\n        vector<int> prv(N*N, -1);\n        \n        priority_queue<pair<double,int>, vector<pair<double,int>>, greater<>> pq;\n        dist[idx(si, sj)] = 0;\n        pq.push({0, idx(si, sj)});\n        \n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u]) continue;\n            int i = u / N, j = u % N;\n            \n            auto relax = [&](int ni, int nj, double w) {\n                int nu = idx(ni, nj);\n                if (dist[u] + w < dist[nu]) {\n                    dist[nu] = dist[u] + w;\n                    prv[nu] = u;\n                    pq.push({dist[nu], nu});\n                }\n            };\n            \n            if (i > 0) relax(i-1, j, getV(i-1, j));\n            if (i < N-1) relax(i+1, j, getV(i, j));\n            if (j > 0) relax(i, j-1, getH(i, j-1));\n            if (j < N-1) relax(i, j+1, getH(i, j));\n        }\n        \n        string path = \"\";\n        vector<tuple<int, int, int>> edges;\n        \n        int cur = idx(ti, tj);\n        while (prv[cur] != -1) {\n            int ci = cur / N, cj = cur % N;\n            int pi = prv[cur] / N, pj = prv[cur] % N;\n            \n            if (ci < pi) { path += 'U'; edges.emplace_back(1, ci, cj); }\n            else if (ci > pi) { path += 'D'; edges.emplace_back(1, pi, pj); }\n            else if (cj < pj) { path += 'L'; edges.emplace_back(0, ci, cj); }\n            else { path += 'R'; edges.emplace_back(0, pi, pj); }\n            \n            cur = prv[cur];\n        }\n        \n        reverse(path.begin(), path.end());\n        cout << path << \"\\n\" << flush;\n        \n        int feedback;\n        cin >> feedback;\n        \n        double est = 0;\n        for (auto& [t, ei, ej] : edges) {\n            est += (t == 0) ? getH(ei, ej) : getV(ei, ej);\n        }\n        \n        double ratio = feedback / est;\n        \n        for (auto& [t, ei, ej] : edges) {\n            double implied = (t == 0) ? getH(ei, ej) * ratio : getV(ei, ej) * ratio;\n            \n            if (t == 0) {\n                int cnt = ++h_cnt[ei][ej];\n                double alpha = 1.0 / (1.0 + cnt);\n                h[ei][ej] = h[ei][ej] * (1 - alpha) + implied * alpha;\n            } else {\n                int cnt = ++v_cnt[ei][ej];\n                double alpha = 1.0 / (1.0 + cnt);\n                v[ei][ej] = v[ei][ej] * (1 - alpha) + implied * alpha;\n            }\n        }\n        \n        // Update row/column averages\n        for (int i = 0; i < N; i++) {\n            double sum = 0; int cnt = 0;\n            for (int j = 0; j < N-1; j++) {\n                if (h_cnt[i][j] > 0) { sum += h[i][j]; cnt++; }\n            }\n            if (cnt > 0) { h_row[i] = sum / cnt; h_row_cnt[i] = cnt; }\n        }\n        \n        for (int j = 0; j < N; j++) {\n            double sum = 0; int cnt = 0;\n            for (int i = 0; i < N-1; i++) {\n                if (v_cnt[i][j] > 0) { sum += v[i][j]; cnt++; }\n            }\n            if (cnt > 0) { v_col[j] = sum / cnt; v_col_cnt[j] = cnt; }\n        }\n    }\n    \n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n, m;\n    cin >> n >> m;\n    \n    vector<string> strs(m);\n    for(int i = 0; i < m; i++) cin >> strs[i];\n    \n    vector<int> order(m);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return strs[a].size() > strs[b].size();\n    });\n    \n    char grid[N][N];\n    fill(&grid[0][0], &grid[N][0], '.');\n    \n    // Greedy placement with max overlap preference\n    for(int idx : order) {\n        const string& s = strs[idx];\n        int bestR = -1, bestC, bestD, bestOv = -1;\n        \n        for(int r = 0; r < N; r++) {\n            for(int c = 0; c < N; c++) {\n                for(int d = 0; d < 2; d++) {\n                    bool can = true;\n                    int ov = 0;\n                    for(int p = 0; p < (int)s.size() && can; p++) {\n                        int ni = d ? (r + p) % N : r;\n                        int nj = d ? c : (c + p) % N;\n                        if(grid[ni][nj] != '.' && grid[ni][nj] != s[p]) can = false;\n                        if(grid[ni][nj] != '.') ov++;\n                    }\n                    if(can && ov > bestOv) {\n                        bestOv = ov;\n                        bestR = r; bestC = c; bestD = d;\n                    }\n                }\n            }\n        }\n        \n        if(bestR >= 0) {\n            for(int p = 0; p < (int)s.size(); p++) {\n                int ni = bestD ? (bestR + p) % N : bestR;\n                int nj = bestD ? bestC : (bestC + p) % N;\n                grid[ni][nj] = s[p];\n            }\n        }\n    }\n    \n    // Fill remaining cells randomly\n    mt19937 rng(42);\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < N; j++) {\n            if(grid[i][j] == '.') grid[i][j] = 'A' + rng() % 8;\n        }\n    }\n    \n    // Count function for SA\n    auto countMatched = [&]() {\n        int cnt = 0;\n        for(const auto& s : strs) {\n            bool found = false;\n            for(int r = 0; r < N && !found; r++) {\n                for(int c = 0; c < N && !found; c++) {\n                    for(int d = 0; d < 2 && !found; d++) {\n                        bool ok = true;\n                        for(int p = 0; p < (int)s.size() && ok; p++) {\n                            int ni = d ? (r + p) % N : r;\n                            int nj = d ? c : (c + p) % N;\n                            if(grid[ni][nj] != s[p]) ok = false;\n                        }\n                        if(ok) found = true;\n                    }\n                }\n            }\n            if(found) cnt++;\n        }\n        return cnt;\n    };\n    \n    // Simple SA to improve\n    char bestGrid[N][N];\n    memcpy(bestGrid, grid, sizeof(grid));\n    int bestScore = countMatched();\n    int curScore = bestScore;\n    \n    auto start = chrono::high_resolution_clock::now();\n    double T = 2.0;\n    \n    while(true) {\n        auto now = chrono::high_resolution_clock::now();\n        if(chrono::duration<double>(now - start).count() > 2.7) break;\n        \n        int i = rng() % N, j = rng() % N;\n        char old = grid[i][j];\n        char newc = 'A' + rng() % 8;\n        if(newc == old) continue;\n        \n        grid[i][j] = newc;\n        int newScore = countMatched();\n        \n        if(newScore >= curScore || (rng() & 0xFFFF) < 65536.0 * exp((newScore - curScore) / T)) {\n            curScore = newScore;\n            if(newScore > bestScore) {\n                bestScore = newScore;\n                memcpy(bestGrid, grid, sizeof(grid));\n            }\n        } else {\n            grid[i][j] = old;\n        }\n        T *= 0.9999;\n    }\n    \n    for(int i = 0; i < N; i++) {\n        cout << string(bestGrid[i], bestGrid[i] + N) << '\\n';\n    }\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, si, sj;\nvector<string> grid;\n\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir_char[] = {'U', 'D', 'L', 'R'};\n\ninline bool is_road(int i, int j) {\n    return i >= 0 && i < N && j >= 0 && j < N && grid[i][j] != '#';\n}\n\npair<vector<vector<int>>, vector<vector<pair<int,int>>>> dijkstra(int si, int sj) {\n    vector<vector<int>> dist(N, vector<int>(N, INT_MAX));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1,-1}));\n    priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;\n    dist[si][sj] = 0; pq.push({0, si, sj});\n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top(); pq.pop();\n        if (d > dist[i][j]) continue;\n        for (int k = 0; k < 4; k++) {\n            int ni = i + dx[k], nj = j + dy[k];\n            if (is_road(ni, nj)) {\n                int c = grid[ni][nj] - '0';\n                if (dist[i][j] + c < dist[ni][nj]) {\n                    dist[ni][nj] = dist[i][j] + c;\n                    parent[ni][nj] = {i, j};\n                    pq.push({dist[ni][nj], ni, nj});\n                }\n            }\n        }\n    }\n    return {dist, parent};\n}\n\nstring get_path(int i1, int j1, int i2, int j2, vector<vector<pair<int,int>>>& parent) {\n    if (i1 == i2 && j1 == j2) return \"\";\n    string path;\n    int ci = i2, cj = j2;\n    while (ci != i1 || cj != j1) {\n        auto [pi, pj] = parent[ci][cj];\n        for (int k = 0; k < 4; k++) if (pi + dx[k] == ci && pj + dy[k] == cj) { path += dir_char[k]; break; }\n        ci = pi; cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint calc_path_time(const string& path) {\n    int time = 0, ci = si, cj = sj;\n    for (char c : path) {\n        if (c == 'U') ci--; else if (c == 'D') ci++; else if (c == 'L') cj--; else cj++;\n        time += grid[ci][cj] - '0';\n    }\n    return time;\n}\n\nstring solve(double alpha) {\n    vector<vector<bool>> visible(N, vector<bool>(N, false));\n    int visible_count = 0, total_roads = 0;\n    for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (is_road(i, j)) total_roads++;\n    \n    auto mark_visible = [&](int i, int j) {\n        if (!visible[i][j]) { visible[i][j] = true; visible_count++; }\n        for (int jj = j - 1; jj >= 0 && is_road(i, jj); jj--) if (!visible[i][jj]) { visible[i][jj] = true; visible_count++; }\n        for (int jj = j + 1; jj < N && is_road(i, jj); jj++) if (!visible[i][jj]) { visible[i][jj] = true; visible_count++; }\n        for (int ii = i - 1; ii >= 0 && is_road(ii, j); ii--) if (!visible[ii][j]) { visible[ii][j] = true; visible_count++; }\n        for (int ii = i + 1; ii < N && is_road(ii, j); ii++) if (!visible[ii][j]) { visible[ii][j] = true; visible_count++; }\n    };\n    \n    auto count_new_visible = [&](int i, int j) {\n        int cnt = !visible[i][j];\n        for (int jj = j - 1; jj >= 0 && is_road(i, jj); jj--) cnt += !visible[i][jj];\n        for (int jj = j + 1; jj < N && is_road(i, jj); jj++) cnt += !visible[i][jj];\n        for (int ii = i - 1; ii >= 0 && is_road(ii, j); ii--) cnt += !visible[ii][j];\n        for (int ii = i + 1; ii < N && is_road(ii, j); ii++) cnt += !visible[ii][j];\n        return cnt;\n    };\n    \n    auto [dist_from_start, parent_from_start] = dijkstra(si, sj);\n    int cur_i = si, cur_j = sj;\n    string result;\n    mark_visible(cur_i, cur_j);\n    \n    while (visible_count < total_roads) {\n        auto [dist, parent] = dijkstra(cur_i, cur_j);\n        int best_i = -1, best_j = -1;\n        double best_score = -1e18;\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (dist[i][j] == INT_MAX || dist[i][j] == 0) continue;\n                int nv = count_new_visible(i, j);\n                if (nv == 0) continue;\n                double cost = dist[i][j] + alpha * dist_from_start[i][j];\n                double score = (double)nv / cost;\n                if (score > best_score) { best_score = score; best_i = i; best_j = j; }\n            }\n        }\n        \n        if (best_i == -1) break;\n        \n        string path = get_path(cur_i, cur_j, best_i, best_j, parent);\n        result += path;\n        int ti = cur_i, tj = cur_j;\n        for (char c : path) {\n            if (c == 'U') ti--; else if (c == 'D') ti++; else if (c == 'L') tj--; else tj++;\n            mark_visible(ti, tj);\n        }\n        cur_i = best_i; cur_j = best_j;\n    }\n    \n    if (cur_i != si || cur_j != sj) {\n        auto [dist, parent] = dijkstra(cur_i, cur_j);\n        result += get_path(cur_i, cur_j, si, sj, parent);\n    }\n    return result;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(nullptr);\n    cin >> N >> si >> sj;\n    grid.resize(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    \n    string best_result;\n    int best_time = INT_MAX;\n    \n    for (double alpha : {0.0, 0.03, 0.06, 0.1, 0.15, 0.2, 0.25, 0.3}) {\n        string result = solve(alpha);\n        int time = calc_path_time(result);\n        if (time < best_time) { best_time = time; best_result = result; }\n    }\n    \n    cout << best_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    vector<vector<int>> deps(N), rdeps(N);\n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        deps[v].push_back(u);\n        rdeps[u].push_back(v);\n    }\n    \n    vector<int> taskStatus(N, -1);\n    vector<int> memberTask(M, -1), memberStartDay(M, 0);\n    \n    double initSkill = 40.0 / sqrt(K);\n    vector<vector<double>> skillEst(M, vector<double>(K, initSkill));\n    vector<vector<double>> skillLo(M, vector<double>(K, 0.0));\n    \n    auto estimateTime = [&](int task, int member) -> double {\n        double w = 0;\n        for (int k = 0; k < K; k++)\n            w += max(0.0, (double)d[task][k] - skillEst[member][k]);\n        return max(1.0, w);\n    };\n    \n    auto avgTime = [&](int task) -> double {\n        double sum = 0;\n        for (int j = 0; j < M; j++) sum += estimateTime(task, j);\n        return sum / M;\n    };\n    \n    // Calculate weighted depth (considering task difficulty)\n    vector<double> wdepth(N);\n    for (int i = N - 1; i >= 0; i--) {\n        wdepth[i] = avgTime(i);\n        double maxChild = 0;\n        for (int v : rdeps[i])\n            maxChild = max(maxChild, wdepth[v]);\n        wdepth[i] += maxChild;\n    }\n    \n    // Downstream task count\n    vector<int> downstream(N, 0);\n    for (int i = N - 1; i >= 0; i--) {\n        downstream[i] = (int)rdeps[i].size();\n        for (int v : rdeps[i])\n            downstream[i] += downstream[v];\n    }\n    \n    for (int day = 1; ; day++) {\n        // Recalculate weighted depth periodically\n        if (day % 50 == 1) {\n            for (int i = N - 1; i >= 0; i--) {\n                if (taskStatus[i] == 1) { wdepth[i] = 0; continue; }\n                wdepth[i] = avgTime(i);\n                double maxChild = 0;\n                for (int v : rdeps[i])\n                    maxChild = max(maxChild, wdepth[v]);\n                wdepth[i] += maxChild;\n            }\n        }\n        \n        vector<int> availTasks;\n        for (int i = 0; i < N; i++) {\n            if (taskStatus[i] != -1) continue;\n            bool ok = true;\n            for (int dep : deps[i])\n                if (taskStatus[dep] != 1) { ok = false; break; }\n            if (ok) availTasks.push_back(i);\n        }\n        \n        vector<int> freeMembers;\n        for (int j = 0; j < M; j++)\n            if (memberTask[j] == -1) freeMembers.push_back(j);\n        \n        // Create candidate pairs and score them\n        vector<tuple<double, int, int, double>> candidates; // (score, task, member, time)\n        for (int task : availTasks) {\n            for (int member : freeMembers) {\n                double t = estimateTime(task, member);\n                // Higher wdepth = more critical, want to minimize time for critical tasks\n                double score = wdepth[task] / max(1.0, t);\n                candidates.push_back({-score, task, member, t});\n            }\n        }\n        sort(candidates.begin(), candidates.end());\n        \n        vector<pair<int, int>> assignments;\n        vector<bool> usedMember(M, false), usedTask(N, false);\n        \n        for (auto& [score, task, member, t] : candidates) {\n            if (usedMember[member] || usedTask[task]) continue;\n            usedMember[member] = true;\n            usedTask[task] = true;\n            assignments.push_back({member + 1, task + 1});\n            taskStatus[task] = 0;\n            memberTask[member] = task;\n            memberStartDay[member] = day;\n        }\n        \n        cout << assignments.size();\n        for (auto& [a, b] : assignments) cout << \" \" << a << \" \" << b;\n        cout << \"\\n\";\n        cout.flush();\n        \n        int n; cin >> n;\n        if (n == -1) break;\n        \n        for (int i = 0; i < n; i++) {\n            int f; cin >> f; f--;\n            int task = memberTask[f];\n            int timeTaken = day - memberStartDay[f] + 1;\n            taskStatus[task] = 1;\n            memberTask[f] = -1;\n            \n            if (timeTaken == 1) {\n                for (int k = 0; k < K; k++) {\n                    skillLo[f][k] = max(skillLo[f][k], (double)d[task][k]);\n                    skillEst[f][k] = max(skillEst[f][k], (double)d[task][k]);\n                }\n            } else {\n                double wEst = (double)timeTaken;\n                double currW = 0;\n                for (int k = 0; k < K; k++)\n                    currW += max(0.0, (double)d[task][k] - skillEst[f][k]);\n                \n                if (currW > 0.5) {\n                    double factor = wEst / currW;\n                    factor = 0.6 * factor + 0.4;\n                    factor = max(0.5, min(1.5, factor));\n                    \n                    for (int k = 0; k < K; k++) {\n                        double gap = d[task][k] - skillEst[f][k];\n                        if (gap > 0) {\n                            double newSkill = d[task][k] - gap * factor;\n                            skillEst[f][k] = max(skillLo[f][k], newSkill);\n                        }\n                    }\n                } else if (wEst > 4) {\n                    for (int k = 0; k < K; k++) {\n                        if (d[task][k] > skillLo[f][k] + 0.5) {\n                            skillEst[f][k] = max(skillLo[f][k], \n                                skillEst[f][k] - (wEst - 3) * d[task][k] / (avgTime(task) * K + 1));\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1000, M = 50, CX = 400, CY = 400;\nint ordA[N], ordB[N], ordC[N], ordD[N];\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\ninline int dist(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint buildRoute(const vector<int>& sel, vector<pair<int,bool>>& ev) {\n    ev.clear();\n    ev.reserve(2 * M);\n    bool picked[N] = {}, done[N] = {};\n    int cx = CX, cy = CY, cost = 0;\n    \n    for (int i = 0; i < 2*M; i++) {\n        int best = -1, bd = 1e9;\n        bool isDel = false;\n        for (int j : sel) {\n            if (!picked[j]) {\n                int d = dist(cx, cy, ordA[j], ordB[j]);\n                if (d < bd) { bd = d; best = j; isDel = false; }\n            } else if (!done[j]) {\n                int d = dist(cx, cy, ordC[j], ordD[j]);\n                if (d < bd) { bd = d; best = j; isDel = true; }\n            }\n        }\n        cost += bd;\n        if (isDel) { cx = ordC[best]; cy = ordD[best]; done[best] = true; }\n        else { cx = ordA[best]; cy = ordB[best]; picked[best] = true; }\n        ev.push_back({best, isDel});\n    }\n    return cost + dist(cx, cy, CX, CY);\n}\n\nint calcCost(const vector<pair<int,bool>>& ev) {\n    int cx = CX, cy = CY, cost = 0;\n    for (auto& [idx, isDel] : ev) {\n        int nx = isDel ? ordC[idx] : ordA[idx];\n        int ny = isDel ? ordD[idx] : ordB[idx];\n        cost += dist(cx, cy, nx, ny);\n        cx = nx; cy = ny;\n    }\n    return cost + dist(cx, cy, CX, CY);\n}\n\nbool validSwap(vector<pair<int,bool>>& ev, int i, int j) {\n    swap(ev[i], ev[j]);\n    map<int, int> pickPos;\n    for (int k = 0; k < (int)ev.size(); k++) {\n        if (!ev[k].second) pickPos[ev[k].first] = k;\n        else if (pickPos.find(ev[k].first) == pickPos.end() || pickPos[ev[k].first] > k) {\n            swap(ev[i], ev[j]);\n            return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    auto st = chrono::steady_clock::now();\n    for (int i = 0; i < N; i++) cin >> ordA[i] >> ordB[i] >> ordC[i] >> ordD[i];\n    \n    auto elapsed = [&]() {\n        return chrono::duration<double>(chrono::steady_clock::now() - st).count();\n    };\n    \n    vector<pair<int,int>> byDist(N);\n    for (int i = 0; i < N; i++) {\n        byDist[i] = {dist(CX, CY, ordA[i], ordB[i]) + dist(CX, CY, ordC[i], ordD[i]), i};\n    }\n    sort(byDist.begin(), byDist.end());\n    \n    vector<int> sel(M), unsel(N-M);\n    for (int i = 0; i < M; i++) sel[i] = byDist[i].second;\n    for (int i = 0; i < N-M; i++) unsel[i] = byDist[M+i].second;\n    \n    vector<pair<int,bool>> ev, bestEv;\n    int cost = buildRoute(sel, ev);\n    int bestCost = cost;\n    vector<int> bestSel = sel;\n    bestEv = ev;\n    \n    double temp = 3000.0;\n    \n    while (elapsed() < 1.8) {\n        int si = rng() % M;\n        int ui = rng() % (N-M);\n        swap(sel[si], unsel[ui]);\n        \n        int nc = buildRoute(sel, ev);\n        int delta = nc - cost;\n        \n        if (delta < 0 || (rng() % 10000) < 10000 * exp(-delta / temp)) {\n            cost = nc;\n            if (nc < bestCost) {\n                bestCost = nc;\n                bestSel = sel;\n                bestEv = ev;\n            }\n        } else {\n            swap(sel[si], unsel[ui]);\n        }\n        temp *= 0.99995;\n    }\n    \n    // Light 2-opt on best route at the end\n    bool improved = true;\n    while (improved && elapsed() < 1.95) {\n        improved = false;\n        for (int i = 0; i < 2*M - 1 && !improved; i++) {\n            for (int j = i + 1; j < 2*M && !improved; j++) {\n                if (bestEv[i].first == bestEv[j].first) continue;\n                int oldCost = bestCost;\n                if (validSwap(bestEv, i, j)) {\n                    int nc = calcCost(bestEv);\n                    if (nc < bestCost) {\n                        bestCost = nc;\n                        improved = true;\n                    } else {\n                        swap(bestEv[i], bestEv[j]);\n                    }\n                }\n            }\n        }\n    }\n    \n    cout << M;\n    for (int x : bestSel) cout << \" \" << (x+1);\n    cout << \"\\n\" << (2*M+2) << \" \" << CX << \" \" << CY;\n    for (auto& [idx, isDel] : bestEv) {\n        if (isDel) cout << \" \" << ordC[idx] << \" \" << ordD[idx];\n        else cout << \" \" << ordA[idx] << \" \" << ordB[idx];\n    }\n    cout << \" \" << CX << \" \" << CY << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass UnionFind {\n    vector<int> parent, rank_;\npublic:\n    UnionFind(int n) : parent(n), rank_(n, 0) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    int find(int x) {\n        if (parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    bool unite(int x, int y) {\n        int px = find(x), py = find(y);\n        if (px == py) return false;\n        if (rank_[px] < rank_[py]) swap(px, py);\n        parent[py] = px;\n        if (rank_[px] == rank_[py]) rank_[px]++;\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 400, M = 1995;\n    \n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<int> u(M), v(M), d(M);\n    for (int i = 0; i < M; i++) {\n        cin >> u[i] >> v[i];\n        double dx = x[u[i]] - x[v[i]];\n        double dy = y[u[i]] - y[v[i]];\n        d[i] = (int)round(sqrt(dx * dx + dy * dy));\n    }\n    \n    UnionFind uf(N);\n    int components = N;\n    \n    for (int i = 0; i < M; i++) {\n        int l;\n        cin >> l;\n        \n        int pu = uf.find(u[i]);\n        int pv = uf.find(v[i]);\n        \n        bool already_connected = (pu == pv);\n        double ratio = (double)l / d[i];\n        \n        bool adopt = false;\n        \n        if (!already_connected) {\n            int useful_remaining = 0;\n            int same_pair_remaining = 0;\n            \n            for (int j = i + 1; j < M; j++) {\n                int uj = uf.find(u[j]);\n                int vj = uf.find(v[j]);\n                if (uj != vj) {\n                    useful_remaining++;\n                    if ((uj == pu && vj == pv) || (uj == pv && vj == pu)) {\n                        same_pair_remaining++;\n                    }\n                }\n            }\n            \n            int needed = components - 1;\n            \n            // Must accept if no alternatives\n            if (same_pair_remaining == 0) {\n                adopt = true;\n            }\n            // Safety: running low on useful edges\n            else if (useful_remaining < needed * 2) {\n                adopt = true;\n            }\n            else {\n                // Expected minimum of (k+1) uniform [1,3] samples = 1 + 2/(k+2)\n                double k = same_pair_remaining;\n                double expected_min = 1.0 + 2.0 / (k + 2.0);\n                \n                // Be more accepting - larger buffer helps avoid missing good opportunities\n                double threshold = expected_min + 0.25;\n                \n                if (ratio <= threshold) {\n                    adopt = true;\n                }\n            }\n        }\n        \n        if (adopt) {\n            uf.unite(u[i], v[i]);\n            components--;\n        }\n        \n        cout << (adopt ? 1 : 0) << \"\\n\" << flush;\n    }\n    \n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<array<int,3>> pets;\nvector<array<int,2>> humans;\nbool blocked[32][32];\n\nbool pet_at(int x, int y) {\n    for (auto& p : pets) if (p[0] == x && p[1] == y) return true;\n    return false;\n}\n\nbool pet_adjacent(int x, int y) {\n    int dx[] = {0, -1, 1, 0, 0}, dy[] = {0, 0, 0, -1, 1};\n    for (int d = 0; d < 5; d++) if (pet_at(x+dx[d], y+dy[d])) return true;\n    return false;\n}\n\nbool can_place(int x, int y) {\n    if (x < 1 || x > 30 || y < 1 || y > 30 || blocked[x][y]) return false;\n    for (auto& h : humans) if (h[0] == x && h[1] == y) return false;\n    return !pet_adjacent(x, y);\n}\n\nbool passable(int x, int y) {\n    return x >= 1 && x <= 30 && y >= 1 && y <= 30 && !blocked[x][y];\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N; pets.resize(N);\n    for (int i = 0; i < N; i++) cin >> pets[i][0] >> pets[i][1] >> pets[i][2];\n    cin >> M; humans.resize(M);\n    for (int i = 0; i < M; i++) cin >> humans[i][0] >> humans[i][1];\n    \n    set<pair<int,int>> target;\n    for (int i = 1; i <= 30; i++) {\n        for (int c : {7, 14, 21, 28}) {\n            target.insert({i, c});\n            target.insert({c, i});\n        }\n    }\n    \n    int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};\n    char wc[] = {'u', 'd', 'l', 'r'}, mc[] = {'U', 'D', 'L', 'R'};\n    \n    for (int turn = 0; turn < 300; turn++) {\n        string action(M, '.');\n        \n        for (int i = 0; i < M; i++) {\n            int hx = humans[i][0], hy = humans[i][1];\n            int best = -1, bestd = -1;\n            \n            for (int d = 0; d < 4; d++) {\n                int nx = hx + dx[d], ny = hy + dy[d];\n                if (can_place(nx, ny)) {\n                    int sc = target.count({nx, ny}) ? 100 : 1;\n                    if (sc > best) { best = sc; bestd = d; }\n                }\n            }\n            \n            if (bestd >= 0) {\n                action[i] = wc[bestd];\n            } else {\n                int minD = INT_MAX, moveD = -1;\n                for (auto& [tx, ty] : target) {\n                    if (blocked[tx][ty]) continue;\n                    int dist = abs(hx-tx) + abs(hy-ty);\n                    if (dist > 0 && dist < minD) minD = dist;\n                }\n                for (int d = 0; d < 4; d++) {\n                    int nx = hx + dx[d], ny = hy + dy[d];\n                    if (!passable(nx, ny) || pet_at(nx, ny)) continue;\n                    for (auto& [tx, ty] : target) {\n                        if (blocked[tx][ty]) continue;\n                        if (abs(nx-tx) + abs(ny-ty) < minD) {\n                            minD = abs(nx-tx) + abs(ny-ty);\n                            moveD = d;\n                        }\n                    }\n                }\n                if (moveD >= 0) action[i] = mc[moveD];\n            }\n        }\n        \n        cout << action << \"\\n\" << flush;\n        \n        for (int i = 0; i < M; i++) {\n            char a = action[i];\n            for (int d = 0; d < 4; d++) {\n                if (a == wc[d]) blocked[humans[i][0]+dx[d]][humans[i][1]+dy[d]] = true;\n                if (a == mc[d]) { humans[i][0] += dx[d]; humans[i][1] += dy[d]; }\n            }\n        }\n        \n        for (int i = 0; i < N; i++) {\n            string s; cin >> s;\n            for (char c : s) {\n                if (c == 'U') pets[i][0]--;\n                else if (c == 'D') pets[i][0]++;\n                else if (c == 'L') pets[i][1]--;\n                else if (c == 'R') pets[i][1]++;\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N = 20;\nint si, sj, ti, tj;\ndouble p;\nbool hwall[20][19];\nbool vwall[19][20];\n\nbool canMove(int i, int j, char dir) {\n    if (dir == 'U') return i > 0 && !vwall[i-1][j];\n    if (dir == 'D') return i < 19 && !vwall[i][j];\n    if (dir == 'L') return j > 0 && !hwall[i][j-1];\n    if (dir == 'R') return j < 19 && !hwall[i][j];\n    return false;\n}\n\npair<int,int> doMove(int i, int j, char dir) {\n    if (!canMove(i, j, dir)) return {i, j};\n    if (dir == 'U') return {i-1, j};\n    if (dir == 'D') return {i+1, j};\n    if (dir == 'L') return {i, j-1};\n    if (dir == 'R') return {i, j+1};\n    return {i, j};\n}\n\ndouble evaluate(const string& s) {\n    if (s.empty() || s.size() > 200) return -1;\n    vector<vector<double>> prob(N, vector<double>(N, 0));\n    prob[si][sj] = 1.0;\n    double expectedScore = 0;\n    for (int t = 1; t <= (int)s.size(); t++) {\n        char dir = s[t-1];\n        vector<vector<double>> newProb(N, vector<double>(N, 0));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (prob[i][j] < 1e-18) continue;\n                auto [ni, nj] = doMove(i, j, dir);\n                if (ni == ti && nj == tj) {\n                    expectedScore += (1-p) * prob[i][j] * (401 - t);\n                } else {\n                    newProb[ni][nj] += (1-p) * prob[i][j];\n                }\n                newProb[i][j] += p * prob[i][j];\n            }\n        }\n        prob = newProb;\n    }\n    return expectedScore;\n}\n\nstring bfsWithOrder(vector<char>& order) {\n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1,-1}));\n    vector<vector<char>> fromDir(N, vector<char>(N, ' '));\n    queue<pair<int,int>> q;\n    q.push({si, sj});\n    dist[si][sj] = 0;\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        for (char d : order) {\n            auto [ni, nj] = doMove(i, j, d);\n            if (ni == i && nj == j) continue;\n            if (dist[ni][nj] == -1) {\n                dist[ni][nj] = dist[i][j] + 1;\n                parent[ni][nj] = {i, j};\n                fromDir[ni][nj] = d;\n                q.push({ni, nj});\n            }\n        }\n    }\n    string path;\n    int ci = ti, cj = tj;\n    while (ci != si || cj != sj) {\n        path += fromDir[ci][cj];\n        auto [pi, pj] = parent[ci][cj];\n        ci = pi; cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nmt19937 rng(12345);\nstring best;\ndouble bestScore = -1;\nconst char dirs[] = {'U', 'D', 'L', 'R'};\n\nvoid updateBest(const string& s) {\n    if (s.size() > 200 || s.empty()) return;\n    double score = evaluate(s);\n    if (score > bestScore) {\n        bestScore = score;\n        best = s;\n    }\n}\n\nchrono::steady_clock::time_point startTime;\n\nbool timeUp(int ms = 1900) {\n    return chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() > ms;\n}\n\nvoid localSearch() {\n    while (!timeUp()) {\n        bool improved = false;\n        \n        // Try removing each character\n        for (size_t i = 0; i < best.size() && !improved && !timeUp(); i++) {\n            string trial = best.substr(0, i) + best.substr(i + 1);\n            if (!trial.empty()) {\n                double score = evaluate(trial);\n                if (score > bestScore) { bestScore = score; best = trial; improved = true; }\n            }\n        }\n        \n        // Try changing each character\n        for (size_t i = 0; i < best.size() && !improved && !timeUp(); i++) {\n            for (char d : dirs) {\n                if (d == best[i]) continue;\n                string trial = best;\n                trial[i] = d;\n                double score = evaluate(trial);\n                if (score > bestScore) { bestScore = score; best = trial; improved = true; break; }\n            }\n        }\n        \n        // Try inserting characters\n        if (best.size() < 200) {\n            for (size_t i = 0; i <= best.size() && !improved && !timeUp(); i++) {\n                for (char d : dirs) {\n                    string trial = best.substr(0, i) + d + best.substr(i);\n                    if (trial.size() <= 200) {\n                        double score = evaluate(trial);\n                        if (score > bestScore) { bestScore = score; best = trial; improved = true; break; }\n                    }\n                }\n            }\n        }\n        \n        // Try duplicating characters\n        if (best.size() < 200) {\n            for (size_t i = 0; i < best.size() && !improved && !timeUp(); i++) {\n                string trial = best.substr(0, i+1) + best[i] + best.substr(i+1);\n                if (trial.size() <= 200) {\n                    double score = evaluate(trial);\n                    if (score > bestScore) { bestScore = score; best = trial; improved = true; }\n                }\n            }\n        }\n        \n        if (!improved) break;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    startTime = chrono::steady_clock::now();\n    \n    cin >> si >> sj >> ti >> tj >> p;\n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < 19; j++) hwall[i][j] = (s[j] == '1');\n    }\n    for (int i = 0; i < 19; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) vwall[i][j] = (s[j] == '1');\n    }\n    \n    vector<char> order = {'U', 'D', 'L', 'R'};\n    set<string> pathSet;\n    \n    for (int iter = 0; iter < 200 && !timeUp(500); iter++) {\n        shuffle(order.begin(), order.end(), rng);\n        pathSet.insert(bfsWithOrder(order));\n    }\n    vector<string> paths(pathSet.begin(), pathSet.end());\n    \n    for (const string& path : paths) {\n        if (timeUp(1200)) break;\n        int pathLen = path.size();\n        \n        // Strategy 1: Uniform move repetition\n        for (int rep = 1; rep * pathLen <= 200; rep++) {\n            string result;\n            for (char c : path) for (int i = 0; i < rep; i++) result += c;\n            updateBest(result);\n        }\n        \n        // Strategy 2: Path multiplication\n        for (int rep = 1; rep * pathLen <= 200; rep++) {\n            string result;\n            for (int i = 0; i < rep; i++) result += path;\n            updateBest(result);\n        }\n        \n        // Strategy 3: Wall-aware repetition\n        for (int bonus = 1; bonus <= 8; bonus++) {\n            for (int baseR = 1; baseR <= 12 && baseR * pathLen <= 200; baseR++) {\n                string result;\n                int ci = si, cj = sj;\n                for (char c : path) {\n                    auto [ni, nj] = doMove(ci, cj, c);\n                    bool safeAfter = !canMove(ni, nj, c);\n                    int reps = safeAfter ? baseR + bonus : baseR;\n                    for (int i = 0; i < reps && result.size() < 200; i++) result += c;\n                    ci = ni; cj = nj;\n                }\n                updateBest(result);\n            }\n        }\n        \n        // Strategy 4: Combined repetition\n        for (int pathRep = 1; pathRep <= 10; pathRep++) {\n            for (int moveRep = 1; moveRep * pathLen * pathRep <= 200 && moveRep <= 10; moveRep++) {\n                string result;\n                for (int pr = 0; pr < pathRep; pr++)\n                    for (char c : path) for (int mr = 0; mr < moveRep; mr++) result += c;\n                updateBest(result);\n            }\n        }\n        \n        // Strategy 5: Progressive repetition (increasing)\n        for (int startRep = 1; startRep <= 5; startRep++) {\n            for (int endRep = startRep; endRep <= 12; endRep++) {\n                string result;\n                for (int i = 0; i < pathLen && result.size() < 200; i++) {\n                    int rep = startRep + (endRep - startRep) * i / max(1, pathLen - 1);\n                    for (int j = 0; j < rep && result.size() < 200; j++) result += path[i];\n                }\n                updateBest(result);\n            }\n        }\n        \n        // Strategy 6: Progressive repetition (decreasing)\n        for (int startRep = 2; startRep <= 12; startRep++) {\n            for (int endRep = 1; endRep < startRep; endRep++) {\n                string result;\n                for (int i = 0; i < pathLen && result.size() < 200; i++) {\n                    int rep = startRep - (startRep - endRep) * i / max(1, pathLen - 1);\n                    for (int j = 0; j < rep && result.size() < 200; j++) result += path[i];\n                }\n                updateBest(result);\n            }\n        }\n        \n        // Strategy 7: Path mult with extra repetition at end\n        for (int pathRep = 2; pathRep * pathLen <= 200; pathRep++) {\n            for (int extra = 1; extra <= 5; extra++) {\n                string result;\n                for (int i = 0; i < pathRep - 1; i++) result += path;\n                for (char c : path) for (int j = 0; j < extra && result.size() < 200; j++) result += c;\n                updateBest(result);\n            }\n        }\n    }\n    \n    localSearch();\n    \n    cout << best << endl;\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nint tiles[N][N];\nint rotation[N][N];\n\nconst int di[] = {0, -1, 0, 1};\nconst int dj[] = {-1, 0, 1, 0};\n\nconst int to_arr[8][4] = {\n    {1, 0, -1, -1}, {3, -1, -1, 0}, {-1, -1, 3, 2}, {-1, 2, 1, -1},\n    {1, 0, 3, 2}, {3, 2, 1, 0}, {2, -1, 0, -1}, {-1, 3, -1, 1},\n};\n\ninline int getState(int i, int j) {\n    int t = tiles[i][j], r = rotation[i][j];\n    if (t < 4) return (t + r) % 4;\n    if (t < 6) return 4 + (t - 4 + r) % 2;\n    return 6 + (t - 6 + r) % 2;\n}\n\nint traceLoop(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd, length = 0;\n    do {\n        int state = getState(i, j);\n        int d2 = to_arr[state][d];\n        if (d2 == -1) return 0;\n        length++;\n        if (length > 4 * N * N) return 0;\n        i += di[d2]; j += dj[d2];\n        if ((unsigned)i >= N || (unsigned)j >= N) return 0;\n        d = (d2 + 2) % 4;\n    } while (i != si || j != sj || d != sd);\n    return length;\n}\n\npair<int, int> computeTopTwoLoops() {\n    static bool visited[N][N][4];\n    memset(visited, 0, sizeof(visited));\n    int top1 = 0, top2 = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int state = getState(i, j);\n            for (int d = 0; d < 4; d++) {\n                if (to_arr[state][d] == -1 || visited[i][j][d]) continue;\n                int len = traceLoop(i, j, d);\n                if (len > 0) {\n                    if (len > top1) { top2 = top1; top1 = len; }\n                    else if (len > top2) { top2 = len; }\n                    int ci = i, cj = j, cd = d;\n                    do {\n                        visited[ci][cj][cd] = true;\n                        int st = getState(ci, cj);\n                        int d2 = to_arr[st][cd];\n                        ci += di[d2]; cj += dj[d2];\n                        cd = (d2 + 2) % 4;\n                    } while (ci != i || cj != j || cd != d);\n                }\n            }\n        }\n    }\n    return {top1, top2};\n}\n\nint best_rotation[N][N];\nlong long best_score;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = s[j] - '0';\n            rotation[i][j] = 0;\n        }\n    }\n    \n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    \n    auto [l1, l2] = computeTopTwoLoops();\n    best_score = (long long)l1 * l2;\n    memcpy(best_rotation, rotation, sizeof(rotation));\n    long long current_score = best_score;\n    \n    const double TIME_LIMIT = 1.9;\n    \n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start_time).count();\n        if (elapsed > TIME_LIMIT) break;\n        \n        double T = 1000.0 * pow(0.0001, elapsed / TIME_LIMIT);\n        \n        int i = rng() % N, j = rng() % N;\n        int old_rot = rotation[i][j];\n        int new_rot = (old_rot + 1 + rng() % 3) % 4;\n        \n        rotation[i][j] = new_rot;\n        auto [nl1, nl2] = computeTopTwoLoops();\n        long long new_score = (long long)nl1 * nl2;\n        \n        double delta = (double)(new_score - current_score);\n        if (delta >= 0 || uniform_real_distribution<double>(0, 1)(rng) < exp(delta / T)) {\n            current_score = new_score;\n            if (new_score > best_score) {\n                best_score = new_score;\n                memcpy(best_rotation, rotation, sizeof(rotation));\n            }\n        } else {\n            rotation[i][j] = old_rot;\n        }\n    }\n    \n    string result;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            result += ('0' + best_rotation[i][j]);\n    cout << result << endl;\n    \n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dc_char[] = {'U', 'D', 'L', 'R'};\n\nint hexChar(char c) {\n    return (c >= '0' && c <= '9') ? c - '0' : c - 'a' + 10;\n}\n\nint calcScore(const vector<vector<int>>& board) {\n    vector<vector<int>> adj(N * N);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (board[i][j] == 0) continue;\n            if (i + 1 < N && board[i+1][j] != 0 && (board[i][j] & 8) && (board[i+1][j] & 2)) {\n                adj[i*N+j].push_back((i+1)*N+j);\n                adj[(i+1)*N+j].push_back(i*N+j);\n            }\n            if (j + 1 < N && board[i][j+1] != 0 && (board[i][j] & 4) && (board[i][j+1] & 1)) {\n                adj[i*N+j].push_back(i*N+j+1);\n                adj[i*N+j+1].push_back(i*N+j);\n            }\n        }\n    }\n    vector<bool> vis(N * N, false);\n    int maxTree = 0;\n    for (int s = 0; s < N * N; s++) {\n        if (vis[s] || board[s/N][s%N] == 0) continue;\n        int cnt = 0, edges = 0;\n        queue<int> q; q.push(s); vis[s] = true;\n        while (!q.empty()) {\n            int u = q.front(); q.pop(); cnt++;\n            edges += adj[u].size();\n            for (int v : adj[u]) if (!vis[v]) { vis[v] = true; q.push(v); }\n        }\n        if (edges / 2 == cnt - 1) maxTree = max(maxTree, cnt);\n    }\n    return maxTree;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    int er, ec;\n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) {\n            board[i][j] = hexChar(s[j]);\n            if (board[i][j] == 0) { er = i; ec = j; }\n        }\n    }\n    \n    string best, cur;\n    int bestScore = calcScore(board), curScore = bestScore;\n    auto bestBoard = board; int bestEr = er, bestEc = ec;\n    \n    mt19937 rng(42);\n    auto start = chrono::steady_clock::now();\n    \n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count() < 2800) {\n        if (cur.size() >= (size_t)T || bestScore >= N * N - 1) break;\n        \n        vector<int> valid;\n        for (int d = 0; d < 4; d++) {\n            int nr = er + dr[d], nc = ec + dc[d];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N) valid.push_back(d);\n        }\n        int d = valid[rng() % valid.size()];\n        int nr = er + dr[d], nc = ec + dc[d];\n        \n        swap(board[er][ec], board[nr][nc]);\n        cur += dc_char[d];\n        int newScore = calcScore(board);\n        \n        double temp = 1.0 - (double)cur.size() / T;\n        bool accept = newScore > curScore || (rng() % 1000 < 100 * temp);\n        \n        if (accept) {\n            er = nr; ec = nc; curScore = newScore;\n            if (curScore > bestScore || (curScore == bestScore && cur.size() < best.size())) {\n                bestScore = curScore; best = cur;\n                bestBoard = board; bestEr = er; bestEc = ec;\n            }\n        } else {\n            cur.pop_back();\n            swap(board[er][ec], board[nr][nc]);\n        }\n        \n        if (cur.size() > T / 2 && rng() % 100 < 5) {\n            board = bestBoard; er = bestEr; ec = bestEc;\n            cur = best; curScore = bestScore;\n        }\n    }\n    \n    cout << best << endl;\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nint N, K;\nvector<int> a(10);\nvector<pair<ll, ll>> berries;\nvector<array<ll, 4>> cuts;\nvector<vector<int>> sides;\n\ninline int side(ll x1, ll y1, ll x2, ll y2, ll px, ll py) {\n    __int128 cross = (__int128)(x2 - x1) * (py - y1) - (__int128)(y2 - y1) * (px - x1);\n    if (cross > 0) return 1;\n    if (cross < 0) return -1;\n    return 0;\n}\n\nint calcScore() {\n    int numCuts = cuts.size();\n    unordered_map<uint64_t, int> pieceCount;\n    \n    for (int j = 0; j < N; j++) {\n        bool onLine = false;\n        uint64_t h = 0;\n        for (int i = 0; i < numCuts; i++) {\n            if (sides[i][j] == 0) { onLine = true; break; }\n            h = h * 3ULL + (uint64_t)(sides[i][j] + 1);\n        }\n        if (!onLine) pieceCount[h]++;\n    }\n    \n    vector<int> b(11, 0);\n    for (auto& [sig, cnt] : pieceCount) {\n        if (cnt >= 1 && cnt <= 10) b[cnt]++;\n    }\n    \n    int total = 0;\n    for (int d = 1; d <= 10; d++) total += min(a[d-1], b[d]);\n    return total;\n}\n\nvoid updateSides(int idx) {\n    while ((int)sides.size() <= idx) sides.push_back(vector<int>(N));\n    for (int j = 0; j < N; j++) {\n        sides[idx][j] = side(cuts[idx][0], cuts[idx][1], cuts[idx][2], cuts[idx][3],\n                            berries[j].first, berries[j].second);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> K;\n    for (int i = 0; i < 10; i++) cin >> a[i];\n    \n    berries.resize(N);\n    for (int i = 0; i < N; i++) cin >> berries[i].first >> berries[i].second;\n    \n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    auto randLine = [&]() -> array<ll, 4> {\n        ll px = (ll)(rng() % 20001) - 10000;\n        ll py = (ll)(rng() % 20001) - 10000;\n        ll qx = (ll)(rng() % 20001) - 10000;\n        ll qy = (ll)(rng() % 20001) - 10000;\n        while (px == qx && py == qy) { qx = (ll)(rng() % 20001) - 10000; qy = (ll)(rng() % 20001) - 10000; }\n        return {px, py, qx, qy};\n    };\n    \n    auto perpBisector = [&](int i, int j) -> array<ll, 4> {\n        if (i == j) return randLine();\n        ll dx = berries[j].first - berries[i].first;\n        ll dy = berries[j].second - berries[i].second;\n        ll mx = berries[i].first + berries[j].first;\n        ll my = berries[i].second + berries[j].second;\n        return {mx - dy * 1000, my + dx * 1000, mx + dy * 1000, my - dx * 1000};\n    };\n    \n    auto radialLine = [&](double angle) -> array<ll, 4> {\n        ll px = (ll)(cos(angle) * 15000);\n        ll py = (ll)(sin(angle) * 15000);\n        if (px == 0 && py == 0) px = 1;\n        return {px, py, -px, -py};\n    };\n    \n    int bestScore = 0;\n    vector<array<ll, 4>> bestCuts;\n    \n    auto start = chrono::steady_clock::now();\n    \n    for (int restart = 0; ; restart++) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration_cast<chrono::milliseconds>(now - start).count();\n        if (elapsed > 2850) break;\n        \n        cuts.clear();\n        sides.clear();\n        int numCuts = 25 + rng() % 35;\n        \n        for (int i = 0; i < numCuts; i++) {\n            int strategy = rng() % 4;\n            if (strategy == 0) cuts.push_back(randLine());\n            else if (strategy == 1) cuts.push_back(perpBisector(rng() % N, rng() % N));\n            else if (strategy == 2) cuts.push_back(radialLine((double)(rng() % 10000) / 10000.0 * M_PI * 2));\n            else {\n                int b1 = rng() % N, b2 = rng() % N;\n                if (b1 != b2) {\n                    cuts.push_back({berries[b1].first, berries[b1].second, berries[b2].first, berries[b2].second});\n                } else cuts.push_back(randLine());\n            }\n            updateSides(i);\n        }\n        \n        int curScore = calcScore();\n        if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n        \n        for (int iter = 0; ; iter++) {\n            now = chrono::steady_clock::now();\n            elapsed = chrono::duration_cast<chrono::milliseconds>(now - start).count();\n            if (elapsed > 2850) break;\n            \n            double progress = elapsed / 2850.0;\n            double temp = 3.0 * (1.0 - progress) + 0.1;\n            int moveType = rng() % 100;\n            \n            if (moveType < 75 && !cuts.empty()) {\n                int idx = rng() % cuts.size();\n                auto oldCut = cuts[idx];\n                auto oldSide = sides[idx];\n                \n                int strat = rng() % 4;\n                if (strat == 0) cuts[idx] = randLine();\n                else if (strat == 1) cuts[idx] = perpBisector(rng() % N, rng() % N);\n                else if (strat == 2) cuts[idx] = radialLine((double)(rng() % 10000) / 10000.0 * M_PI * 2);\n                else {\n                    int b1 = rng() % N, b2 = rng() % N;\n                    if (b1 != b2) cuts[idx] = {berries[b1].first, berries[b1].second, berries[b2].first, berries[b2].second};\n                    else cuts[idx] = randLine();\n                }\n                updateSides(idx);\n                \n                int newScore = calcScore();\n                double acceptProb = exp((newScore - curScore) / temp);\n                if (newScore > curScore || (double)(rng() % 1000000) / 1000000.0 < acceptProb) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else {\n                    cuts[idx] = oldCut;\n                    sides[idx] = oldSide;\n                }\n            } else if (moveType < 90 && cuts.size() < (size_t)min(K, 80)) {\n                int strat = rng() % 4;\n                if (strat == 0) cuts.push_back(randLine());\n                else if (strat == 1) cuts.push_back(perpBisector(rng() % N, rng() % N));\n                else if (strat == 2) cuts.push_back(radialLine((double)(rng() % 10000) / 10000.0 * M_PI * 2));\n                else {\n                    int b1 = rng() % N, b2 = rng() % N;\n                    if (b1 != b2) cuts.push_back({berries[b1].first, berries[b1].second, berries[b2].first, berries[b2].second});\n                    else cuts.push_back(randLine());\n                }\n                updateSides(cuts.size() - 1);\n                \n                int newScore = calcScore();\n                if (newScore >= curScore) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else {\n                    cuts.pop_back();\n                    sides.pop_back();\n                }\n            } else if (cuts.size() > 10) {\n                int idx = rng() % cuts.size();\n                auto oldCut = cuts[idx];\n                auto oldSide = sides[idx];\n                cuts.erase(cuts.begin() + idx);\n                sides.erase(sides.begin() + idx);\n                \n                int newScore = calcScore();\n                if (newScore >= curScore) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else {\n                    cuts.insert(cuts.begin() + idx, oldCut);\n                    sides.insert(sides.begin() + idx, oldSide);\n                }\n            }\n        }\n    }\n    \n    cout << bestCuts.size() << \"\\n\";\n    for (auto& c : bestCuts) cout << c[0] << \" \" << c[1] << \" \" << c[2] << \" \" << c[3] << \"\\n\";\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, c;\nset<pair<int,int>> dots;\nset<tuple<int,int,int,int>> usedSegs;\nvector<array<int, 8>> ops;\n\nbool inGrid(int x, int y) { return x >= 0 && x < N && y >= 0 && y < N; }\nlong long wt(int x, int y) { return (long long)(x-c)*(x-c) + (long long)(y-c)*(y-c) + 1; }\n\nvoid addSeg(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g == 0) return;\n    dx /= g; dy /= g;\n    for (int i = 0; i < g; i++) {\n        int a = x1+i*dx, b = y1+i*dy, e = a+dx, f = b+dy;\n        if (a > e || (a == e && b > f)) { swap(a,e); swap(b,f); }\n        usedSegs.insert({a,b,e,f});\n    }\n}\n\nbool segUsed(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g == 0) return true;\n    dx /= g; dy /= g;\n    for (int i = 0; i < g; i++) {\n        int a = x1+i*dx, b = y1+i*dy, e = a+dx, f = b+dy;\n        if (a > e || (a == e && b > f)) { swap(a,e); swap(b,f); }\n        if (usedSegs.count({a,b,e,f})) return true;\n    }\n    return false;\n}\n\nbool dotOnSeg(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g <= 1) return false;\n    dx /= g; dy /= g;\n    for (int i = 1; i < g; i++)\n        if (dots.count({x1+i*dx, y1+i*dy})) return true;\n    return false;\n}\n\nbool isValidRect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    int v1x = x2-x1, v1y = y2-y1;\n    int v2x = x3-x2, v2y = y3-y2;\n    if (v1x == 0 && v1y == 0) return false;\n    if (v2x == 0 && v2y == 0) return false;\n    if (v1x*v2x + v1y*v2y != 0) return false;\n    bool axis1 = (v1x == 0 || v1y == 0);\n    bool diag1 = (abs(v1x) == abs(v1y));\n    if (!axis1 && !diag1) return false;\n    bool axis2 = (v2x == 0 || v2y == 0);\n    bool diag2 = (abs(v2x) == abs(v2y));\n    if (!axis2 && !diag2) return false;\n    if (x4 != x1 + v2x || y4 != y1 + v2y) return false;\n    return true;\n}\n\nbool tryAdd(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (!inGrid(x1,y1) || dots.count({x1,y1})) return false;\n    if (!dots.count({x2,y2}) || !dots.count({x3,y3}) || !dots.count({x4,y4})) return false;\n    set<pair<int,int>> pts = {{x1,y1},{x2,y2},{x3,y3},{x4,y4}};\n    if (pts.size() != 4) return false;\n    if (!isValidRect(x1,y1,x2,y2,x3,y3,x4,y4)) return false;\n    if (dotOnSeg(x1,y1,x2,y2) || dotOnSeg(x2,y2,x3,y3) || \n        dotOnSeg(x3,y3,x4,y4) || dotOnSeg(x4,y4,x1,y1)) return false;\n    if (segUsed(x1,y1,x2,y2) || segUsed(x2,y2,x3,y3) || \n        segUsed(x3,y3,x4,y4) || segUsed(x4,y4,x1,y1)) return false;\n    \n    dots.insert({x1,y1});\n    addSeg(x1,y1,x2,y2); addSeg(x2,y2,x3,y3);\n    addSeg(x3,y3,x4,y4); addSeg(x4,y4,x1,y1);\n    ops.push_back({x1,y1,x2,y2,x3,y3,x4,y4});\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    c = (N-1) / 2;\n    for (int i = 0; i < M; i++) { int x, y; cin >> x >> y; dots.insert({x, y}); }\n    \n    auto tstart = chrono::steady_clock::now();\n    mt19937 rng(42);\n    \n    int fails = 0;\n    while (chrono::duration<double>(chrono::steady_clock::now() - tstart).count() < 4.5) {\n        vector<pair<int,int>> dl(dots.begin(), dots.end());\n        shuffle(dl.begin(), dl.end(), rng);\n        int sz = min((int)dl.size(), 100);\n        \n        vector<tuple<long long, array<int,8>>> candidates;\n        \n        for (int i = 0; i < sz; i++) {\n            for (int j = 0; j < sz; j++) {\n                if (i == j) continue;\n                for (int k = 0; k < sz; k++) {\n                    if (k == i || k == j) continue;\n                    auto [ax, ay] = dl[i];\n                    auto [bx, by] = dl[j];\n                    auto [cx, cy] = dl[k];\n                    \n                    // Try: new point D, with corners D-A-B-C (A opposite to C, B opposite to D)\n                    // D = A + C - B\n                    int dx = ax + cx - bx, dy = ay + cy - by;\n                    if (inGrid(dx, dy) && !dots.count({dx, dy})) {\n                        long long w = wt(dx, dy);\n                        candidates.push_back({w, {dx, dy, ax, ay, bx, by, cx, cy}});\n                    }\n                }\n            }\n        }\n        \n        sort(candidates.begin(), candidates.end(), greater<>());\n        \n        bool found = false;\n        for (auto& [w, arr] : candidates) {\n            if (tryAdd(arr[0],arr[1],arr[2],arr[3],arr[4],arr[5],arr[6],arr[7])) {\n                found = true;\n                break;\n            }\n        }\n        \n        if (!found) {\n            if (++fails > 200) break;\n        } else {\n            fails = 0;\n        }\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto& op : ops) {\n        for (int i = 0; i < 8; i++) cout << op[i] << \" \\n\"[i==7];\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 10;\n\nstruct State {\n    int grid[N][N];\n    \n    State() { memset(grid, 0, sizeof(grid)); }\n    \n    int countEmpty() const {\n        int cnt = 0;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] == 0) cnt++;\n        return cnt;\n    }\n    \n    void place(int p, int flavor) {\n        int cnt = 0;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] == 0 && ++cnt == p) { grid[i][j] = flavor; return; }\n    }\n    \n    void tilt(char dir) {\n        if (dir == 'F') {\n            for (int j = 0; j < N; j++) {\n                int w = 0;\n                for (int i = 0; i < N; i++) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[w++][j] = v; }\n            }\n        } else if (dir == 'B') {\n            for (int j = 0; j < N; j++) {\n                int w = N - 1;\n                for (int i = N - 1; i >= 0; i--) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[w--][j] = v; }\n            }\n        } else if (dir == 'L') {\n            for (int i = 0; i < N; i++) {\n                int w = 0;\n                for (int j = 0; j < N; j++) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[i][w++] = v; }\n            }\n        } else {\n            for (int i = 0; i < N; i++) {\n                int w = N - 1;\n                for (int j = N - 1; j >= 0; j--) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[i][w--] = v; }\n            }\n        }\n    }\n    \n    long long calcScore() const {\n        bool vis[N][N] = {};\n        long long sum = 0;\n        int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (grid[i][j] && !vis[i][j]) {\n                    int f = grid[i][j], sz = 0;\n                    queue<pair<int,int>> q; q.push({i, j}); vis[i][j] = true;\n                    while (!q.empty()) {\n                        auto [x, y] = q.front(); q.pop(); sz++;\n                        for (int d = 0; d < 4; d++) {\n                            int nx = x + dx[d], ny = y + dy[d];\n                            if (nx >= 0 && nx < N && ny >= 0 && ny < N && !vis[nx][ny] && grid[nx][ny] == f) {\n                                vis[nx][ny] = true; q.push({nx, ny});\n                            }\n                        }\n                    }\n                    sum += (long long)sz * sz;\n                }\n            }\n        }\n        return sum;\n    }\n};\n\nmt19937 rng(12345);\nconst char dirs[] = {'F', 'B', 'L', 'R'};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int f[101];\n    for (int t = 1; t <= 100; t++) cin >> f[t];\n    \n    State state;\n    \n    for (int t = 1; t <= 100; t++) {\n        int p; cin >> p;\n        state.place(p, f[t]);\n        \n        int depth = min(12, 100 - t);\n        int numSims = 25;\n        \n        char bestDir = 'F';\n        long long bestScore = -1;\n        \n        for (char dir : dirs) {\n            long long totalScore = 0;\n            \n            for (int sim = 0; sim < numSims; sim++) {\n                State s = state;\n                s.tilt(dir);\n                \n                for (int step = 1; step <= depth && t + step <= 100; step++) {\n                    int empty = s.countEmpty();\n                    if (empty == 0) break;\n                    int randPos = (rng() % empty) + 1;\n                    s.place(randPos, f[t + step]);\n                    \n                    // Greedy tilt\n                    char simBest = 'F';\n                    long long simBestScore = -1;\n                    for (char d : dirs) {\n                        State tmp = s;\n                        tmp.tilt(d);\n                        long long sc = tmp.calcScore();\n                        if (sc > simBestScore) { simBestScore = sc; simBest = d; }\n                    }\n                    s.tilt(simBest);\n                }\n                totalScore += s.calcScore();\n            }\n            \n            if (totalScore > bestScore) {\n                bestScore = totalScore;\n                bestDir = dir;\n            }\n        }\n        \n        state.tilt(bestDir);\n        cout << bestDir << '\\n' << flush;\n    }\n    \n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\ndouble eps;\n\nvector<int> get_sorted_degrees(const string& s) {\n    vector<int> deg(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 (s[idx++] == '1') {\n                deg[i]++;\n                deg[j]++;\n            }\n        }\n    }\n    sort(deg.begin(), deg.end());\n    return deg;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    cin >> M >> eps;\n    \n    // Better N selection based on theoretical analysis\n    // Need larger N for higher noise to maintain distinguishability\n    double noise_factor = (eps < 0.001) ? 1.0 : 1.0 / max(0.2, 1.0 - 2.0 * eps);\n    \n    // Base N on M and noise\n    if (eps < 0.01) {\n        N = (int)ceil(sqrt(2.0 * M)) + 2;\n    } else if (eps < 0.05) {\n        N = (int)ceil(sqrt(2.5 * M)) + 4;\n    } else if (eps < 0.15) {\n        N = (int)ceil(sqrt(3.0 * M * noise_factor)) + 8;\n    } else if (eps < 0.25) {\n        N = (int)ceil(sqrt(4.0 * M * noise_factor)) + 15;\n    } else if (eps < 0.35) {\n        N = (int)ceil(sqrt(5.0 * M * noise_factor)) + 25;\n    } else {\n        N = (int)ceil(sqrt(6.0 * M * noise_factor)) + 35;\n    }\n    \n    N = max(N, (int)(2.0 * sqrt(M)));\n    N = max(N, 8);\n    N = min(N, 100);\n    \n    cout << N << \"\\n\";\n    \n    int total = N * (N - 1) / 2;\n    \n    vector<string> G(M);\n    vector<vector<double>> expected_deg(M);\n    \n    // Create M graphs with linearly spaced edge counts\n    for (int i = 0; i < M; i++) {\n        string s(total, '0');\n        long long edges = (M > 1) ? ((long long)i * total / (M - 1)) : 0;\n        \n        // Fill edges in a pattern that creates varied degree distribution\n        int idx = 0;\n        int filled = 0;\n        for (int a = 0; a < N && filled < edges; a++) {\n            for (int b = a + 1; b < N && filled < edges; b++) {\n                int pos = a * (2 * N - a - 1) / 2 + (b - a - 1);\n                s[pos] = '1';\n                filled++;\n            }\n        }\n        \n        G[i] = s;\n        \n        // Compute expected degree sequence after noise\n        vector<int> deg = get_sorted_degrees(s);\n        expected_deg[i].resize(N);\n        double transform = 1.0 - 2.0 * eps;\n        double base = (N - 1) * eps;\n        for (int j = 0; j < N; j++) {\n            expected_deg[i][j] = deg[j] * transform + base;\n        }\n        \n        cout << s << \"\\n\";\n    }\n    cout.flush();\n    \n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n        \n        vector<int> deg_h = get_sorted_degrees(H);\n        \n        int best = 0;\n        double best_score = 1e18;\n        \n        for (int i = 0; i < M; i++) {\n            // Weighted L2 distance - weight more heavily at extremes\n            double score = 0;\n            for (int j = 0; j < N; j++) {\n                double diff = deg_h[j] - expected_deg[i][j];\n                // Weight endpoints more (more informative)\n                double weight = 1.0 + 0.5 * (abs(j - N/2.0) / (N/2.0));\n                score += weight * diff * diff;\n            }\n            \n            if (score < best_score) {\n                best_score = score;\n                best = i;\n            }\n        }\n        \n        cout << best << \"\\n\";\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, D, K;\nvector<array<int,3>> edges;\nvector<vector<pair<int,int>>> adj;\nvector<vector<int>> adjEdge;\nmt19937 rng(42);\nconst long long INF = 1e9;\n\nvector<long long> dijkstraMask(int src, const vector<bool>& excl) {\n    vector<long long> dist(N, INF);\n    priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> pq;\n    dist[src] = 0;\n    pq.push({0, src});\n    while (!pq.empty()) {\n        auto [d, u] = pq.top(); pq.pop();\n        if (d > dist[u]) continue;\n        for (size_t i = 0; i < adj[u].size(); i++) {\n            if (excl[adjEdge[u][i]]) continue;\n            auto [v, w] = adj[u][i];\n            if (dist[u] + w < dist[v]) {\n                dist[v] = dist[u] + w;\n                pq.push({dist[v], v});\n            }\n        }\n    }\n    return dist;\n}\n\nint numSamples;\nvector<int> samples;\nvector<vector<long long>> origDist;\nvector<int> assign_;\nvector<int> cnt;\n\ndouble evalDay(int d) {\n    vector<bool> excl(M, false);\n    for (int e = 0; e < M; e++) if (assign_[e] == d) excl[e] = true;\n    double tot = 0;\n    for (int i = 0; i < numSamples; i++) {\n        auto dist = dijkstraMask(samples[i], excl);\n        for (int v = 0; v < N; v++) if (v != samples[i])\n            tot += min(dist[v], INF) - origDist[i][v];\n    }\n    return tot;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    auto start = chrono::steady_clock::now();\n    \n    cin >> N >> M >> D >> K;\n    edges.resize(M); adj.resize(N); adjEdge.resize(N);\n    \n    for (int i = 0; i < M; i++) {\n        int u, v, w; cin >> u >> v >> w; u--; v--;\n        edges[i] = {u, v, w};\n        adj[u].push_back({v, w}); adj[v].push_back({u, w});\n        adjEdge[u].push_back(i); adjEdge[v].push_back(i);\n    }\n    for (int i = 0; i < N; i++) { int x, y; cin >> x >> y; }\n    \n    vector<bool> noEdge(M, false);\n    vector<long long> crit(M);\n    for (int e = 0; e < M; e++) {\n        noEdge[e] = true;\n        auto dist = dijkstraMask(edges[e][0], noEdge);\n        crit[e] = dist[edges[e][1]] - edges[e][2];\n        noEdge[e] = false;\n    }\n    \n    numSamples = min(55, N);\n    samples.resize(N); iota(samples.begin(), samples.end(), 0);\n    shuffle(samples.begin(), samples.end(), rng);\n    samples.resize(numSamples);\n    \n    origDist.resize(numSamples);\n    for (int i = 0; i < numSamples; i++) origDist[i] = dijkstraMask(samples[i], noEdge);\n    \n    double globalBest = 1e18;\n    vector<int> globalBestAssign;\n    \n    for (int restart = 0; restart < 3; restart++) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > 5.0) break;\n        \n        vector<int> order(M); iota(order.begin(), order.end(), 0);\n        if (restart == 0) {\n            sort(order.begin(), order.end(), [&](int a, int b) { return crit[a] > crit[b]; });\n        } else {\n            shuffle(order.begin(), order.end(), rng);\n            sort(order.begin(), order.end(), [&](int a, int b) { return crit[a] > crit[b]; });\n        }\n        \n        assign_.assign(M, 0);\n        cnt.assign(D + 1, 0);\n        vector<set<int>> dayVertices(D + 1);\n        \n        for (int e : order) {\n            int u = edges[e][0], v = edges[e][1];\n            int best = 1, bestScore = INT_MAX;\n            for (int d = 1; d <= D; d++) {\n                if (cnt[d] >= K) continue;\n                int conflict = (dayVertices[d].count(u) ? 1 : 0) + (dayVertices[d].count(v) ? 1 : 0);\n                int score = conflict * 10000 + cnt[d] + (restart > 0 ? (int)(rng() % 100) : 0);\n                if (score < bestScore) { bestScore = score; best = d; }\n            }\n            assign_[e] = best; cnt[best]++;\n            dayVertices[best].insert(u); dayVertices[best].insert(v);\n        }\n        \n        vector<double> dayCost(D + 1);\n        double cur = 0;\n        for (int d = 1; d <= D; d++) { dayCost[d] = evalDay(d); cur += dayCost[d]; }\n        \n        double bestScore = cur;\n        vector<int> bestAssign = assign_;\n        double temp = max(1.0, cur / D / 3);\n        int noImprove = 0;\n        \n        while (true) {\n            now = chrono::steady_clock::now();\n            elapsed = chrono::duration<double>(now - start).count();\n            double timePerRestart = 5.3 / 3;\n            if (elapsed > (restart + 1) * timePerRestart || elapsed > 5.3) break;\n            \n            if (noImprove > 500) {\n                temp = max(temp, bestScore / D / 10);\n                noImprove = 0;\n            }\n            \n            int worstDay = 1;\n            for (int d = 2; d <= D; d++) if (dayCost[d] > dayCost[worstDay]) worstDay = d;\n            \n            int moveType = rng() % 5;\n            \n            if (moveType < 2) {\n                int e1 = rng() % M, e2 = rng() % M;\n                if (assign_[e1] == assign_[e2]) continue;\n                int d1 = assign_[e1], d2 = assign_[e2];\n                \n                swap(assign_[e1], assign_[e2]);\n                double nc1 = evalDay(d1), nc2 = evalDay(d2);\n                double delta = (nc1 + nc2) - (dayCost[d1] + dayCost[d2]);\n                \n                if (delta < 0 || (double)(rng() % 1000000) / 1000000 < exp(-delta / temp)) {\n                    dayCost[d1] = nc1; dayCost[d2] = nc2; cur += delta;\n                    if (cur < bestScore) { bestScore = cur; bestAssign = assign_; noImprove = 0; }\n                    else noImprove++;\n                } else { swap(assign_[e1], assign_[e2]); noImprove++; }\n            } else if (moveType == 2) {\n                int e = rng() % M;\n                int oldD = assign_[e], newD = rng() % D + 1;\n                if (newD == oldD || cnt[newD] >= K) continue;\n                \n                assign_[e] = newD; cnt[oldD]--; cnt[newD]++;\n                double nc1 = evalDay(oldD), nc2 = evalDay(newD);\n                double delta = (nc1 + nc2) - (dayCost[oldD] + dayCost[newD]);\n                \n                if (delta < 0 || (double)(rng() % 1000000) / 1000000 < exp(-delta / temp)) {\n                    dayCost[oldD] = nc1; dayCost[newD] = nc2; cur += delta;\n                    if (cur < bestScore) { bestScore = cur; bestAssign = assign_; noImprove = 0; }\n                    else noImprove++;\n                } else { assign_[e] = oldD; cnt[oldD]++; cnt[newD]--; noImprove++; }\n            } else {\n                vector<int> worstEdges;\n                for (int e = 0; e < M; e++) if (assign_[e] == worstDay) worstEdges.push_back(e);\n                if (worstEdges.empty()) continue;\n                int e = worstEdges[rng() % worstEdges.size()];\n                int newD = rng() % D + 1;\n                if (newD == worstDay || cnt[newD] >= K) continue;\n                \n                assign_[e] = newD; cnt[worstDay]--; cnt[newD]++;\n                double nc1 = evalDay(worstDay), nc2 = evalDay(newD);\n                double delta = (nc1 + nc2) - (dayCost[worstDay] + dayCost[newD]);\n                \n                if (delta < 0 || (double)(rng() % 1000000) / 1000000 < exp(-delta / temp)) {\n                    dayCost[worstDay] = nc1; dayCost[newD] = nc2; cur += delta;\n                    if (cur < bestScore) { bestScore = cur; bestAssign = assign_; noImprove = 0; }\n                    else noImprove++;\n                } else { assign_[e] = worstDay; cnt[worstDay]++; cnt[newD]--; noImprove++; }\n            }\n            temp *= 0.999995;\n            if (temp < 0.1) temp = 0.1;\n        }\n        \n        if (bestScore < globalBest) {\n            globalBest = bestScore;\n            globalBestAssign = bestAssign;\n        }\n    }\n    \n    for (int i = 0; i < M; i++) cout << globalBestAssign[i] << \" \\n\"[i == M-1];\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nint D;\nstring f[2][15], r[2][15];\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D;\n    for (int i = 0; i < 2; i++) {\n        for (int k = 0; k < D; k++) cin >> f[i][k];\n        for (int k = 0; k < D; k++) cin >> r[i][k];\n    }\n    \n    vector<int> b[2];\n    for (int i = 0; i < 2; i++) b[i].assign(D * D * D, 0);\n    \n    auto idx = [&](int x, int y, int z) { return x * D * D + y * D + z; };\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    int n = 0;\n    \n    // Step 1: Create large shared blocks from cells valid in both at same position\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                bool v0 = (f[0][z][x] == '1' && r[0][z][y] == '1');\n                bool v1 = (f[1][z][x] == '1' && r[1][z][y] == '1');\n                if (v0 && v1 && b[0][idx(x,y,z)] == 0) {\n                    n++;\n                    queue<tuple<int,int,int>> q;\n                    q.push({x, y, z});\n                    b[0][idx(x,y,z)] = b[1][idx(x,y,z)] = n;\n                    while (!q.empty()) {\n                        auto [cx, cy, cz] = q.front(); q.pop();\n                        for (int d = 0; d < 6; d++) {\n                            int nx = cx + dx[d], ny = cy + dy[d], nz = cz + dz[d];\n                            if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D) {\n                                bool nv0 = (f[0][nz][nx] == '1' && r[0][nz][ny] == '1');\n                                bool nv1 = (f[1][nz][nx] == '1' && r[1][nz][ny] == '1');\n                                if (nv0 && nv1 && b[0][idx(nx,ny,nz)] == 0) {\n                                    b[0][idx(nx,ny,nz)] = b[1][idx(nx,ny,nz)] = n;\n                                    q.push({nx, ny, nz});\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    // Step 2: Find remaining constraints for each arrangement\n    vector<tuple<int,int,int>> extra[2];\n    for (int arr = 0; arr < 2; arr++) {\n        set<int> needFront, needRight;\n        for (int z = 0; z < D; z++) {\n            for (int x = 0; x < D; x++) if (f[arr][z][x] == '1') needFront.insert(z * D + x);\n            for (int y = 0; y < D; y++) if (r[arr][z][y] == '1') needRight.insert(z * D + y);\n        }\n        \n        // Remove constraints already satisfied by shared blocks\n        for (int x = 0; x < D; x++) {\n            for (int y = 0; y < D; y++) {\n                for (int z = 0; z < D; z++) {\n                    if (b[arr][idx(x,y,z)] > 0) {\n                        needFront.erase(z * D + x);\n                        needRight.erase(z * D + y);\n                    }\n                }\n            }\n        }\n        \n        // Greedily pick unit blocks for remaining constraints\n        while (!needFront.empty() || !needRight.empty()) {\n            int bestX = -1, bestY = -1, bestZ = -1, bestScore = -1;\n            for (int z = 0; z < D; z++) {\n                for (int x = 0; x < D; x++) {\n                    if (f[arr][z][x] != '1') continue;\n                    for (int y = 0; y < D; y++) {\n                        if (r[arr][z][y] != '1') continue;\n                        int score = 0;\n                        if (needFront.count(z * D + x)) score++;\n                        if (needRight.count(z * D + y)) score++;\n                        if (score > bestScore) {\n                            bestScore = score;\n                            bestX = x; bestY = y; bestZ = z;\n                        }\n                    }\n                }\n            }\n            if (bestScore <= 0) break;\n            extra[arr].push_back({bestX, bestY, bestZ});\n            needFront.erase(bestZ * D + bestX);\n            needRight.erase(bestZ * D + bestY);\n        }\n    }\n    \n    // Step 3: Assign unit blocks (shared between arrangements)\n    int m1 = extra[0].size(), m2 = extra[1].size();\n    int totalExtra = max(m1, m2);\n    \n    for (int i = 0; i < m1; i++) {\n        auto [x, y, z] = extra[0][i];\n        b[0][idx(x,y,z)] = n + 1 + i;\n    }\n    for (int i = 0; i < m2; i++) {\n        auto [x, y, z] = extra[1][i];\n        b[1][idx(x,y,z)] = n + 1 + i;\n    }\n    \n    n += totalExtra;\n    \n    cout << n << \"\\n\";\n    for (int i = 0; i < 2; i++) {\n        for (int j = 0; j < D * D * D; j++) {\n            if (j) cout << \" \";\n            cout << b[i][j];\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, K;\nvector<pair<int,int>> V, R;\nvector<tuple<int,int,long long>> E;\nvector<vector<pair<int,int>>> adj;\n\ndouble dist(int i, int k) {\n    double dx = V[i].first - R[k].first, dy = V[i].second - R[k].second;\n    return sqrt(dx*dx + dy*dy);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    V.resize(N); R.resize(K); E.resize(M); adj.resize(N);\n    \n    for(int i = 0; i < N; i++) cin >> V[i].first >> V[i].second;\n    for(int j = 0; j < M; j++) {\n        int u, v; long long w;\n        cin >> u >> v >> w; u--; v--;\n        E[j] = {u, v, w};\n        adj[u].push_back({v, j});\n        adj[v].push_back({u, j});\n    }\n    for(int k = 0; k < K; k++) cin >> R[k].first >> R[k].second;\n    \n    // All-pairs shortest paths\n    vector<vector<long long>> distVV(N, vector<long long>(N, LLONG_MAX/2));\n    vector<vector<int>> parentV(N, vector<int>(N, -1));\n    \n    for(int s = 0; s < N; s++) {\n        distVV[s][s] = 0;\n        priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> pq;\n        pq.push({0, s});\n        while(!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if(d > distVV[s][u]) continue;\n            for(auto [v, eid] : adj[u]) {\n                long long w = get<2>(E[eid]);\n                if(distVV[s][u] + w < distVV[s][v]) {\n                    distVV[s][v] = distVV[s][u] + w;\n                    parentV[s][v] = u;\n                    pq.push({distVV[s][v], v});\n                }\n            }\n        }\n    }\n    \n    vector<int> bestP(N, 0), bestB(M, 0), bestAssign(K);\n    long long bestCost = LLONG_MAX;\n    \n    // Try different weight factors for initial assignment\n    for(double factor : {0.0, 0.001, 0.01, 0.05, 0.1, 0.2}) {\n        vector<int> assignment(K);\n        for(int k = 0; k < K; k++) {\n            int best = -1; double bestScore = 1e18;\n            for(int i = 0; i < N; i++) {\n                double d = dist(i, k);\n                if(d > 5000) continue;\n                double score = d * d + factor * distVV[0][i];\n                if(score < bestScore) { bestScore = score; best = i; }\n            }\n            assignment[k] = best;\n        }\n        \n        auto computeP = [&]() {\n            vector<int> P(N, 0);\n            for(int k = 0; k < K; k++) {\n                int v = assignment[k];\n                P[v] = max(P[v], (int)ceil(dist(v, k) - 1e-9));\n            }\n            return P;\n        };\n        \n        auto buildSteinerTree = [&](const vector<int>& P) {\n            vector<int> terminals; terminals.push_back(0);\n            for(int i = 0; i < N; i++) if(P[i] > 0 && i != 0) terminals.push_back(i);\n            \n            vector<int> B(M, 0);\n            if(terminals.size() <= 1) return B;\n            \n            set<int> inTree; inTree.insert(0);\n            vector<long long> minD(N, LLONG_MAX);\n            vector<int> minFrom(N, -1);\n            for(int t : terminals) if(t != 0) minD[t] = distVV[0][t];\n            \n            while(inTree.size() < terminals.size()) {\n                int best = -1;\n                for(int t : terminals) if(inTree.find(t) == inTree.end()) {\n                    if(best == -1 || minD[t] < minD[best]) best = t;\n                }\n                if(best == -1) break;\n                \n                inTree.insert(best);\n                int cur = best, src = minFrom[best] == -1 ? 0 : minFrom[best];\n                while(cur != src) {\n                    int p = parentV[src][cur];\n                    for(auto [nxt, eid] : adj[cur]) if(nxt == p) { B[eid] = 1; break; }\n                    cur = p;\n                }\n                \n                for(int t : terminals) if(inTree.find(t) == inTree.end()) {\n                    if(distVV[best][t] < minD[t]) { minD[t] = distVV[best][t]; minFrom[t] = best; }\n                }\n            }\n            return B;\n        };\n        \n        auto getReachable = [&](const vector<int>& B) {\n            vector<bool> visited(N, false);\n            queue<int> q; q.push(0); visited[0] = true;\n            vector<int> reach;\n            while(!q.empty()) {\n                int u = q.front(); q.pop(); reach.push_back(u);\n                for(auto [v, eid] : adj[u]) if(B[eid] && !visited[v]) {\n                    visited[v] = true; q.push(v);\n                }\n            }\n            return reach;\n        };\n        \n        auto calcCost = [&](const vector<int>& P, const vector<int>& B) {\n            long long cost = 0;\n            for(int i = 0; i < N; i++) cost += (long long)P[i] * P[i];\n            for(int j = 0; j < M; j++) if(B[j]) cost += get<2>(E[j]);\n            return cost;\n        };\n        \n        vector<int> P = computeP();\n        vector<int> B = buildSteinerTree(P);\n        \n        // Local search using reachable vertices\n        for(int iter = 0; iter < 20; iter++) {\n            vector<int> reach = getReachable(B);\n            bool improved = false;\n            for(int k = 0; k < K; k++) {\n                int curV = assignment[k];\n                double curD = dist(curV, k);\n                for(int v : reach) {\n                    double d = dist(v, k);\n                    if(d < curD - 0.01 && d <= 5000) {\n                        assignment[k] = v; curV = v; curD = d;\n                        improved = true;\n                    }\n                }\n            }\n            if(!improved) break;\n            P = computeP();\n            B = buildSteinerTree(P);\n        }\n        \n        long long cost = calcCost(P, B);\n        if(cost < bestCost) {\n            bestCost = cost; bestP = P; bestB = B; bestAssign = assignment;\n        }\n    }\n    \n    for(int i = 0; i < N; i++) cout << bestP[i] << \" \\n\"[i==N-1];\n    for(int j = 0; j < M; j++) cout << bestB[j] << \" \\n\"[j==M-1];\n    \n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nint b[N][N];\nvector<tuple<int, int, int, int>> ops;\n\nvoid do_swap(int x1, int y1, int x2, int y2) {\n    ops.push_back({x1, y1, x2, y2});\n    swap(b[x1][y1], b[x2][y2]);\n}\n\nvoid sift_down(int x, int y) {\n    while (x < N - 1) {\n        int min_child_y = (b[x + 1][y + 1] < b[x + 1][y]) ? (y + 1) : y;\n        if (b[x][y] > b[x + 1][min_child_y]) {\n            do_swap(x, y, x + 1, min_child_y);\n            x = x + 1;\n            y = min_child_y;\n        } else {\n            break;\n        }\n    }\n}\n\nbool has_violation(int x, int y) {\n    if (x >= N - 1) return false;\n    return b[x][y] > b[x + 1][y] || b[x][y] > b[x + 1][y + 1];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int x = 0; x < N; x++) {\n        for (int y = 0; y <= x; y++) {\n            cin >> b[x][y];\n        }\n    }\n    \n    // Process violations iteratively - prioritize by value (larger values first)\n    bool changed = true;\n    while (changed) {\n        changed = false;\n        // Collect all violations with their values\n        vector<tuple<int, int, int>> violations; // (value, x, y)\n        for (int x = N - 2; x >= 0; x--) {\n            for (int y = 0; y <= x; y++) {\n                if (has_violation(x, y)) {\n                    violations.push_back({b[x][y], x, y});\n                }\n            }\n        }\n        \n        // Sort by value descending (fix larger values first)\n        sort(violations.rbegin(), violations.rend());\n        \n        for (auto& [val, x, y] : violations) {\n            if (has_violation(x, y)) {\n                sift_down(x, y);\n                changed = true;\n            }\n        }\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto& [x1, y1, x2, y2] : ops) {\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;\nint ex, ey;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nvector<vector<int>> grid;\n\nvector<pair<int,int>> findReachableEmpty() {\n    vector<pair<int,int>> result;\n    vector<vector<bool>> vis(D, vector<bool>(D, false));\n    queue<pair<int,int>> q;\n    q.push({ex, ey});\n    vis[ex][ey] = true;\n    \n    while (!q.empty()) {\n        int x = q.front().first, y = q.front().second;\n        q.pop();\n        \n        // This is an empty square (entrance or regular empty)\n        if (!(x == ex && y == ey)) {\n            result.push_back({x, y});\n        }\n        \n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx >= 0 && nx < D && ny >= 0 && ny < D && !vis[nx][ny] && grid[nx][ny] == -1) {\n                vis[nx][ny] = true;\n                q.push({nx, ny});\n            }\n        }\n    }\n    return result;\n}\n\nvector<pair<int,int>> findReachableContainers() {\n    vector<pair<int,int>> result;\n    vector<vector<bool>> vis(D, vector<bool>(D, false));\n    queue<pair<int,int>> q;\n    q.push({ex, ey});\n    vis[ex][ey] = true;\n    \n    while (!q.empty()) {\n        int x = q.front().first, y = q.front().second;\n        q.pop();\n        \n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx >= 0 && nx < D && ny >= 0 && ny < D && !vis[nx][ny] && grid[nx][ny] != -2) {\n                vis[nx][ny] = true;\n                if (grid[nx][ny] >= 0) {\n                    // This is a container adjacent to reachable empty square\n                    result.push_back({nx, ny});\n                } else {\n                    // This is an empty square, continue searching\n                    q.push({nx, ny});\n                }\n            }\n        }\n    }\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D >> N;\n    ex = 0;\n    ey = (D - 1) / 2;\n    \n    grid.assign(D, vector<int>(D, -1));\n    \n    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n        grid[x][y] = -2;\n    }\n    \n    int total = D * D - 1 - N;\n    \n    // Placement phase\n    for (int iter = 0; iter < total; iter++) {\n        int t;\n        cin >> t;\n        \n        vector<pair<int,int>> reach = findReachableEmpty();\n        \n        // Simple strategy: place at the last reachable position (furthest from entrance in BFS order)\n        pair<int,int> best = reach.back();\n        \n        grid[best.first][best.second] = t;\n        cout << best.first << \" \" << best.second << endl;\n    }\n    \n    // Transport phase\n    for (int iter = 0; iter < total; iter++) {\n        vector<pair<int,int>> reachable = findReachableContainers();\n        \n        // Find container with smallest number\n        pair<int,int> best = reachable[0];\n        for (auto& pos : reachable) {\n            if (grid[pos.first][pos.second] < grid[best.first][best.second]) {\n                best = pos;\n            }\n        }\n        \n        cout << best.first << \" \" << best.second << \"\\n\";\n        grid[best.first][best.second] = -1;\n    }\n    \n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint n, m;\nint dx[] = {0, 0, 1, -1};\nint dy[] = {1, -1, 0, 0};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> n >> m;\n    vector<vector<int>> grid(n, vector<int>(n));\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < n; j++)\n            cin >> grid[i][j];\n    \n    // Output original grid first as valid baseline\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cout << grid[i][j];\n            if (j < n-1) cout << \" \";\n        }\n        cout << \"\\n\";\n    }\n    cout.flush();\n    \n    // Colors adjacent to 0 (boundary colors)\n    set<int> adjToZero;\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) {\n                adjToZero.insert(grid[i][j]);\n            }\n        }\n    }\n    \n    // Track adjacency edge counts\n    map<pair<int,int>, int> edgeCount;\n    auto addEdge = [&](int a, int b) {\n        if (a > b) swap(a, b);\n        if (a != b) edgeCount[{a, b}]++;\n    };\n    auto removeEdge = [&](int a, int b) {\n        if (a > b) swap(a, b);\n        if (a != b) edgeCount[{a, b}]--;\n    };\n    \n    auto best = grid;\n    \n    // Initialize edge counts\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            int c = best[i][j];\n            if (i == 0 || i == n-1 || j == 0 || j == n-1) {\n                addEdge(0, c);\n            }\n            // Only count right and down to avoid double counting\n            if (j + 1 < n && best[i][j+1] != c) addEdge(c, best[i][j+1]);\n            if (i + 1 < n && best[i+1][j] != c) addEdge(c, best[i+1][j]);\n        }\n    }\n    \n    // Required adjacencies (those with count > 0)\n    set<pair<int,int>> required;\n    for (auto& [p, cnt] : edgeCount) {\n        if (cnt > 0) required.insert(p);\n    }\n    \n    vector<int> colorCount(m + 1, 0);\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < n; j++)\n            colorCount[best[i][j]]++;\n    \n    auto start = chrono::steady_clock::now();\n    \n    vector<pair<int,int>> candidates;\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < n; j++)\n            candidates.push_back({i, j});\n    \n    mt19937 rng(12345);\n    shuffle(candidates.begin(), candidates.end(), rng);\n    \n    for (auto [i, j] : candidates) {\n        auto elapsed = chrono::steady_clock::now() - start;\n        if (chrono::duration_cast<chrono::milliseconds>(elapsed).count() > 1800) break;\n        \n        int c = best[i][j];\n        if (c == 0) continue;\n        if (colorCount[c] <= 1) continue;\n        \n        // Check all neighbors are colors that can be adjacent to 0\n        bool canRemove = true;\n        for (int d = 0; d < 4; d++) {\n            int ni = i + dx[d], nj = j + dy[d];\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                int nc = best[ni][nj];\n                if (nc != 0 && adjToZero.find(nc) == adjToZero.end()) {\n                    canRemove = false;\n                    break;\n                }\n            }\n        }\n        if (!canRemove) continue;\n        \n        // Cell must touch 0 (boundary or adjacent to 0 cell)\n        bool touchesZero = (i == 0 || i == n-1 || j == 0 || j == n-1);\n        for (int d = 0; d < 4 && !touchesZero; d++) {\n            int ni = i + dx[d], nj = j + dy[d];\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n && best[ni][nj] == 0) {\n                touchesZero = true;\n            }\n        }\n        if (!touchesZero) continue;\n        \n        // Must have same-color neighbor for connectivity\n        bool hasNeighbor = false;\n        for (int d = 0; d < 4; d++) {\n            int ni = i + dx[d], nj = j + dy[d];\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n && best[ni][nj] == c) {\n                hasNeighbor = true;\n                break;\n            }\n        }\n        if (!hasNeighbor) continue;\n        \n        // Try removal - track edge changes\n        vector<pair<int,int>> lostEdges, gainedEdges;\n        \n        // Lost: boundary edge if on boundary\n        if (i == 0 || i == n-1 || j == 0 || j == n-1) {\n            lostEdges.push_back({min(0,c), max(0,c)});\n        }\n        \n        // Lost/gained from neighbors\n        for (int d = 0; d < 4; d++) {\n            int ni = i + dx[d], nj = j + dy[d];\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                int nc = best[ni][nj];\n                if (nc != c && nc != 0) {\n                    lostEdges.push_back({min(c,nc), max(c,nc)});\n                    gainedEdges.push_back({0, nc});\n                }\n            }\n        }\n        \n        // Check if any required edge would be lost\n        bool wouldBreak = false;\n        map<pair<int,int>, int> delta;\n        for (auto& e : lostEdges) delta[e]--;\n        for (auto& e : gainedEdges) delta[e]++;\n        \n        for (auto& [e, d] : delta) {\n            int newCount = edgeCount[e] + d;\n            if (required.count(e) && newCount <= 0) {\n                wouldBreak = true;\n                break;\n            }\n        }\n        if (wouldBreak) continue;\n        \n        // Check connectivity of color c after removal\n        best[i][j] = 0;\n        \n        int si = -1, sj = -1, total = 0;\n        for (int x = 0; x < n; x++) {\n            for (int y = 0; y < n; y++) {\n                if (best[x][y] == c) {\n                    if (si < 0) { si = x; sj = y; }\n                    total++;\n                }\n            }\n        }\n        \n        bool connected = true;\n        if (total > 0) {\n            vector<vector<bool>> vis(n, vector<bool>(n, false));\n            queue<pair<int,int>> q;\n            q.push({si, sj});\n            vis[si][sj] = true;\n            int found = 1;\n            while (!q.empty()) {\n                auto [x, y] = q.front(); q.pop();\n                for (int d = 0; d < 4; d++) {\n                    int nx = x + dx[d], ny = y + dy[d];\n                    if (nx >= 0 && nx < n && ny >= 0 && ny < n && !vis[nx][ny] && best[nx][ny] == c) {\n                        vis[nx][ny] = true;\n                        found++;\n                        q.push({nx, ny});\n                    }\n                }\n            }\n            connected = (found == total);\n        }\n        \n        if (!connected) {\n            best[i][j] = c;\n            continue;\n        }\n        \n        // Apply edge changes\n        for (auto& [e, d] : delta) {\n            edgeCount[e] += d;\n        }\n        colorCount[c]--;\n    }\n    \n    // Output improved solution\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cout << best[i][j];\n            if (j < n-1) cout << \" \";\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, D, Q;\nint query_count = 0;\n\nchar query(const vector<int>& L, const vector<int>& R) {\n    cout << L.size() << \" \" << R.size();\n    for (int x : L) cout << \" \" << x;\n    for (int x : R) cout << \" \" << x;\n    cout << \"\\n\" << flush;\n    char c;\n    cin >> c;\n    query_count++;\n    return c;\n}\n\nvector<int> sorted_items;\n\nvoid merge_sort(int l, int r) {\n    if (r - l <= 1) return;\n    int m = (l + r) / 2;\n    merge_sort(l, m);\n    merge_sort(m, r);\n    \n    vector<int> left(sorted_items.begin() + l, sorted_items.begin() + m);\n    vector<int> right(sorted_items.begin() + m, sorted_items.begin() + r);\n    \n    int i = 0, j = 0, k = l;\n    while (i < (int)left.size() && j < (int)right.size()) {\n        if (query_count >= Q) {\n            while (i < (int)left.size()) sorted_items[k++] = left[i++];\n            while (j < (int)right.size()) sorted_items[k++] = right[j++];\n            return;\n        }\n        char c = query({left[i]}, {right[j]});\n        if (c != '>') sorted_items[k++] = left[i++];\n        else sorted_items[k++] = right[j++];\n    }\n    while (i < (int)left.size()) sorted_items[k++] = left[i++];\n    while (j < (int)right.size()) sorted_items[k++] = right[j++];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> D >> Q;\n    \n    sorted_items.resize(N);\n    iota(sorted_items.begin(), sorted_items.end(), 0);\n    merge_sort(0, N);\n    \n    vector<int> rank_of(N);\n    for (int i = 0; i < N; i++) rank_of[sorted_items[i]] = i;\n    \n    // Initial weight estimation\n    vector<double> w(N);\n    for (int i = 0; i < N; i++) w[i] = i + 1;\n    \n    // Use remaining queries for weight estimation\n    int est_budget = min((Q - query_count) / 2, N * 3);\n    \n    for (int j = N - 1; j >= 1 && est_budget > 0; j--) {\n        int lo = 1, hi = j;\n        while (lo < hi && est_budget > 0 && query_count < Q) {\n            int mid = (lo + hi) / 2;\n            vector<int> L, R = {sorted_items[j]};\n            for (int t = 0; t < mid; t++) L.push_back(sorted_items[t]);\n            char c = query(L, R);\n            est_budget--;\n            if (c == '>' || c == '=') hi = mid;\n            else lo = mid + 1;\n        }\n        double sum = 0;\n        for (int t = 0; t < lo; t++) sum += w[t];\n        w[j] = max(w[j], sum * 1.05);\n    }\n    \n    // Greedy assignment\n    vector<double> set_weight(D, 0);\n    vector<int> assignment(N);\n    vector<vector<int>> sets(D);\n    \n    for (int i = N - 1; i >= 0; i--) {\n        int item = sorted_items[i];\n        int best = 0;\n        for (int j = 1; j < D; j++)\n            if (set_weight[j] < set_weight[best]) best = j;\n        assignment[item] = best;\n        set_weight[best] += w[i];\n        sets[best].push_back(item);\n    }\n    \n    // Simple local search: try moving smallest item from heaviest to lightest set\n    for (int iter = 0; iter < 50 && query_count + 3 < Q; iter++) {\n        // Find heaviest and lightest sets by estimation\n        int heavy = 0, light = 0;\n        for (int i = 1; i < D; i++) {\n            if (set_weight[i] > set_weight[heavy]) heavy = i;\n            if (set_weight[i] < set_weight[light]) light = i;\n        }\n        \n        if (heavy == light || sets[heavy].size() <= 1) break;\n        \n        // Compare them\n        if (query_count >= Q) break;\n        char cmp = query(sets[heavy], sets[light]);\n        \n        if (cmp != '>') break; // Already balanced or wrong estimation\n        \n        // Find lightest item in heavy set\n        int min_item = sets[heavy][0];\n        int min_rank = rank_of[min_item];\n        for (int item : sets[heavy]) {\n            if (rank_of[item] < min_rank) {\n                min_rank = rank_of[item];\n                min_item = item;\n            }\n        }\n        \n        // Try moving it\n        vector<int> new_heavy, new_light = sets[light];\n        for (int item : sets[heavy])\n            if (item != min_item) new_heavy.push_back(item);\n        new_light.push_back(min_item);\n        \n        if (new_heavy.empty()) break;\n        if (query_count >= Q) break;\n        \n        char new_cmp = query(new_heavy, new_light);\n        \n        // Accept if balanced or reversed (but not too much)\n        if (new_cmp == '=' || new_cmp == '<') {\n            sets[heavy] = new_heavy;\n            sets[light] = new_light;\n            assignment[min_item] = light;\n            set_weight[heavy] -= w[min_rank];\n            set_weight[light] += w[min_rank];\n        } else {\n            break; // Can't improve\n        }\n    }\n    \n    while (query_count < Q) query({sorted_items[0]}, {sorted_items[1]});\n    \n    for (int i = 0; i < N; i++)\n        cout << assignment[i] << \" \\n\"[i == N - 1];\n    \n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::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    vector<int> pos(n + 1);\n    \n    for (int i = 0; i < m; i++) {\n        int h = n / m;\n        for (int j = 0; j < h; j++) {\n            int x;\n            cin >> x;\n            stacks[i].push_back(x);\n            pos[x] = i;\n        }\n    }\n    \n    vector<pair<int, int>> ops;\n    \n    for (int v = 1; v <= n; v++) {\n        int stack_id = pos[v];\n        \n        int idx = 0;\n        while (stacks[stack_id][idx] != v) idx++;\n        \n        if (idx < (int)stacks[stack_id].size() - 1) {\n            int move_start = idx + 1;\n            int bottom_box = stacks[stack_id][move_start];\n            \n            int max_moving = 0;\n            int min_moving = INT_MAX;\n            int cnt = (int)stacks[stack_id].size() - move_start;\n            \n            // Track which upcoming boxes are in our group\n            set<int> upcoming_in_group;\n            for (int j = move_start; j < (int)stacks[stack_id].size(); j++) {\n                int b = stacks[stack_id][j];\n                max_moving = max(max_moving, b);\n                min_moving = min(min_moving, b);\n                // Check next few boxes we'll need\n                if (b <= v + 10) {\n                    upcoming_in_group.insert(b);\n                }\n            }\n            \n            int best_dest = -1;\n            int best_score = INT_MIN;\n            \n            for (int i = 0; i < m; i++) {\n                if (i == stack_id) continue;\n                \n                int score = 0;\n                \n                if (stacks[i].empty()) {\n                    // Empty stack - very good, value based on min_moving\n                    // More valuable for groups with smaller min (more urgent)\n                    score = n * 3 + (n - min_moving);\n                } else {\n                    int min_in_dest = INT_MAX;\n                    for (int b : stacks[i]) {\n                        min_in_dest = min(min_in_dest, b);\n                    }\n                    \n                    if (min_in_dest > min_moving) {\n                        // Safe - our group won't be re-moved due to dest\n                        score = n * 3;\n                        \n                        // Bonus: if top > max_moving, good stacking\n                        if (stacks[i].back() > max_moving) {\n                            score += 50;\n                        }\n                    } else {\n                        // Unsafe - will be re-moved when extracting min_in_dest\n                        // Prefer later re-moves\n                        score = min_in_dest;\n                        \n                        // Penalty proportional to group size (bigger groups = worse to re-move)\n                        score -= cnt * 3;\n                    }\n                }\n                \n                // Penalty for tall stacks\n                score -= (int)stacks[i].size() * 2;\n                \n                // Bonus if upcoming boxes would be accessible\n                for (int ub : upcoming_in_group) {\n                    // Check if ub would be safe in this destination\n                    if (stacks[i].empty()) {\n                        score += 5;\n                    } else {\n                        int min_d = INT_MAX;\n                        for (int b : stacks[i]) min_d = min(min_d, b);\n                        if (min_d > ub) {\n                            score += 5;\n                        }\n                    }\n                }\n                \n                if (score > best_score) {\n                    best_score = score;\n                    best_dest = i;\n                }\n            }\n            \n            ops.push_back({bottom_box, best_dest + 1});\n            \n            for (int j = move_start; j < (int)stacks[stack_id].size(); j++) {\n                int b = stacks[stack_id][j];\n                stacks[best_dest].push_back(b);\n                pos[b] = best_dest;\n            }\n            stacks[stack_id].resize(move_start);\n        }\n        \n        ops.push_back({v, 0});\n        stacks[stack_id].pop_back();\n    }\n    \n    for (auto& [a, b] : ops) {\n        cout << a << \" \" << b << \"\\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;\nlong long totalD;\nmt19937 rng(42);\n\nint di[] = {0, 1, 0, -1};\nint dj[] = {1, 0, -1, 0};\nchar dirChar[] = {'R', 'D', 'L', 'U'};\n\nbool canMove(int i, int j, int dir) {\n    int ni = i + di[dir], nj = j + dj[dir];\n    if (ni < 0 || ni >= N || nj < 0 || nj >= N) return false;\n    if (dir == 0) return v[i][j] == '0';\n    if (dir == 1) return h[i][j] == '0';\n    if (dir == 2) return j > 0 && v[i][j-1] == '0';\n    return i > 0 && h[i-1][j] == '0';\n}\n\nlong double fastEvaluate(const string& path) {\n    int L = path.size();\n    vector<vector<int>> lastVisit(N, vector<int>(N, 0));\n    vector<vector<long long>> contrib(N, vector<long long>(N, 0));\n    long long contribSum = 0;\n    int ci = 0, cj = 0;\n    \n    auto move = [&](int t, char c) {\n        int dir = (c == 'R') ? 0 : (c == 'D') ? 1 : (c == 'L') ? 2 : 3;\n        ci += di[dir]; cj += dj[dir];\n        contribSum -= contrib[ci][cj];\n        contrib[ci][cj] = (long long)d[ci][cj] * t;\n        contribSum += contrib[ci][cj];\n    };\n    \n    for (int t = 1; t <= L; t++) move(t, path[t-1]);\n    \n    long double totalSum = 0;\n    for (int t = L + 1; t <= 2 * L; t++) {\n        totalSum += (long long)totalD * t - contribSum;\n        move(t, path[(t-1) % L]);\n    }\n    return totalSum / L;\n}\n\nstring generatePath(int mode) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    string path;\n    \n    function<void(int, int)> dfs = [&](int i, int j) {\n        visited[i][j] = true;\n        vector<pair<int, int>> children;\n        for (int dir = 0; dir < 4; dir++) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj] && canMove(i, j, dir)) {\n                children.push_back({d[ni][nj], dir});\n            }\n        }\n        \n        if (mode == 0) sort(children.begin(), children.end());\n        else if (mode == 1) sort(children.rbegin(), children.rend());\n        else shuffle(children.begin(), children.end(), rng);\n        \n        for (auto [dval, dir] : children) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (!visited[ni][nj]) {\n                path += dirChar[dir];\n                dfs(ni, nj);\n                path += dirChar[(dir + 2) % 4];\n            }\n        }\n    };\n    dfs(0, 0);\n    return path;\n}\n\nstring getLoopTo(int ti, int tj) {\n    vector<vector<int>> par(N, vector<int>(N, -1));\n    queue<pair<int,int>> bfs;\n    bfs.push({0, 0});\n    par[0][0] = -2;\n    \n    while (!bfs.empty()) {\n        auto [i, j] = bfs.front(); bfs.pop();\n        if (i == ti && j == tj) break;\n        for (int dir = 0; dir < 4; dir++) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && par[ni][nj] == -1 && canMove(i, j, dir)) {\n                par[ni][nj] = (dir + 2) % 4;\n                bfs.push({ni, nj});\n            }\n        }\n    }\n    \n    string toTarget, fromTarget;\n    int ci = ti, cj = tj;\n    while (ci != 0 || cj != 0) {\n        int pdir = par[ci][cj];\n        fromTarget += dirChar[pdir];\n        toTarget += dirChar[(pdir + 2) % 4];\n        ci += di[pdir]; cj += dj[pdir];\n    }\n    reverse(toTarget.begin(), toTarget.end());\n    return toTarget + fromTarget;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> 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    totalD = 0;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n            totalD += d[i][j];\n        }\n    \n    string bestPath;\n    long double bestScore = 1e18;\n    \n    auto tryPath = [&](const string& path) {\n        long double score = fastEvaluate(path);\n        if (score < bestScore) {\n            bestScore = score;\n            bestPath = path;\n        }\n        return score;\n    };\n    \n    // Deterministic orderings\n    for (int mode = 0; mode < 2; mode++) tryPath(generatePath(mode));\n    \n    // Random search\n    auto startTime = chrono::steady_clock::now();\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() < 1000) {\n        tryPath(generatePath(2));\n    }\n    \n    // Get top high-d cells for loop candidates\n    vector<tuple<int,int,int,string>> loopCandidates;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            if (i != 0 || j != 0)\n                loopCandidates.push_back({d[i][j], i, j, getLoopTo(i, j)});\n    sort(loopCandidates.rbegin(), loopCandidates.rend());\n    \n    // Try adding loops greedily\n    string currentBest = bestPath;\n    long double currentScore = bestScore;\n    \n    for (int iter = 0; iter < 3; iter++) {\n        for (int c = 0; c < min(15, (int)loopCandidates.size()); c++) {\n            auto& [dval, ti, tj, loop] = loopCandidates[c];\n            if (currentBest.size() + loop.size() > 100000) continue;\n            \n            string candidate = currentBest + loop;\n            long double score = fastEvaluate(candidate);\n            if (score < currentScore) {\n                currentScore = score;\n                currentBest = candidate;\n                if (score < bestScore) {\n                    bestScore = score;\n                    bestPath = currentBest;\n                }\n            }\n        }\n    }\n    \n    // Try multiple loops to same high-d cell\n    for (int c = 0; c < min(5, (int)loopCandidates.size()); c++) {\n        auto& [dval, ti, tj, loop] = loopCandidates[c];\n        string candidate = bestPath;\n        for (int rep = 1; rep <= 10 && candidate.size() + loop.size() <= 100000; rep++) {\n            candidate += loop;\n            tryPath(candidate);\n        }\n    }\n    \n    cout << bestPath << endl;\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, si, sj;\nvector<string> A;\nmap<char, vector<pair<int,int>>> charPos;\n\nint overlap(const string& a, const string& b) {\n    int maxOv = min((int)a.length(), (int)b.length());\n    for (int ov = maxOv; ov >= 1; ov--) {\n        if (a.substr(a.length() - ov) == b.substr(0, ov)) return ov;\n    }\n    return 0;\n}\n\nstring buildSuperstring(vector<string>& t) {\n    vector<string> remaining = t;\n    \n    while (remaining.size() > 1) {\n        int bestOv = -1, bestI = -1, bestJ = -1;\n        \n        for (int i = 0; i < (int)remaining.size(); i++) {\n            for (int j = 0; j < (int)remaining.size(); j++) {\n                if (i != j) {\n                    int ov = overlap(remaining[i], remaining[j]);\n                    if (ov > bestOv) { bestOv = ov; bestI = i; bestJ = j; }\n                }\n            }\n        }\n        \n        string merged = remaining[bestI] + remaining[bestJ].substr(bestOv);\n        \n        vector<string> newRemaining;\n        for (int k = 0; k < (int)remaining.size(); k++) {\n            if (k != bestI && k != bestJ) {\n                if (merged.find(remaining[k]) == string::npos)\n                    newRemaining.push_back(remaining[k]);\n            }\n        }\n        newRemaining.push_back(merged);\n        remaining = newRemaining;\n    }\n    return remaining[0];\n}\n\npair<int, vector<pair<int,int>>> computePath(const string& ss) {\n    int n = ss.length();\n    if (n == 0) return {0, {}};\n    \n    // dp[pos][idx] = min cost from pos to end, starting at charPos[ss[pos]][idx]\n    vector<vector<int>> dp(n);\n    \n    for (int pos = n - 1; pos >= 0; pos--) {\n        char c = ss[pos];\n        int sz = charPos[c].size();\n        dp[pos].resize(sz);\n        \n        if (pos == n - 1) {\n            for (int idx = 0; idx < sz; idx++) dp[pos][idx] = 0;\n        } else {\n            char nc = ss[pos + 1];\n            for (int idx = 0; idx < sz; idx++) {\n                auto [r, col] = charPos[c][idx];\n                int best = INT_MAX;\n                for (int nidx = 0; nidx < (int)charPos[nc].size(); nidx++) {\n                    auto [nr, ncol] = charPos[nc][nidx];\n                    int dist = abs(nr - r) + abs(ncol - col) + 1;\n                    best = min(best, dist + dp[pos + 1][nidx]);\n                }\n                dp[pos][idx] = best;\n            }\n        }\n    }\n    \n    // Find best starting position\n    char c0 = ss[0];\n    int bestCost = INT_MAX, bestIdx = 0;\n    for (int idx = 0; idx < (int)charPos[c0].size(); idx++) {\n        auto [r, col] = charPos[c0][idx];\n        int dist = abs(r - si) + abs(col - sj) + 1;\n        int total = dist + dp[0][idx];\n        if (total < bestCost) { bestCost = total; bestIdx = idx; }\n    }\n    \n    // Reconstruct path\n    vector<pair<int,int>> path(n);\n    int curI = si, curJ = sj;\n    for (int pos = 0; pos < n; pos++) {\n        char c = ss[pos];\n        int best = INT_MAX, bIdx = 0;\n        for (int idx = 0; idx < (int)charPos[c].size(); idx++) {\n            auto [r, col] = charPos[c][idx];\n            int dist = abs(r - curI) + abs(col - curJ) + 1;\n            int total = dist + dp[pos][idx];\n            if (total < best) { best = total; bIdx = idx; }\n        }\n        path[pos] = charPos[c][bIdx];\n        curI = path[pos].first;\n        curJ = path[pos].second;\n    }\n    \n    return {bestCost, path};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> si >> sj;\n    A.resize(N);\n    for (int i = 0; i < N; i++) {\n        cin >> A[i];\n        for (int j = 0; j < N; j++)\n            charPos[A[i][j]].push_back({i, j});\n    }\n    \n    vector<string> t(M);\n    for (int i = 0; i < M; i++) cin >> t[i];\n    \n    string ss = buildSuperstring(t);\n    auto [cost, path] = computePath(ss);\n    \n    for (auto& [i, j] : path)\n        cout << i << \" \" << j << \"\\n\";\n    \n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\ndouble eps;\nvector<vector<pair<int,int>>> shapes;\nmap<pair<int,int>, int> drilled;\nset<pair<int,int>> confirmed_oil, confirmed_no_oil;\nint qcount = 0;\n\nint queryDrill(int i, int j) {\n    pair<int,int> key = make_pair(i, j);\n    if (drilled.count(key)) return drilled[key];\n    cout << \"q 1 \" << i << \" \" << j << \"\\n\" << flush;\n    qcount++;\n    int v; cin >> v;\n    drilled[key] = v;\n    if (v > 0) confirmed_oil.insert(key);\n    else confirmed_no_oil.insert(key);\n    return v;\n}\n\nint queryDivine(const vector<pair<int,int>>& cells) {\n    cout << \"q \" << cells.size();\n    for (auto& c : cells) cout << \" \" << c.first << \" \" << c.second;\n    cout << \"\\n\" << flush;\n    qcount++;\n    int v; cin >> v;\n    return v;\n}\n\nint submit(set<pair<int,int>> oil) {\n    for (auto& c : confirmed_oil) oil.insert(c);\n    cout << \"a \" << oil.size();\n    for (auto& c : oil) cout << \" \" << c.first << \" \" << c.second;\n    cout << \"\\n\" << flush;\n    int r; cin >> r;\n    return r;\n}\n\nvector<vector<set<pair<int,int>>>> placements;\n\nvoid filterPlacements() {\n    for (int m = 0; m < M; m++) {\n        vector<set<pair<int,int>>> valid;\n        for (auto& p : placements[m]) {\n            bool ok = true;\n            for (auto& c : confirmed_no_oil) {\n                if (p.count(c)) { ok = false; break; }\n            }\n            if (ok) valid.push_back(p);\n        }\n        if (!valid.empty()) placements[m] = valid;\n    }\n}\n\nbool allUnique() {\n    for (int m = 0; m < M; m++)\n        if (placements[m].size() > 1) return false;\n    return true;\n}\n\nset<pair<int,int>> getAnswer() {\n    set<pair<int,int>> answer;\n    for (int m = 0; m < M; m++) {\n        if (!placements[m].empty()) {\n            for (auto& c : placements[m][0]) answer.insert(c);\n        }\n    }\n    return answer;\n}\n\nset<pair<int,int>> getPossible() {\n    set<pair<int,int>> possible;\n    for (int m = 0; m < M; m++)\n        for (auto& p : placements[m])\n            for (auto& c : p) possible.insert(c);\n    return possible;\n}\n\npair<int,int> getBestCell(const vector<vector<double>>& prob) {\n    map<pair<int,int>, vector<int>> cellToField;\n    for (int m = 0; m < M; m++) {\n        set<pair<int,int>> inAny;\n        for (auto& p : placements[m])\n            for (auto& c : p) inAny.insert(c);\n        for (auto& c : inAny)\n            cellToField[c].push_back(m);\n    }\n    \n    pair<int,int> best = {-1, -1};\n    double bestScore = -1;\n    \n    for (auto& [cell, fields] : cellToField) {\n        if (drilled.count(cell)) continue;\n        \n        int eliminates = 0;\n        for (int m : fields) {\n            for (auto& p : placements[m]) {\n                if (p.count(cell)) eliminates++;\n            }\n        }\n        \n        // Prefer cells with low probability (likely no oil) that eliminate many\n        double score = eliminates * (1.0 - prob[cell.first][cell.second]);\n        if (score > bestScore) {\n            bestScore = score;\n            best = cell;\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> eps;\n    shapes.resize(M);\n    \n    for (int m = 0; m < M; m++) {\n        int d; cin >> d;\n        shapes[m].resize(d);\n        for (int i = 0; i < d; i++)\n            cin >> shapes[m][i].first >> shapes[m][i].second;\n    }\n    \n    placements.resize(M);\n    for (int m = 0; m < M; m++) {\n        int maxI = 0, maxJ = 0;\n        for (auto& c : shapes[m]) {\n            maxI = max(maxI, c.first);\n            maxJ = max(maxJ, c.second);\n        }\n        for (int di = 0; di + maxI < N; di++) {\n            for (int dj = 0; dj + maxJ < N; dj++) {\n                set<pair<int,int>> cells;\n                for (auto& c : shapes[m])\n                    cells.insert(make_pair(di + c.first, dj + c.second));\n                placements[m].push_back(cells);\n            }\n        }\n    }\n    \n    vector<vector<double>> prob(N, vector<double>(N, 0.5));\n    \n    // Row divination\n    vector<int> rowEst(N);\n    for (int i = 0; i < N; i++) {\n        vector<pair<int,int>> row;\n        for (int j = 0; j < N; j++) row.push_back({i, j});\n        rowEst[i] = queryDivine(row);\n        double est = max(0.0, (rowEst[i] - N * eps) / (1 - 2 * eps));\n        for (int j = 0; j < N; j++)\n            prob[i][j] = min(1.0, est / N);\n    }\n    \n    // Column divination\n    vector<int> colEst(N);\n    for (int j = 0; j < N; j++) {\n        vector<pair<int,int>> col;\n        for (int i = 0; i < N; i++) col.push_back({i, j});\n        colEst[j] = queryDivine(col);\n        double est = max(0.0, (colEst[j] - N * eps) / (1 - 2 * eps));\n        for (int i = 0; i < N; i++)\n            prob[i][j] = (prob[i][j] + min(1.0, est / N)) / 2;\n    }\n    \n    while (qcount < 2*N*N - 5 && !allUnique()) {\n        auto cell = getBestCell(prob);\n        if (cell.first < 0) break;\n        \n        queryDrill(cell.first, cell.second);\n        filterPlacements();\n    }\n    \n    set<pair<int,int>> answer = allUnique() ? getAnswer() : getPossible();\n    for (auto& c : confirmed_no_oil) answer.erase(c);\n    \n    if (!submit(answer)) {\n        answer = getPossible();\n        for (auto& c : confirmed_no_oil) answer.erase(c);\n        if (!submit(answer)) {\n            for (int i = 0; i < N && qcount < 2*N*N - 1; i++)\n                for (int j = 0; j < N && qcount < 2*N*N - 1; j++)\n                    if (!drilled.count({i,j})) queryDrill(i, j);\n            submit(confirmed_oil);\n        }\n    }\n    \n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    for (int d = 0; d < D; d++) {\n        vector<int> h(N);\n        int totalH = 0;\n        \n        // Calculate minimum height needed for each reservation\n        for (int k = 0; k < N; k++) {\n            h[k] = (a[d][k] + W - 1) / W;  // ceil(a[k] / W)\n            if (h[k] == 0) h[k] = 1;\n            totalH += h[k];\n        }\n        \n        if (totalH > W) {\n            int excess = totalH - W;\n            \n            // Calculate slack for each: extra area at current height\n            vector<pair<int, int>> slack(N);\n            for (int k = 0; k < N; k++) {\n                slack[k] = {h[k] * W - a[d][k], k};\n            }\n            sort(slack.begin(), slack.end(), greater<pair<int,int>>());\n            \n            // Reduce heights of those with most slack first\n            for (int i = 0; i < N && excess > 0; i++) {\n                int k = slack[i].second;\n                while (h[k] > 1 && excess > 0) {\n                    int newSlack = (h[k] - 1) * W - a[d][k];\n                    if (newSlack >= 0) {\n                        h[k]--;\n                        excess--;\n                    } else {\n                        break;\n                    }\n                }\n            }\n            \n            // If still excess, reduce even with penalties (larger reservations last)\n            for (int k = 0; k < N && excess > 0; k++) {\n                while (h[k] > 1 && excess > 0) {\n                    h[k]--;\n                    excess--;\n                }\n            }\n        } else if (totalH < W) {\n            int extra = W - totalH;\n            // Distribute extra space, prioritizing larger reservations\n            while (extra > 0) {\n                for (int k = N - 1; k >= 0 && extra > 0; k--) {\n                    h[k]++;\n                    extra--;\n                }\n            }\n        }\n        \n        // Output rectangles\n        int y = 0;\n        for (int k = 0; k < N; k++) {\n            cout << y << \" 0 \" << y + h[k] << \" \" << W << \"\\n\";\n            y += h[k];\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long P = 998244353;\nint N, M, K;\nvector<vector<long long>> a_init;\nvector<array<array<long long, 3>, 3>> stamps;\n\nlong long calcScore(const vector<vector<long long>>& a) {\n    long long s = 0;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            s += a[i][j];\n    return s;\n}\n\nvoid applyOp(vector<vector<long long>>& a, int m, int p, int q) {\n    for (int i = 0; i < 3; i++)\n        for (int j = 0; j < 3; j++)\n            a[p+i][q+j] = (a[p+i][q+j] + stamps[m][i][j]) % P;\n}\n\nlong long calcGain(const vector<vector<long long>>& a, int m, int p, int q) {\n    long long gain = 0;\n    for (int i = 0; i < 3; i++)\n        for (int j = 0; j < 3; j++)\n            gain += (a[p+i][q+j] + stamps[m][i][j]) % P - a[p+i][q+j];\n    return gain;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    cin >> N >> M >> K;\n    a_init.assign(N, vector<long long>(N));\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            cin >> a_init[i][j];\n            a_init[i][j] %= P;\n        }\n    \n    stamps.resize(M);\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    auto start = chrono::steady_clock::now();\n    auto elapsed = [&]() { return chrono::duration<double>(chrono::steady_clock::now() - start).count(); };\n    \n    vector<tuple<int,int,int>> best_ops;\n    long long best_score = calcScore(a_init);\n    \n    mt19937 rng(12345);\n    \n    for (int trial = 0; elapsed() < 1.85; trial++) {\n        vector<tuple<int,int,int>> ops;\n        auto a = a_init;\n        \n        // Randomized greedy\n        for (int op = 0; op < K; op++) {\n            vector<tuple<long long, int, int, int>> cands;\n            for (int m = 0; m < M; m++)\n                for (int p = 0; p <= N-3; p++)\n                    for (int q = 0; q <= N-3; q++) {\n                        long long gain = calcGain(a, m, p, q);\n                        if (gain > 0) cands.push_back({gain, m, p, q});\n                    }\n            if (cands.empty()) break;\n            sort(cands.rbegin(), cands.rend());\n            int pick = (trial == 0) ? 0 : rng() % min((int)cands.size(), 1 + trial);\n            auto [g, m, p, q] = cands[pick];\n            applyOp(a, m, p, q);\n            ops.push_back({m, p, q});\n        }\n        \n        // Local optimization passes\n        for (int iter = 0; iter < 5 && elapsed() < 1.85; iter++) {\n            bool improved = false;\n            \n            // Try replacing each operation\n            for (int idx = 0; idx < (int)ops.size() && elapsed() < 1.85; idx++) {\n                auto orig = ops[idx];\n                auto a2 = a_init;\n                for (int k = 0; k < (int)ops.size(); k++)\n                    if (k != idx) {\n                        auto [m,p,q] = ops[k];\n                        applyOp(a2, m, p, q);\n                    }\n                \n                long long bestGain = 0;\n                int bm=-1, bp=-1, bq=-1;\n                for (int m = 0; m < M; m++)\n                    for (int p = 0; p <= N-3; p++)\n                        for (int q = 0; q <= N-3; q++) {\n                            long long gain = calcGain(a2, m, p, q);\n                            if (gain > bestGain) { bestGain = gain; bm=m; bp=p; bq=q; }\n                        }\n                \n                if (bm != -1) {\n                    ops[idx] = {bm, bp, bq};\n                    a = a2;\n                    applyOp(a, bm, bp, bq);\n                    if (make_tuple(bm,bp,bq) != orig) improved = true;\n                }\n            }\n            \n            // Try removing operations that hurt\n            for (int idx = (int)ops.size()-1; idx >= 0 && elapsed() < 1.85; idx--) {\n                auto a2 = a_init;\n                for (int k = 0; k < (int)ops.size(); k++)\n                    if (k != idx) {\n                        auto [m,p,q] = ops[k];\n                        applyOp(a2, m, p, q);\n                    }\n                if (calcScore(a2) >= calcScore(a)) {\n                    ops.erase(ops.begin() + idx);\n                    a = a2;\n                    improved = true;\n                }\n            }\n            \n            // Try adding more operations\n            while (ops.size() < (size_t)K && elapsed() < 1.85) {\n                long long bestGain = 0;\n                int bm=-1, bp=-1, bq=-1;\n                for (int m = 0; m < M; m++)\n                    for (int p = 0; p <= N-3; p++)\n                        for (int q = 0; q <= N-3; q++) {\n                            long long gain = calcGain(a, m, p, q);\n                            if (gain > bestGain) { bestGain = gain; bm=m; bp=p; bq=q; }\n                        }\n                if (bm == -1) break;\n                applyOp(a, bm, bp, bq);\n                ops.push_back({bm, bp, bq});\n                improved = true;\n            }\n            \n            if (!improved) break;\n        }\n        \n        long long score = calcScore(a);\n        if (score > best_score) {\n            best_score = score;\n            best_ops = ops;\n        }\n    }\n    \n    cout << best_ops.size() << \"\\n\";\n    for (auto& [m,p,q] : best_ops) cout << m << \" \" << p << \" \" << q << \"\\n\";\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 5;\nint A[N][N];\nint grid[N][N];\nint cr[N], cc[N], hold[N];\nint next_in[N];\nstring ans[N];\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n; cin >> n;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            cin >> A[i][j];\n    \n    memset(grid, -1, sizeof(grid));\n    memset(hold, -1, sizeof(hold));\n    memset(next_in, 0, sizeof(next_in));\n    for (int i = 0; i < N; i++) { cr[i] = i; cc[i] = 0; }\n    \n    for (int t = 0; t < 5000; t++) {\n        // Step 1: Bring in 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 c = 0; c < N; c++)\n                    if (cr[c] == i && cc[c] == 0 && hold[c] != -1)\n                        blocked = true;\n                if (!blocked) grid[i][0] = A[i][next_in[i]++];\n            }\n        }\n        \n        // Decide moves\n        char moves[N];\n        for (int c = 0; c < N; c++) moves[c] = '.';\n        \n        for (int c = 0; c < N; c++) {\n            int r = cr[c], col = cc[c];\n            \n            if (hold[c] == -1) {\n                if (grid[r][col] != -1) {\n                    moves[c] = 'P';\n                } else if (col > 0) {\n                    moves[c] = 'L';\n                }\n            } else {\n                int target_row = hold[c] / N;\n                if (col < N-1) {\n                    bool can_move = (c == 0 || grid[r][col+1] == -1);\n                    if (can_move) moves[c] = 'R';\n                } else {\n                    moves[c] = 'Q';\n                }\n            }\n        }\n        \n        // Step 2: Execute moves\n        for (int c = 0; c < N; c++) {\n            char m = moves[c];\n            if (m == 'P') {\n                hold[c] = grid[cr[c]][cc[c]];\n                grid[cr[c]][cc[c]] = -1;\n            } else if (m == 'Q') {\n                grid[cr[c]][cc[c]] = hold[c];\n                hold[c] = -1;\n            } else if (m == 'R') cc[c]++;\n            else if (m == 'L') cc[c]--;\n            else if (m == 'U') cr[c]--;\n            else if (m == 'D') cr[c]++;\n        }\n        \n        // Step 3: Dispatch\n        for (int i = 0; i < N; i++) grid[i][N-1] = -1;\n        \n        for (int c = 0; c < N; c++) ans[c] += moves[c];\n        \n        // Check if done\n        bool done = true;\n        for (int i = 0; i < N; i++) if (next_in[i] < N) done = false;\n        for (int c = 0; c < N; c++) if (hold[c] != -1) done = false;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] != -1) done = false;\n        if (done) break;\n    }\n    \n    // Trim trailing dots\n    size_t maxlen = 0;\n    for (int i = 0; i < N; i++) maxlen = max(maxlen, ans[i].size());\n    \n    while (maxlen > 1) {\n        bool all_dot = true;\n        for (int i = 0; i < N; i++) {\n            if (ans[i].size() >= maxlen && ans[i][maxlen-1] != '.') all_dot = false;\n        }\n        if (!all_dot) break;\n        maxlen--;\n        for (int i = 0; i < N; i++)\n            if (ans[i].size() > maxlen) ans[i].resize(maxlen);\n    }\n    \n    for (int i = 0; i < N; i++) cout << ans[i] << \"\\n\";\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<vector<int>> h;\nvector<string> ops;\nint cx = 0, cy = 0;\nint load = 0;\n\nvoid do_load(int d) {\n    if (d <= 0) return;\n    ops.push_back(\"+\" + to_string(d));\n    load += d;\n    h[cx][cy] -= d;\n}\n\nvoid do_unload(int d) {\n    if (d <= 0) return;\n    ops.push_back(\"-\" + to_string(d));\n    load -= d;\n    h[cx][cy] += d;\n}\n\nvoid move_one(char dir) {\n    ops.push_back(string(1, dir));\n    if (dir == 'U') cx--;\n    else if (dir == 'D') cx++;\n    else if (dir == 'L') cy--;\n    else if (dir == 'R') cy++;\n}\n\nvoid process_cell() {\n    // Opportunistically load if positive\n    if (h[cx][cy] > 0) {\n        do_load(h[cx][cy]);\n    }\n    // Opportunistically unload if negative and we have load\n    if (h[cx][cy] < 0 && load > 0) {\n        do_unload(min(load, -h[cx][cy]));\n    }\n}\n\nvoid move_to(int tx, int ty, bool opportunistic = false) {\n    while (cx < tx) {\n        move_one('D');\n        if (opportunistic) process_cell();\n    }\n    while (cx > tx) {\n        move_one('U');\n        if (opportunistic) process_cell();\n    }\n    while (cy < ty) {\n        move_one('R');\n        if (opportunistic) process_cell();\n    }\n    while (cy > ty) {\n        move_one('L');\n        if (opportunistic) process_cell();\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    h.resize(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    while (true) {\n        if (load == 0) {\n            // Find nearest source\n            int si = -1, sj = -1, best_dist = INT_MAX;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h[i][j] > 0) {\n                        int dist = abs(i - cx) + abs(j - cy);\n                        if (dist < best_dist) {\n                            best_dist = dist;\n                            si = i; sj = j;\n                        }\n                    }\n                }\n            }\n            \n            if (si == -1) break;\n            \n            move_to(si, sj, true);\n            if (h[cx][cy] > 0) do_load(h[cx][cy]);\n        } else {\n            // Find nearest sink\n            int ti = -1, tj = -1, best_dist = INT_MAX;\n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h[i][j] < 0) {\n                        int dist = abs(i - cx) + abs(j - cy);\n                        if (dist < best_dist) {\n                            best_dist = dist;\n                            ti = i; tj = j;\n                        }\n                    }\n                }\n            }\n            \n            if (ti == -1) break;\n            \n            move_to(ti, tj, true);\n            if (h[cx][cy] < 0 && load > 0) {\n                do_unload(min(load, -h[cx][cy]));\n            }\n        }\n    }\n    \n    for (const auto& op : ops) {\n        cout << op << \"\\n\";\n    }\n    \n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \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, 0));\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    for (int t = 0; t < T; t++) {\n        // Find max value for each criterion\n        vector<int> maxVal(M, -1);\n        for (int l = 0; l < M; l++) {\n            for (int i = 0; i < seed_count; i++) {\n                maxVal[l] = max(maxVal[l], X[i][l]);\n            }\n        }\n        \n        // Calculate score for each seed (bonus for having max values)\n        vector<pair<double, int>> seed_scores(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            double score = 0;\n            for (int l = 0; l < M; l++) {\n                if (X[i][l] == maxVal[l]) {\n                    score += 1000;\n                }\n                score += X[i][l];\n            }\n            seed_scores[i] = {score, i};\n        }\n        \n        sort(seed_scores.begin(), seed_scores.end(), greater<pair<double, int>>());\n        \n        vector<int> selected(N * N);\n        for (int i = 0; i < N * N; i++) {\n            selected[i] = seed_scores[i].second;\n        }\n        \n        auto getValue = [&](int idx) {\n            int total = 0;\n            for (int l = 0; l < M; l++) total += X[idx][l];\n            return total;\n        };\n        \n        sort(selected.begin(), selected.end(), [&](int a, int b) {\n            return getValue(a) > getValue(b);\n        });\n        \n        vector<pair<int, int>> pos_order;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                pos_order.push_back({i, j});\n            }\n        }\n        \n        double cx = (N - 1) / 2.0;\n        double cy = (N - 1) / 2.0;\n        sort(pos_order.begin(), pos_order.end(), [&](auto& a, auto& b) {\n            double da = abs(a.first - cx) + abs(a.second - cy);\n            double db = abs(b.first - cx) + abs(b.second - cy);\n            if (da != db) return da < db;\n            if (a.first != b.first) return a.first < b.first;\n            return a.second < b.second;\n        });\n        \n        vector<vector<int>> A(N, vector<int>(N, -1));\n        for (int i = 0; i < N * N; i++) {\n            A[pos_order[i].first][pos_order[i].second] = selected[i];\n        }\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << A[i][j];\n                if (j < N - 1) cout << \" \";\n                else cout << \"\\n\";\n            }\n        }\n        cout.flush();\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\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, V;\nconst int DX[] = {0, 1, 0, -1};\nconst int DY[] = {1, 0, -1, 0};\n\nint rx, ry;\nvector<int> dirs;\nvector<bool> holding;\nint numF;\n\npair<int,int> fingertip(int i) { return {rx + DX[dirs[i]], ry + DY[dirs[i]]}; }\nbool valid(int x, int y) { return x >= 0 && x < N && y >= 0 && y < N; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> V;\n    vector<string> grid(N), target(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    for (int i = 0; i < N; i++) cin >> target[i];\n    \n    numF = V - 1;\n    cout << numF + 1 << \"\\n\";\n    for (int i = 1; i <= numF; i++) cout << \"0 1\\n\";\n    cout << \"0 0\\n\";\n    \n    rx = ry = 0;\n    dirs.assign(numF, 0);\n    holding.assign(numF, false);\n    \n    set<pair<int,int>> pickup, dropS;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] == '1' && target[i][j] == '0') pickup.insert({i, j});\n            if (target[i][j] == '1' && grid[i][j] == '0') dropS.insert({i, j});\n        }\n    \n    vector<string> ops;\n    \n    auto makeOp = [&](char mv, vector<char>& rot, vector<char>& act) {\n        string s; s += mv;\n        for (int i = 0; i < numF; i++) s += rot[i];\n        s += '.';\n        for (int i = 0; i < numF; i++) s += act[i];\n        ops.push_back(s);\n    };\n    \n    while (ops.size() < 95000 && (!pickup.empty() || !dropS.empty() || \n           any_of(holding.begin(), holding.end(), [](bool h){return h;}))) {\n        \n        vector<char> rot(numF, '.'), act(numF, '.');\n        bool acted = false;\n        \n        // Try pick/drop at current positions\n        for (int i = 0; i < numF; i++) {\n            auto [fx, fy] = fingertip(i);\n            if (!valid(fx, fy)) continue;\n            if (!holding[i] && pickup.count({fx, fy})) {\n                act[i] = 'P'; pickup.erase({fx, fy}); holding[i] = true; acted = true;\n            } else if (holding[i] && dropS.count({fx, fy})) {\n                act[i] = 'P'; dropS.erase({fx, fy}); holding[i] = false; acted = true;\n            }\n        }\n        if (acted) { makeOp('.', rot, act); continue; }\n        \n        // Find best target for each fingertip (cached)\n        int bestDist = INT_MAX, bestF = -1, bestDir = -1;\n        pair<int,int> bestTarget;\n        \n        for (int i = 0; i < numF; i++) {\n            auto& targets = holding[i] ? dropS : pickup;\n            if (targets.empty()) continue;\n            \n            auto [fx, fy] = fingertip(i);\n            for (auto& t : targets) {\n                int dist = abs(t.first - fx) + abs(t.second - fy);\n                if (dist < bestDist) {\n                    bestDist = dist;\n                    bestF = i;\n                    bestTarget = t;\n                }\n            }\n        }\n        \n        if (bestF == -1) break;\n        \n        // Find best direction to reach target\n        int tx = bestTarget.first, ty = bestTarget.second;\n        bestDist = INT_MAX;\n        bestDir = dirs[bestF];\n        \n        for (int d = 0; d < 4; d++) {\n            int nrx = tx - DX[d], nry = ty - DY[d];\n            if (!valid(nrx, nry)) continue;\n            int diff = (d - dirs[bestF] + 4) % 4;\n            int rotCost = min(diff, 4 - diff);\n            int dist = abs(nrx - rx) + abs(nry - ry) + rotCost;\n            if (dist < bestDist) {\n                bestDist = dist;\n                bestDir = d;\n            }\n        }\n        \n        int trx = tx - DX[bestDir], tr_y = ty - DY[bestDir];\n        char mv = '.';\n        \n        // Move towards target root position\n        if (rx < trx && valid(rx + 1, ry)) { mv = 'D'; rx++; }\n        else if (rx > trx && valid(rx - 1, ry)) { mv = 'U'; rx--; }\n        else if (ry < tr_y && valid(rx, ry + 1)) { mv = 'R'; ry++; }\n        else if (ry > tr_y && valid(rx, ry - 1)) { mv = 'L'; ry--; }\n        \n        // Rotate fingertip towards target direction\n        if (dirs[bestF] != bestDir) {\n            int diff = (bestDir - dirs[bestF] + 4) % 4;\n            if (diff == 1) { rot[bestF] = 'R'; dirs[bestF] = (dirs[bestF] + 1) % 4; }\n            else if (diff == 3) { rot[bestF] = 'L'; dirs[bestF] = (dirs[bestF] + 3) % 4; }\n            else { rot[bestF] = 'R'; dirs[bestF] = (dirs[bestF] + 1) % 4; }\n        }\n        \n        if (mv == '.' && rot[bestF] == '.') {\n            // Stuck - try any move\n            if (valid(rx + 1, ry)) { mv = 'D'; rx++; }\n            else if (valid(rx - 1, ry)) { mv = 'U'; rx--; }\n            else if (valid(rx, ry + 1)) { mv = 'R'; ry++; }\n            else if (valid(rx, ry - 1)) { mv = 'L'; ry--; }\n            else {\n                rot[bestF] = 'R';\n                dirs[bestF] = (dirs[bestF] + 1) % 4;\n            }\n        }\n        \n        makeOp(mv, rot, act);\n    }\n    \n    for (auto& op : ops) cout << op << \"\\n\";\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::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    for (int i = 0; i < N; i++)\n        cin >> mackerel[i].first >> mackerel[i].second;\n    for (int i = 0; i < N; i++)\n        cin >> sardine[i].first >> sardine[i].second;\n    \n    vector<int> xs, ys;\n    for (auto& p : mackerel) { xs.push_back(p.first); ys.push_back(p.second); }\n    for (auto& p : sardine) { xs.push_back(p.first); ys.push_back(p.second); }\n    \n    sort(xs.begin(), xs.end()); xs.erase(unique(xs.begin(), xs.end()), xs.end());\n    sort(ys.begin(), ys.end()); ys.erase(unique(ys.begin(), ys.end()), ys.end());\n    \n    int nx = xs.size(), ny = ys.size();\n    map<int, int> x_idx, y_idx;\n    for (int i = 0; i < nx; i++) x_idx[xs[i]] = i;\n    for (int i = 0; i < ny; i++) y_idx[ys[i]] = i;\n    \n    vector<vector<int>> grid(ny + 1, vector<int>(nx + 1, 0));\n    for (auto& p : mackerel) grid[y_idx[p.second] + 1][x_idx[p.first] + 1]++;\n    for (auto& p : sardine) grid[y_idx[p.second] + 1][x_idx[p.first] + 1]--;\n    \n    for (int i = 1; i <= ny; i++)\n        for (int j = 1; j <= nx; j++)\n            grid[i][j] += grid[i-1][j] + grid[i][j-1] - grid[i-1][j-1];\n    \n    auto query = [&](int y1, int x1, int y2, int x2) -> int {\n        return grid[y2+1][x2+1] - grid[y1][x2+1] - grid[y2+1][x1] + grid[y1][x1];\n    };\n    \n    int best_score = 0;\n    int bx1 = 0, by1 = 0, bx2 = 0, by2 = 0;\n    \n    mt19937 rng(12345);\n    \n    vector<tuple<int,int,int,int,int>> candidates;\n    \n    // Random sampling phase\n    for (int iter = 0; iter < 300000; iter++) {\n        int i1 = rng() % N, i2 = rng() % N;\n        int x1i = x_idx[mackerel[i1].first];\n        int y1i = y_idx[mackerel[i1].second];\n        int x2i = x_idx[mackerel[i2].first];\n        int y2i = y_idx[mackerel[i2].second];\n        \n        if (x1i > x2i) swap(x1i, x2i);\n        if (y1i > y2i) swap(y1i, y2i);\n        \n        int score = query(y1i, x1i, y2i, x2i);\n        if (score > best_score - 50) {\n            candidates.push_back({score, x1i, y1i, x2i, y2i});\n        }\n        if (score > best_score) {\n            best_score = score;\n            bx1 = x1i; by1 = y1i; bx2 = x2i; by2 = y2i;\n        }\n    }\n    \n    // Sort candidates and keep top ones\n    sort(candidates.rbegin(), candidates.rend());\n    if (candidates.size() > 50) candidates.resize(50);\n    \n    // Optimize each candidate\n    for (auto& [sc, cx1, cy1, cx2, cy2] : candidates) {\n        // Optimize each edge independently\n        for (int round = 0; round < 3; round++) {\n            // Optimize x1\n            for (int x = 0; x <= cx2; x++) {\n                int score = query(cy1, x, cy2, cx2);\n                if (score > query(cy1, cx1, cy2, cx2)) cx1 = x;\n            }\n            // Optimize x2\n            for (int x = cx1; x < nx; x++) {\n                int score = query(cy1, cx1, cy2, x);\n                if (score > query(cy1, cx1, cy2, cx2)) cx2 = x;\n            }\n            // Optimize y1\n            for (int y = 0; y <= cy2; y++) {\n                int score = query(y, cx1, cy2, cx2);\n                if (score > query(cy1, cx1, cy2, cx2)) cy1 = y;\n            }\n            // Optimize y2\n            for (int y = cy1; y < ny; y++) {\n                int score = query(cy1, cx1, y, cx2);\n                if (score > query(cy1, cx1, cy2, cx2)) cy2 = y;\n            }\n        }\n        \n        int final_score = query(cy1, cx1, cy2, cx2);\n        if (final_score > best_score) {\n            best_score = final_score;\n            bx1 = cx1; by1 = cy1; bx2 = cx2; by2 = cy2;\n        }\n    }\n    \n    int outx1 = xs[bx1], outy1 = ys[by1];\n    int outx2 = xs[bx2], outy2 = ys[by2];\n    \n    if (best_score == 0) {\n        outx1 = 0; outy1 = 0; outx2 = 1; outy2 = 1;\n    }\n    \n    cout << 4 << \"\\n\";\n    cout << outx1 << \" \" << outy1 << \"\\n\";\n    cout << outx2 << \" \" << outy1 << \"\\n\";\n    cout << outx2 << \" \" << outy2 << \"\\n\";\n    cout << outx1 << \" \" << outy2 << \"\\n\";\n    \n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nlong long sigma;\nvector<long long> w, h;\n\nstruct PlacedRect { long long x1, y1, x2, y2; int id; };\n\ntuple<long long, long long> simulate(const vector<tuple<int,int,char,int>>& ops) {\n    vector<PlacedRect> placed;\n    long long W = 0, H = 0;\n    for (auto& [p, r, d, b] : ops) {\n        long long rw = w[p], rh = h[p];\n        if (r) swap(rw, rh);\n        long long x = 0, y = 0;\n        if (d == 'U') {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n            for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n        } else {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n            for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n        }\n        placed.push_back({x, y, x + rw, y + rh, p});\n        W = max(W, x + rw); H = max(H, y + rh);\n    }\n    return {W, H};\n}\n\nmt19937 rng(42);\n\nvector<tuple<int,int,char,int>> genGreedy(double wBias = 1.0) {\n    vector<tuple<int,int,char,int>> ops;\n    vector<PlacedRect> placed;\n    long long curW = 0, curH = 0;\n    for (int i = 0; i < N; i++) {\n        long long best = LLONG_MAX; tuple<int,char,int> bc = {0,'U',-1};\n        vector<int> bases = {-1};\n        for (int j = max(0, i-10); j < i; j++) bases.push_back(j);\n        \n        for (int r = 0; r < 2; r++) for (char d : {'U','L'}) for (int b : bases) {\n            long long rw = w[i], rh = h[i]; if (r) swap(rw, rh);\n            long long x = 0, y = 0;\n            if (d == 'U') {\n                if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n                for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n            } else {\n                if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n                for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n            }\n            double sc = wBias * max(curW, x+rw) + max(curH, y+rh);\n            if (sc < best) { best = sc; bc = {r, d, b}; }\n        }\n        auto [r, d, b] = bc;\n        long long rw = w[i], rh = h[i]; if (r) swap(rw, rh);\n        long long x = 0, y = 0;\n        if (d == 'U') {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n            for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n        } else {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n            for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n        }\n        placed.push_back({x, y, x+rw, y+rh, i}); curW = max(curW, x+rw); curH = max(curH, y+rh);\n        ops.push_back({i, r, d, b});\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> genShelf(double widthFactor) {\n    long long totalArea = 0;\n    for (int i = 0; i < N; i++) totalArea += w[i] * h[i];\n    long long targetW = (long long)(sqrt(totalArea) * widthFactor);\n    \n    vector<tuple<int,int,char,int>> ops;\n    long long curX = 0, shelfH = 0;\n    int lastInShelf = -1;\n    \n    for (int i = 0; i < N; i++) {\n        int r = (h[i] > w[i]) ? 1 : 0;\n        long long rw = w[i], rh = h[i]; if (r) swap(rw, rh);\n        \n        if (curX + rw > targetW && lastInShelf >= 0) {\n            ops.push_back({i, r, 'L', lastInShelf});\n            curX = rw; shelfH = rh; lastInShelf = i;\n        } else {\n            if (lastInShelf < 0) {\n                ops.push_back({i, r, 'U', -1});\n            } else {\n                ops.push_back({i, r, 'U', lastInShelf});\n            }\n            curX += rw; shelfH = max(shelfH, rh); lastInShelf = i;\n        }\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> genStrip(char dir, int rotMode) {\n    vector<tuple<int,int,char,int>> ops;\n    for (int i = 0; i < N; i++) {\n        int r = (rotMode == 0) ? 0 : (rotMode == 1) ? 1 : \n                ((dir == 'U') ? (w[i] < h[i] ? 1 : 0) : (h[i] < w[i] ? 1 : 0));\n        ops.push_back({i, r, dir, -1});\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> mutate(vector<tuple<int,int,char,int>> ops, int intensity) {\n    int numMut = 1 + rng() % (intensity + 1);\n    for (int m = 0; m < numMut; m++) {\n        int i = rng() % N;\n        auto& [p, r, d, b] = ops[i];\n        int choice = rng() % 3;\n        if (choice == 0) r = 1 - r;\n        else if (choice == 1) d = (d == 'U') ? 'L' : 'U';\n        else if (i > 0) b = (int)(rng() % (i + 1)) - 1;\n    }\n    return ops;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> T >> sigma;\n    w.resize(N); h.resize(N);\n    for (int i = 0; i < N; i++) cin >> w[i] >> h[i];\n    \n    vector<pair<long long, vector<tuple<int,int,char,int>>>> candidates;\n    \n    auto addCandidate = [&](vector<tuple<int,int,char,int>> ops) {\n        auto [sw, sh] = simulate(ops);\n        candidates.push_back({sw + sh, ops});\n    };\n    \n    // Generate diverse initial candidates\n    for (double bias : {0.8, 1.0, 1.2}) addCandidate(genGreedy(bias));\n    for (double wf : {0.8, 1.0, 1.2, 1.5, 2.0}) addCandidate(genShelf(wf));\n    for (char d : {'U', 'L'}) for (int rm = 0; rm < 3; rm++) addCandidate(genStrip(d, rm));\n    \n    sort(candidates.begin(), candidates.end());\n    auto bestOps = candidates[0].second;\n    long long bestSim = candidates[0].first;\n    \n    // Hill climbing\n    auto startTime = chrono::steady_clock::now();\n    for (int iter = 0; (int)candidates.size() < T * 3; iter++) {\n        auto now = chrono::steady_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - startTime).count() > 2500) break;\n        \n        int srcIdx = (rng() % 100 < 80) ? 0 : rng() % min((int)candidates.size(), 5);\n        auto ops = mutate(candidates[srcIdx].second, 1 + iter / 2000);\n        auto [sw, sh] = simulate(ops);\n        \n        if (sw + sh <= bestSim * 1.05) {\n            candidates.push_back({sw + sh, ops});\n            if (sw + sh < bestSim) { bestSim = sw + sh; bestOps = ops; }\n        }\n    }\n    \n    sort(candidates.begin(), candidates.end());\n    candidates.erase(unique(candidates.begin(), candidates.end()), candidates.end());\n    if ((int)candidates.size() > T) candidates.resize(T);\n    \n    while ((int)candidates.size() < T) {\n        auto ops = mutate(bestOps, 2);\n        auto [sw, sh] = simulate(ops);\n        candidates.push_back({sw + sh, ops});\n    }\n    \n    sort(candidates.begin(), candidates.end());\n    \n    long long bestObserved = LLONG_MAX;\n    int bestIdx = 0;\n    \n    for (int t = 0; t < T; t++) {\n        auto& ops = candidates[min(t, (int)candidates.size()-1)].second;\n        \n        cout << ops.size() << \"\\n\";\n        for (auto& [p, r, d, b] : ops) cout << p << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        cout.flush();\n        \n        long long W, H; cin >> W >> H;\n        if (W + H < bestObserved) { bestObserved = W + H; bestIdx = t; }\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<int> parent_arr;\nvector<int> depth_arr;\n\nlong long compute_score() {\n    long long score = 0;\n    for (int i = 0; i < N; i++) {\n        score += (long long)(depth_arr[i] + 1) * A[i];\n    }\n    return score;\n}\n\nvoid rebuild_depths() {\n    vector<vector<int>> children(N);\n    for (int i = 0; i < N; i++) {\n        if (parent_arr[i] != -1) {\n            children[parent_arr[i]].push_back(i);\n        }\n    }\n    \n    fill(depth_arr.begin(), depth_arr.end(), -1);\n    queue<int> q;\n    for (int i = 0; i < N; i++) {\n        if (parent_arr[i] == -1) {\n            depth_arr[i] = 0;\n            q.push(i);\n        }\n    }\n    while (!q.empty()) {\n        int u = q.front(); q.pop();\n        for (int c : children[u]) {\n            depth_arr[c] = depth_arr[u] + 1;\n            q.push(c);\n        }\n    }\n}\n\nvoid dfs(int u) {\n    vector<pair<int, int>> neighbors;\n    for (int v : adj[u]) {\n        if (depth_arr[v] == -1) {\n            neighbors.push_back({-A[v], v});\n        }\n    }\n    sort(neighbors.begin(), neighbors.end());\n    \n    for (auto& [neg_beauty, v] : neighbors) {\n        if (depth_arr[v] == -1 && depth_arr[u] < H) {\n            parent_arr[v] = u;\n            depth_arr[v] = depth_arr[u] + 1;\n            dfs(v);\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    auto start_time = chrono::steady_clock::now();\n    auto elapsed = [&]() {\n        return chrono::duration_cast<chrono::milliseconds>(\n            chrono::steady_clock::now() - start_time).count();\n    };\n    \n    cin >> N >> M >> H;\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    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    parent_arr.resize(N, -1);\n    depth_arr.resize(N, -1);\n    \n    vector<int> best_parent(N, -1);\n    long long best_score = 0;\n    \n    mt19937 rng(12345);\n    \n    // Multiple restarts with different strategies\n    for (int trial = 0; trial < 200 && elapsed() < 800; trial++) {\n        fill(parent_arr.begin(), parent_arr.end(), -1);\n        fill(depth_arr.begin(), depth_arr.end(), -1);\n        \n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        \n        if (trial == 0) {\n            // Sort by beauty ascending\n            sort(order.begin(), order.end(), [&](int a, int b) {\n                return A[a] < A[b];\n            });\n        } else if (trial == 1) {\n            // Sort by degree ascending (low degree = likely leaf = good root)\n            sort(order.begin(), order.end(), [&](int a, int b) {\n                return adj[a].size() < adj[b].size();\n            });\n        } else {\n            // Random with bias toward low beauty\n            vector<int> keys(N);\n            for (int i = 0; i < N; i++) {\n                keys[i] = A[i] + (rng() % 60);\n            }\n            sort(order.begin(), order.end(), [&](int a, int b) {\n                return keys[a] < keys[b];\n            });\n        }\n        \n        for (int start : order) {\n            if (depth_arr[start] != -1) continue;\n            depth_arr[start] = 0;\n            parent_arr[start] = -1;\n            dfs(start);\n        }\n        \n        long long score = compute_score();\n        if (score > best_score) {\n            best_score = score;\n            best_parent = parent_arr;\n        }\n    }\n    \n    parent_arr = best_parent;\n    rebuild_depths();\n    \n    // Local search\n    function<int(int, const vector<vector<int>>&)> calc_height = [&](int v, const vector<vector<int>>& ch) -> int {\n        int h = 0;\n        for (int c : ch[v]) {\n            h = max(h, 1 + calc_height(c, ch));\n        }\n        return h;\n    };\n    \n    for (int iter = 0; iter < 100 && elapsed() < 1900; iter++) {\n        bool improved = false;\n        \n        vector<vector<int>> children(N);\n        for (int i = 0; i < N; i++) {\n            if (parent_arr[i] != -1) {\n                children[parent_arr[i]].push_back(i);\n            }\n        }\n        \n        vector<int> sub_h(N, 0);\n        for (int i = 0; i < N; i++) {\n            sub_h[i] = calc_height(i, children);\n        }\n        \n        vector<int> vorder(N);\n        iota(vorder.begin(), vorder.end(), 0);\n        sort(vorder.begin(), vorder.end(), [&](int a, int b) {\n            return A[a] > A[b];\n        });\n        \n        for (int v : vorder) {\n            if (elapsed() > 1900) break;\n            \n            int cur_depth = depth_arr[v];\n            int best_new_parent = -1;\n            int best_new_depth = cur_depth;\n            \n            for (int u : adj[v]) {\n                if (u == parent_arr[v]) continue;\n                \n                // Check if u is in subtree of v\n                bool in_subtree = false;\n                int p = u;\n                while (p != -1) {\n                    if (p == v) { in_subtree = true; break; }\n                    p = parent_arr[p];\n                }\n                if (in_subtree) continue;\n                \n                int new_depth = depth_arr[u] + 1;\n                if (new_depth > best_new_depth && new_depth + sub_h[v] <= H) {\n                    best_new_depth = new_depth;\n                    best_new_parent = u;\n                }\n            }\n            \n            if (best_new_parent != -1) {\n                parent_arr[v] = best_new_parent;\n                rebuild_depths();\n                \n                // Rebuild children and heights\n                for (int i = 0; i < N; i++) children[i].clear();\n                for (int i = 0; i < N; i++) {\n                    if (parent_arr[i] != -1) {\n                        children[parent_arr[i]].push_back(i);\n                    }\n                }\n                for (int i = 0; i < N; i++) {\n                    sub_h[i] = calc_height(i, children);\n                }\n                improved = true;\n            }\n        }\n        \n        if (!improved) break;\n    }\n    \n    // Final output\n    for (int i = 0; i < N; i++) {\n        cout << parent_arr[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<pair<int,int>> onis;\nvector<vector<int>> valid_dirs;\nvector<array<int, 4>> dists;\n\ninline int get_key(int k, int dir) {\n    return dir * N + ((dir <= 1) ? onis[k].second : onis[k].first);\n}\n\nint compute_cost(const vector<int>& assignment) {\n    int batch_max[80] = {};\n    for (int k = 0; k < M; k++) {\n        int key = get_key(k, assignment[k]);\n        batch_max[key] = max(batch_max[key], dists[k][assignment[k]]);\n    }\n    int total = 0;\n    for (int i = 0; i < 80; i++) total += 2 * batch_max[i];\n    return total;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    vector<string> board(N);\n    for (int i = 0; i < N; i++) cin >> board[i];\n    \n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            if (board[i][j] == 'x') onis.push_back({i, j});\n    \n    M = onis.size();\n    valid_dirs.resize(M);\n    dists.resize(M);\n    \n    for (int k = 0; k < M; k++) {\n        int r = onis[k].first, c = onis[k].second;\n        bool ok = true;\n        for (int i = 0; i < r && ok; i++) if (board[i][c] == 'o') ok = false;\n        if (ok) { valid_dirs[k].push_back(0); dists[k][0] = r + 1; }\n        ok = true;\n        for (int i = r+1; i < N && ok; i++) if (board[i][c] == 'o') ok = false;\n        if (ok) { valid_dirs[k].push_back(1); dists[k][1] = N - r; }\n        ok = true;\n        for (int j = 0; j < c && ok; j++) if (board[r][j] == 'o') ok = false;\n        if (ok) { valid_dirs[k].push_back(2); dists[k][2] = c + 1; }\n        ok = true;\n        for (int j = c+1; j < N && ok; j++) if (board[r][j] == 'o') ok = false;\n        if (ok) { valid_dirs[k].push_back(3); dists[k][3] = N - c; }\n    }\n    \n    mt19937 rng(42);\n    vector<int> best_assignment(M);\n    int best_cost = INT_MAX;\n    \n    auto local_search = [&](vector<int>& asgn) {\n        int cur_cost = compute_cost(asgn);\n        for (int iter = 0; iter < 100; iter++) {\n            bool improved = false;\n            for (int k = 0; k < M; k++) {\n                int orig = asgn[k];\n                for (int dir : valid_dirs[k]) {\n                    if (dir == orig) continue;\n                    asgn[k] = dir;\n                    int nc = compute_cost(asgn);\n                    if (nc < cur_cost) { cur_cost = nc; improved = true; }\n                    else asgn[k] = orig;\n                }\n            }\n            if (!improved) break;\n        }\n        return cur_cost;\n    };\n    \n    for (int trial = 0; trial < 2000; trial++) {\n        vector<int> asgn(M);\n        \n        if (trial == 0) {\n            for (int k = 0; k < M; k++) {\n                int bd = valid_dirs[k][0];\n                for (int d : valid_dirs[k]) if (dists[k][d] < dists[k][bd]) bd = d;\n                asgn[k] = bd;\n            }\n        } else if (trial <= 4) {\n            int pref = trial - 1;\n            for (int k = 0; k < M; k++) {\n                asgn[k] = valid_dirs[k][0];\n                for (int d : valid_dirs[k]) if (d == pref) { asgn[k] = d; break; }\n            }\n        } else if (trial <= 8) {\n            int pref = trial - 5;\n            for (int k = 0; k < M; k++) {\n                asgn[k] = valid_dirs[k][0];\n                int bd = dists[k][asgn[k]];\n                for (int d : valid_dirs[k]) {\n                    if (d == pref && dists[k][d] <= bd + 3) { asgn[k] = d; break; }\n                }\n            }\n        } else {\n            for (int k = 0; k < M; k++)\n                asgn[k] = valid_dirs[k][rng() % valid_dirs[k].size()];\n        }\n        \n        int cost = local_search(asgn);\n        if (cost < best_cost) { best_cost = cost; best_assignment = asgn; }\n    }\n    \n    // Simulated annealing from best\n    {\n        vector<int> asgn = best_assignment;\n        int cur_cost = best_cost;\n        double temp = 10.0;\n        for (int iter = 0; iter < 50000; iter++) {\n            int k = rng() % M;\n            if (valid_dirs[k].size() <= 1) continue;\n            int orig = asgn[k];\n            int nd = valid_dirs[k][rng() % valid_dirs[k].size()];\n            if (nd == orig) continue;\n            asgn[k] = nd;\n            int nc = compute_cost(asgn);\n            if (nc < cur_cost || (rng() % 1000) < 1000 * exp((cur_cost - nc) / temp)) {\n                cur_cost = nc;\n                if (cur_cost < best_cost) { best_cost = cur_cost; best_assignment = asgn; }\n            } else {\n                asgn[k] = orig;\n            }\n            temp *= 0.99995;\n        }\n    }\n    \n    map<int, vector<int>> batches;\n    for (int k = 0; k < M; k++) batches[get_key(k, best_assignment[k])].push_back(k);\n    \n    vector<pair<char,int>> ops;\n    auto L = [&](int r) { ops.push_back({'L', r}); };\n    auto R = [&](int r) { ops.push_back({'R', r}); };\n    auto U = [&](int c) { ops.push_back({'U', c}); };\n    auto D = [&](int c) { ops.push_back({'D', c}); };\n    \n    for (auto& [key, lst] : batches) {\n        int dir = key / N, idx = key % N;\n        int mx = 0;\n        for (int k : lst) mx = max(mx, dists[k][dir]);\n        if (dir == 0) { for (int t = 0; t < mx; t++) U(idx); for (int t = 0; t < mx; t++) D(idx); }\n        else if (dir == 1) { for (int t = 0; t < mx; t++) D(idx); for (int t = 0; t < mx; t++) U(idx); }\n        else if (dir == 2) { for (int t = 0; t < mx; t++) L(idx); for (int t = 0; t < mx; t++) R(idx); }\n        else { for (int t = 0; t < mx; t++) R(idx); for (int t = 0; t < mx; t++) L(idx); }\n    }\n    \n    for (auto& [d, p] : ops) cout << d << \" \" << p << \"\\n\";\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, L;\nvector<int> T;\n\nlong long simulate(const vector<int>& a, const vector<int>& b, vector<int>& t) {\n    fill(t.begin(), t.end(), 0);\n    int x = 0;\n    for (int week = 0; week < L; week++) {\n        t[x]++;\n        x = (t[x] & 1) ? a[x] : b[x];\n    }\n    long long error = 0;\n    for (int i = 0; i < N; i++) error += abs(t[i] - T[i]);\n    return error;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> L;\n    T.resize(N);\n    for (int i = 0; i < N; i++) cin >> T[i];\n    \n    mt19937 rng(12345);\n    \n    vector<int> weighted;\n    for (int i = 0; i < N; i++) {\n        int cnt = max(1, T[i] / 100);\n        for (int j = 0; j < cnt; j++) weighted.push_back(i);\n    }\n    \n    vector<int> sorted_idx(N);\n    iota(sorted_idx.begin(), sorted_idx.end(), 0);\n    sort(sorted_idx.begin(), sorted_idx.end(), [](int x, int y) { return T[x] > T[y]; });\n    \n    vector<int> best_a(N), best_b(N), t(N);\n    long long global_best = LLONG_MAX;\n    \n    auto start = chrono::steady_clock::now();\n    double time_limit = 1.85;\n    \n    for (int restart = 0; ; restart++) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > time_limit) break;\n        \n        vector<int> a(N), b(N);\n        \n        if (restart == 0) {\n            for (int i = 0; i < N; i++) {\n                a[sorted_idx[i]] = sorted_idx[(i + 1) % N];\n                b[sorted_idx[i]] = sorted_idx[(i + 1) % N];\n            }\n        } else if (restart == 1) {\n            for (int i = 0; i < N; i++) {\n                a[sorted_idx[i]] = sorted_idx[(i + 1) % N];\n                b[sorted_idx[i]] = sorted_idx[(i + 2) % N];\n            }\n        } else if (restart % 3 == 0 && global_best < LLONG_MAX) {\n            a = best_a; b = best_b;\n            for (int k = 0; k < N/4; k++) {\n                int idx = rng() % N;\n                a[idx] = weighted[rng() % weighted.size()];\n                b[idx] = weighted[rng() % weighted.size()];\n            }\n        } else {\n            for (int i = 0; i < N; i++) {\n                a[i] = weighted[rng() % weighted.size()];\n                b[i] = weighted[rng() % weighted.size()];\n            }\n        }\n        \n        long long cur_error = simulate(a, b, t);\n        long long local_best = cur_error;\n        vector<int> local_a = a, local_b = b;\n        \n        double restart_budget = min(0.25, (time_limit - elapsed) * 0.6);\n        double restart_start = elapsed;\n        \n        while (true) {\n            now = chrono::steady_clock::now();\n            elapsed = chrono::duration<double>(now - start).count();\n            if (elapsed > time_limit || elapsed - restart_start > restart_budget) break;\n            \n            double progress = (elapsed - restart_start) / restart_budget;\n            double temp = 2500.0 * pow(0.0001, progress);\n            \n            int i = rng() % N;\n            int old_a = a[i], old_b = b[i];\n            \n            int choice = rng() % 4;\n            if (choice == 0) a[i] = weighted[rng() % weighted.size()];\n            else if (choice == 1) b[i] = weighted[rng() % weighted.size()];\n            else if (choice == 2) a[i] = rng() % N;\n            else b[i] = rng() % N;\n            \n            long long new_error = simulate(a, b, t);\n            double delta = new_error - cur_error;\n            \n            if (delta <= 0 || exp(-delta / temp) > (rng() % 1000000) / 1000000.0) {\n                cur_error = new_error;\n                if (new_error < local_best) {\n                    local_best = new_error;\n                    local_a = a; local_b = b;\n                }\n            } else {\n                a[i] = old_a; b[i] = old_b;\n            }\n        }\n        \n        if (local_best < global_best) {\n            global_best = local_best;\n            best_a = local_a; best_b = local_b;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) cout << best_a[i] << \" \" << best_b[i] << \"\\n\";\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nint queries_used = 0;\nint Q_limit;\n\nvector<pair<int,int>> query(vector<int>& cities) {\n    if (queries_used >= Q_limit || cities.size() < 2) return {};\n    cout << \"? \" << cities.size();\n    for (int c : cities) cout << \" \" << c;\n    cout << endl;\n    \n    vector<pair<int,int>> edges;\n    for (size_t i = 0; i + 1 < cities.size(); i++) {\n        int a, b;\n        cin >> a >> b;\n        edges.emplace_back(a, b);\n    }\n    queries_used++;\n    return edges;\n}\n\ndouble estDist(double x1, double y1, double x2, double y2) {\n    double dx = x1 - x2, dy = y1 - y2;\n    return sqrt(dx*dx + dy*dy);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    Q_limit = Q;\n    \n    vector<int> G(M);\n    for (int i = 0; i < M; i++) cin >> G[i];\n    \n    vector<double> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        x[i] = (lx + rx) / 2.0;\n        y[i] = (ly + ry) / 2.0;\n    }\n    \n    // Greedy nearest-neighbor grouping\n    vector<bool> used(N, false);\n    vector<vector<int>> groups(M);\n    \n    // Sort groups by size descending to handle large groups first\n    vector<int> groupOrder(M);\n    iota(groupOrder.begin(), groupOrder.end(), 0);\n    sort(groupOrder.begin(), groupOrder.end(), [&](int a, int b) {\n        return G[a] > G[b];\n    });\n    \n    for (int gi : groupOrder) {\n        int g = G[gi];\n        \n        // Find starting city (unused city closest to center of remaining unused cities)\n        double cx = 0, cy = 0;\n        int cnt = 0;\n        for (int i = 0; i < N; i++) {\n            if (!used[i]) { cx += x[i]; cy += y[i]; cnt++; }\n        }\n        if (cnt > 0) { cx /= cnt; cy /= cnt; }\n        \n        int start = -1;\n        double minD = 1e18;\n        for (int i = 0; i < N; i++) {\n            if (!used[i]) {\n                double d = estDist(x[i], y[i], cx, cy);\n                if (d < minD) { minD = d; start = i; }\n            }\n        }\n        \n        groups[gi].push_back(start);\n        used[start] = true;\n        \n        // Greedily add nearest city\n        while ((int)groups[gi].size() < g) {\n            int best = -1;\n            double bestD = 1e18;\n            for (int i = 0; i < N; i++) {\n                if (used[i]) continue;\n                double minDistToGroup = 1e18;\n                for (int c : groups[gi]) {\n                    minDistToGroup = min(minDistToGroup, estDist(x[i], y[i], x[c], y[c]));\n                }\n                if (minDistToGroup < bestD) {\n                    bestD = minDistToGroup;\n                    best = i;\n                }\n            }\n            groups[gi].push_back(best);\n            used[best] = true;\n        }\n    }\n    \n    vector<vector<pair<int,int>>> edges(M);\n    \n    for (int k = 0; k < M; k++) {\n        int g = groups[k].size();\n        if (g == 1) continue;\n        \n        // Sort within group for better query locality\n        sort(groups[k].begin(), groups[k].end(), [&](int a, int b) {\n            return x[a] + y[a] < x[b] + y[b];\n        });\n        \n        vector<pair<int,int>> all_edges;\n        \n        if (g <= L && queries_used < Q) {\n            edges[k] = query(groups[k]);\n        } else {\n            // Estimate queries needed and adjust step\n            int queriesNeeded = (g - 1 + L - 2) / (L - 1);\n            int queriesAvailable = Q - queries_used;\n            int step = max(1, (L - 1));\n            \n            // If we have budget, use smaller step for more overlap\n            if (queriesNeeded * 2 <= queriesAvailable) {\n                step = max(1, (L - 1) / 2);\n            }\n            \n            for (int i = 0; i < g && queries_used < Q; i += step) {\n                int end = min(i + L, g);\n                if (end - i >= 2) {\n                    vector<int> subset(groups[k].begin() + i, groups[k].begin() + end);\n                    auto e = query(subset);\n                    all_edges.insert(all_edges.end(), e.begin(), e.end());\n                }\n                if (end >= g) break;\n            }\n            \n            map<int, int> city_to_local;\n            for (int i = 0; i < g; i++) city_to_local[groups[k][i]] = i;\n            \n            vector<int> parent(g);\n            iota(parent.begin(), parent.end(), 0);\n            function<int(int)> find = [&](int u) -> int {\n                return parent[u] == u ? u : parent[u] = find(parent[u]);\n            };\n            \n            sort(all_edges.begin(), all_edges.end(), [&](auto& a, auto& b) {\n                double da = estDist(x[a.first], y[a.first], x[a.second], y[a.second]);\n                double db = estDist(x[b.first], y[b.first], x[b.second], y[b.second]);\n                return da < db;\n            });\n            \n            for (auto& e : all_edges) {\n                int u = city_to_local[e.first];\n                int v = city_to_local[e.second];\n                if (find(u) != find(v)) {\n                    parent[find(u)] = find(v);\n                    edges[k].push_back(e);\n                }\n            }\n            \n            // Fallback: connect components using shortest estimated edges\n            while ((int)edges[k].size() < g - 1) {\n                double best_dist = 1e18;\n                int best_u = -1, best_v = -1;\n                for (int i = 0; i < g; i++) {\n                    for (int j = i + 1; j < g; j++) {\n                        if (find(i) != find(j)) {\n                            double d = estDist(x[groups[k][i]], y[groups[k][i]], \n                                             x[groups[k][j]], y[groups[k][j]]);\n                            if (d < best_dist) {\n                                best_dist = d;\n                                best_u = i;\n                                best_v = j;\n                            }\n                        }\n                    }\n                }\n                if (best_u >= 0) {\n                    parent[find(best_u)] = find(best_v);\n                    edges[k].push_back({groups[k][best_u], groups[k][best_v]});\n                } else break;\n            }\n        }\n    }\n    \n    cout << \"!\" << endl;\n    for (int k = 0; k < M; k++) {\n        for (int c : groups[k]) cout << c << \" \";\n        cout << \"\\n\";\n        for (auto& e : edges[k]) {\n            cout << e.first << \" \" << e.second << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc046":"#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<pair<int, int>> targets(M);\n    for (int i = 0; i < M; i++) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n    \n    vector<string> actions;\n    int curR = targets[0].first, curC = targets[0].second;\n    \n    for (int i = 1; i < M; i++) {\n        int tR = targets[i].first, tC = targets[i].second;\n        \n        int moveCost = abs(tR - curR) + abs(tC - curC);\n        int bestCost = moveCost;\n        int bestStrategy = 0;\n        \n        // Edge target strategies (1-4)\n        if (tR == 0 && curR > 0) {\n            int cost = abs(tC - curC) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 1; }\n        }\n        if (tR == N - 1 && curR < N - 1) {\n            int cost = abs(tC - curC) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 2; }\n        }\n        if (tC == 0 && curC > 0) {\n            int cost = abs(tR - curR) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 3; }\n        }\n        if (tC == N - 1 && curC < N - 1) {\n            int cost = abs(tR - curR) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 4; }\n        }\n        \n        // Slide-first strategies (5-8)\n        if (curR > 0) {\n            int cost = 1 + tR + abs(tC - curC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 5; }\n        }\n        if (curR < N - 1) {\n            int cost = 1 + (N - 1 - tR) + abs(tC - curC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 6; }\n        }\n        if (curC > 0) {\n            int cost = 1 + tC + abs(tR - curR);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 7; }\n        }\n        if (curC < N - 1) {\n            int cost = 1 + (N - 1 - tC) + abs(tR - curR);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 8; }\n        }\n        \n        // Double-slide to corners (9-12)\n        if (curR > 0 && curC > 0) { // to (0,0)\n            int cost = 2 + tR + tC;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 9; }\n        }\n        if (curR > 0 && curC < N - 1) { // to (0, N-1)\n            int cost = 2 + tR + (N - 1 - tC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 10; }\n        }\n        if (curR < N - 1 && curC > 0) { // to (N-1, 0)\n            int cost = 2 + (N - 1 - tR) + tC;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 11; }\n        }\n        if (curR < N - 1 && curC < N - 1) { // to (N-1, N-1)\n            int cost = 2 + (N - 1 - tR) + (N - 1 - tC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 12; }\n        }\n        \n        switch (bestStrategy) {\n            case 0:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                break;\n            case 1: case 2: case 3: case 4:\n                if (bestStrategy <= 2) {\n                    while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                    while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                    actions.push_back(bestStrategy == 1 ? \"S U\" : \"S D\");\n                    curR = (bestStrategy == 1) ? 0 : N - 1;\n                } else {\n                    while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                    while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                    actions.push_back(bestStrategy == 3 ? \"S L\" : \"S R\");\n                    curC = (bestStrategy == 3) ? 0 : N - 1;\n                }\n                break;\n            case 5: actions.push_back(\"S U\"); curR = 0; goto moveToTarget;\n            case 6: actions.push_back(\"S D\"); curR = N - 1; goto moveToTarget;\n            case 7: actions.push_back(\"S L\"); curC = 0; goto moveToTarget;\n            case 8: actions.push_back(\"S R\"); curC = N - 1; goto moveToTarget;\n            case 9: actions.push_back(\"S U\"); curR = 0; actions.push_back(\"S L\"); curC = 0; goto moveToTarget;\n            case 10: actions.push_back(\"S U\"); curR = 0; actions.push_back(\"S R\"); curC = N - 1; goto moveToTarget;\n            case 11: actions.push_back(\"S D\"); curR = N - 1; actions.push_back(\"S L\"); curC = 0; goto moveToTarget;\n            case 12: actions.push_back(\"S D\"); curR = N - 1; actions.push_back(\"S R\"); curC = N - 1; goto moveToTarget;\n            moveToTarget:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                break;\n        }\n    }\n    \n    for (const string& action : actions) {\n        cout << action << \"\\n\";\n    }\n    \n    return 0;\n}"},"8":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int W = 10000;\nint n;\nvector<int> px, py, rr;\nint a[201], b[201], c[201], d[201];\n\nbool canExpand(int i, int dir) {\n    int na = a[i], nb = b[i], nc = c[i], nd = d[i];\n    if (dir == 0) na--; else if (dir == 1) nc++; else if (dir == 2) nb--; else nd++;\n    if (na < 0 || nc > W || nb < 0 || nd > W) return false;\n    for (int j = 0; j < n; j++) {\n        if (i != j && !(nc <= a[j] || c[j] <= na || nd <= b[j] || d[j] <= nb)) return false;\n    }\n    return true;\n}\n\nvoid doExpand(int i, int dir) {\n    if (dir == 0) a[i]--; else if (dir == 1) c[i]++; else if (dir == 2) b[i]--; else d[i]++;\n}\n\nlong long area(int i) { return (long long)(c[i] - a[i]) * (d[i] - b[i]); }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> n;\n    px.resize(n); py.resize(n); rr.resize(n);\n    for (int i = 0; i < n; i++) {\n        cin >> px[i] >> py[i] >> rr[i];\n        a[i] = px[i]; b[i] = py[i]; c[i] = px[i]+1; d[i] = py[i]+1;\n    }\n    \n    auto start = chrono::high_resolution_clock::now();\n    auto timeOk = [&]() {\n        return chrono::duration<double>(chrono::high_resolution_clock::now() - start).count() < 4.7;\n    };\n    \n    // Phase 1: Expand only up to target, prioritize by relative deficit\n    while (timeOk()) {\n        bool changed = false;\n        vector<int> order(n);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(), [&](int i, int j) {\n            double di = (double)(rr[i] - area(i)) / rr[i];\n            double dj = (double)(rr[j] - area(j)) / rr[j];\n            return di > dj;\n        });\n        \n        for (int i : order) {\n            if (area(i) >= rr[i]) continue;\n            for (int dir = 0; dir < 4; dir++) {\n                if (area(i) >= rr[i]) break;\n                if (canExpand(i, dir)) {\n                    doExpand(i, dir);\n                    changed = true;\n                }\n            }\n        }\n        if (!changed) break;\n    }\n    \n    // Phase 2: Fill remaining space (some rectangles couldn't reach target)\n    while (timeOk()) {\n        bool changed = false;\n        vector<int> order(n);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(), [&](int i, int j) {\n            return rr[i] - area(i) > rr[j] - area(j);\n        });\n        \n        for (int i : order) {\n            for (int dir = 0; dir < 4; dir++) {\n                if (canExpand(i, dir)) {\n                    doExpand(i, dir);\n                    changed = true;\n                }\n            }\n        }\n        if (!changed) break;\n    }\n    \n    // Phase 3: Multiple shrink-expand cycles\n    for (int cycle = 0; cycle < 10 && timeOk(); cycle++) {\n        // Shrink oversized (prioritize most oversized)\n        for (int iter = 0; iter < 1000 && timeOk(); iter++) {\n            bool changed = false;\n            vector<int> order(n);\n            iota(order.begin(), order.end(), 0);\n            sort(order.begin(), order.end(), [&](int i, int j) {\n                return area(i) - rr[i] > area(j) - rr[j];\n            });\n            \n            for (int i : order) {\n                if (area(i) <= rr[i]) continue;\n                for (int dir = 0; dir < 4; dir++) {\n                    int na = a[i], nb = b[i], nc = c[i], nd = d[i];\n                    if (dir == 0) na++; else if (dir == 1) nc--; else if (dir == 2) nb++; else nd--;\n                    if (na >= nc || nb >= nd) continue;\n                    if (!(na <= px[i] && px[i] < nc && nb <= py[i] && py[i] < nd)) continue;\n                    if ((long long)(nc - na) * (nd - nb) >= rr[i]) {\n                        a[i] = na; b[i] = nb; c[i] = nc; d[i] = nd;\n                        changed = true;\n                    }\n                }\n            }\n            if (!changed) break;\n        }\n        \n        // Expand undersized\n        for (int iter = 0; iter < 1000 && timeOk(); iter++) {\n            bool changed = false;\n            vector<int> order(n);\n            iota(order.begin(), order.end(), 0);\n            sort(order.begin(), order.end(), [&](int i, int j) {\n                return rr[i] - area(i) > rr[j] - area(j);\n            });\n            \n            for (int i : order) {\n                if (area(i) >= rr[i]) continue;\n                for (int dir = 0; dir < 4; dir++) {\n                    if (canExpand(i, dir)) {\n                        doExpand(i, dir);\n                        changed = true;\n                    }\n                }\n            }\n            if (!changed) break;\n        }\n    }\n    \n    for (int i = 0; i < n; i++) {\n        cout << a[i] << \" \" << b[i] << \" \" << c[i] << \" \" << d[i] << \"\\n\";\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dc[] = {'U', 'D', 'L', 'R'};\n\nint t[N][N], p[N][N];\nint si, sj;\nmt19937 rng;\n\ninline int countMoves(int x, int y, const bitset<2500>& used, int curTile) {\n    int cnt = 0;\n    for (int d = 0; d < 4; d++) {\n        int nx = x + dx[d], ny = y + dy[d];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N && !used[t[nx][ny]] && t[nx][ny] != curTile) cnt++;\n    }\n    return cnt;\n}\n\nvoid runBeamSearch(int beamWidth, int moveWeight, int timeLimit,\n                   string& bestPath, int& bestScore, chrono::steady_clock::time_point startTime,\n                   int randRange = 0) {\n    struct State {\n        int x, y, score, priority;\n        bitset<2500> usedTiles;\n        string path;\n    };\n    \n    vector<State> beam;\n    State init;\n    init.x = si; init.y = sj;\n    init.score = p[si][sj];\n    init.usedTiles.set(t[si][sj]);\n    init.path = \"\";\n    init.priority = init.score + countMoves(si, sj, init.usedTiles, -1) * moveWeight;\n    beam.push_back(init);\n    \n    while (!beam.empty()) {\n        if (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() > timeLimit) {\n            for (const auto& state : beam) {\n                if (state.score > bestScore) {\n                    bestScore = state.score;\n                    bestPath = state.path;\n                }\n            }\n            break;\n        }\n        \n        vector<State> nextBeam;\n        nextBeam.reserve(beam.size() * 4);\n        \n        for (const auto& state : beam) {\n            bool canExtend = false;\n            for (int d = 0; d < 4; d++) {\n                int nx = state.x + dx[d];\n                int ny = state.y + dy[d];\n                if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                if (state.usedTiles[t[nx][ny]]) continue;\n                \n                canExtend = true;\n                State newState;\n                newState.x = nx; newState.y = ny;\n                newState.score = state.score + p[nx][ny];\n                newState.usedTiles = state.usedTiles;\n                newState.usedTiles.set(t[nx][ny]);\n                newState.path = state.path + dc[d];\n                \n                int fm = countMoves(nx, ny, newState.usedTiles, -1);\n                newState.priority = newState.score + fm * moveWeight;\n                if (randRange > 0) newState.priority += rng() % randRange;\n                nextBeam.push_back(move(newState));\n            }\n            if (!canExtend && state.score > bestScore) {\n                bestScore = state.score;\n                bestPath = state.path;\n            }\n        }\n        \n        if ((int)nextBeam.size() > beamWidth) {\n            nth_element(nextBeam.begin(), nextBeam.begin() + beamWidth, nextBeam.end(),\n                [](const State& a, const State& b) { return a.priority > b.priority; });\n            nextBeam.resize(beamWidth);\n        }\n        \n        beam = move(nextBeam);\n    }\n}\n\nvoid randomGreedy(string& bestPath, int& bestScore, int moveWeight, int randPercent) {\n    int x = si, y = sj;\n    int score = p[si][sj];\n    string path = \"\";\n    bitset<2500> usedTiles;\n    usedTiles.set(t[si][sj]);\n    \n    while (true) {\n        vector<pair<int, int>> moves;\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            if (usedTiles[t[nx][ny]]) continue;\n            int fm = countMoves(nx, ny, usedTiles, t[nx][ny]);\n            moves.push_back({p[nx][ny] + fm * moveWeight, d});\n        }\n        if (moves.empty()) break;\n        sort(moves.begin(), moves.end(), greater<pair<int,int>>());\n        \n        int choice = 0;\n        if (moves.size() > 1 && (int)(rng() % 100) < randPercent) {\n            choice = rng() % min((int)moves.size(), 3);\n        }\n        \n        int d = moves[choice].second;\n        x += dx[d]; y += dy[d];\n        score += p[x][y];\n        usedTiles.set(t[x][y]);\n        path += dc[d];\n    }\n    if (score > bestScore) {\n        bestScore = score;\n        bestPath = path;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    auto startTime = chrono::steady_clock::now();\n    rng.seed(chrono::steady_clock::now().time_since_epoch().count());\n    \n    cin >> si >> sj;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) cin >> t[i][j];\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) cin >> p[i][j];\n    \n    string bestPath = \"\";\n    int bestScore = p[si][sj];\n    \n    // Diverse beam searches - balanced parameters\n    runBeamSearch(700, 0, 200, bestPath, bestScore, startTime);      // Pure score\n    runBeamSearch(700, 40, 400, bestPath, bestScore, startTime);     // Light move\n    runBeamSearch(700, 80, 600, bestPath, bestScore, startTime);     // Moderate\n    runBeamSearch(700, 120, 800, bestPath, bestScore, startTime);    // Move heavy\n    runBeamSearch(700, 150, 1000, bestPath, bestScore, startTime);   // Very move heavy\n    runBeamSearch(600, 60, 1150, bestPath, bestScore, startTime, 25); // With randomness\n    runBeamSearch(600, 100, 1300, bestPath, bestScore, startTime, 30); // Random + moves\n    \n    // Extended random greedy with varied strategies\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() < 1950) {\n        int moveW = 10 + rng() % 40;  // 10-50\n        int randP = 20 + rng() % 30;  // 20-50\n        randomGreedy(bestPath, bestScore, moveW, randP);\n    }\n    \n    cout << bestPath << endl;\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\ndouble h[N][N-1], v[N-1][N];\nint h_cnt[N][N-1], v_cnt[N-1][N];\ndouble g_sum = 0;\nint g_cnt = 0;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    fill(&h[0][0], &h[0][0] + N*(N-1), 5000.0);\n    fill(&v[0][0], &v[0][0] + (N-1)*N, 5000.0);\n    fill(&h_cnt[0][0], &h_cnt[0][0] + N*(N-1), 0);\n    fill(&v_cnt[0][0], &v_cnt[0][0] + (N-1)*N, 0);\n    \n    auto getH = [&](int i, int j) -> double {\n        if (h_cnt[i][j] > 0) return h[i][j];\n        // Distance-weighted row average\n        double sum = 0, wgt = 0;\n        for (int k = 0; k < N-1; k++) {\n            if (h_cnt[i][k] > 0) {\n                double w = 1.0 / (1.0 + abs(j - k));\n                sum += h[i][k] * w;\n                wgt += w;\n            }\n        }\n        if (wgt > 0) return sum / wgt;\n        if (g_cnt > 0) return g_sum / g_cnt;\n        return 5000.0;\n    };\n    \n    auto getV = [&](int i, int j) -> double {\n        if (v_cnt[i][j] > 0) return v[i][j];\n        // Distance-weighted column average\n        double sum = 0, wgt = 0;\n        for (int k = 0; k < N-1; k++) {\n            if (v_cnt[k][j] > 0) {\n                double w = 1.0 / (1.0 + abs(i - k));\n                sum += v[k][j] * w;\n                wgt += w;\n            }\n        }\n        if (wgt > 0) return sum / wgt;\n        if (g_cnt > 0) return g_sum / g_cnt;\n        return 5000.0;\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 idx = [](int i, int j) { return i * N + j; };\n        vector<double> dist(N*N, 1e18);\n        vector<int> prv(N*N, -1);\n        \n        priority_queue<pair<double,int>, vector<pair<double,int>>, greater<>> pq;\n        dist[idx(si, sj)] = 0;\n        pq.push({0, idx(si, sj)});\n        \n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u]) continue;\n            int i = u / N, j = u % N;\n            \n            auto relax = [&](int ni, int nj, double w) {\n                int nu = idx(ni, nj);\n                if (dist[u] + w < dist[nu]) {\n                    dist[nu] = dist[u] + w;\n                    prv[nu] = u;\n                    pq.push({dist[nu], nu});\n                }\n            };\n            \n            if (i > 0) relax(i-1, j, getV(i-1, j));\n            if (i < N-1) relax(i+1, j, getV(i, j));\n            if (j > 0) relax(i, j-1, getH(i, j-1));\n            if (j < N-1) relax(i, j+1, getH(i, j));\n        }\n        \n        string path = \"\";\n        vector<tuple<int, int, int>> edges;\n        \n        int cur = idx(ti, tj);\n        while (prv[cur] != -1) {\n            int ci = cur / N, cj = cur % N;\n            int pi = prv[cur] / N, pj = prv[cur] % N;\n            \n            if (ci < pi) { path += 'U'; edges.emplace_back(1, ci, cj); }\n            else if (ci > pi) { path += 'D'; edges.emplace_back(1, pi, pj); }\n            else if (cj < pj) { path += 'L'; edges.emplace_back(0, ci, cj); }\n            else { path += 'R'; edges.emplace_back(0, pi, pj); }\n            \n            cur = prv[cur];\n        }\n        \n        reverse(path.begin(), path.end());\n        cout << path << \"\\n\" << flush;\n        \n        int feedback;\n        cin >> feedback;\n        \n        double est = 0;\n        for (auto& [t, ei, ej] : edges) {\n            est += (t == 0) ? getH(ei, ej) : getV(ei, ej);\n        }\n        \n        double ratio = feedback / est;\n        \n        for (auto& [t, ei, ej] : edges) {\n            double implied = (t == 0) ? getH(ei, ej) * ratio : getV(ei, ej) * ratio;\n            \n            if (t == 0) {\n                int cnt = ++h_cnt[ei][ej];\n                double alpha = 1.0 / (1.0 + cnt);\n                h[ei][ej] = h[ei][ej] * (1 - alpha) + implied * alpha;\n            } else {\n                int cnt = ++v_cnt[ei][ej];\n                double alpha = 1.0 / (1.0 + cnt);\n                v[ei][ej] = v[ei][ej] * (1 - alpha) + implied * alpha;\n            }\n        }\n        \n        // Update global average\n        g_sum = 0; g_cnt = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N-1; j++) {\n                if (h_cnt[i][j] > 0) { g_sum += h[i][j]; g_cnt++; }\n            }\n        }\n        for (int i = 0; i < N-1; i++) {\n            for (int j = 0; j < N; j++) {\n                if (v_cnt[i][j] > 0) { g_sum += v[i][j]; g_cnt++; }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;\nint m;\nvector<string> strs;\n\nbool matchAt(const char grid[N][N], int idx, int r, int c, int d) {\n    const string& s = strs[idx];\n    for(int p = 0; p < (int)s.size(); p++) {\n        int ni = d ? (r+p)%N : r, nj = d ? c : (c+p)%N;\n        if(grid[ni][nj] != s[p]) return false;\n    }\n    return true;\n}\n\ntuple<int,int,int> findMatch(const char grid[N][N], int idx) {\n    for(int r = 0; r < N; r++)\n        for(int c = 0; c < N; c++) {\n            if(matchAt(grid, idx, r, c, 0)) return {r, c, 0};\n            if(matchAt(grid, idx, r, c, 1)) return {r, c, 1};\n        }\n    return {-1, -1, -1};\n}\n\nbool posContains(int r, int c, int d, int len, int i, int j) {\n    for(int p = 0; p < len; p++) {\n        int ni = d ? (r+p)%N : r, nj = d ? c : (c+p)%N;\n        if(ni == i && nj == j) return true;\n    }\n    return false;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n; cin >> n >> m;\n    strs.resize(m);\n    for(int i = 0; i < m; i++) cin >> strs[i];\n    \n    mt19937 rng(12345);\n    char bestGrid[N][N];\n    int bestScore = 0;\n    auto start = chrono::high_resolution_clock::now();\n    \n    for(int trial = 0; ; trial++) {\n        if(chrono::duration<double>(chrono::high_resolution_clock::now() - start).count() > 2.0) break;\n        \n        char grid[N][N]; fill(&grid[0][0], &grid[N][0], '.');\n        vector<int> order(m); iota(order.begin(), order.end(), 0);\n        if(trial % 3 == 0) sort(order.begin(), order.end(), [&](int a, int b) { return strs[a].size() > strs[b].size(); });\n        else { shuffle(order.begin(), order.end(), rng); if(trial % 3 == 1) stable_sort(order.begin(), order.end(), [&](int a, int b) { return strs[a].size() > strs[b].size(); }); }\n        \n        for(int idx : order) {\n            const string& s = strs[idx];\n            vector<tuple<int,int,int>> cands; int bestOv = -1;\n            for(int r = 0; r < N; r++) for(int c = 0; c < N; c++) for(int d = 0; d < 2; d++) {\n                bool can = true; int ov = 0;\n                for(int p = 0; p < (int)s.size(); p++) {\n                    int ni = d?(r+p)%N:r, nj = d?c:(c+p)%N;\n                    if(grid[ni][nj] != '.' && grid[ni][nj] != s[p]) { can = false; break; }\n                    if(grid[ni][nj] != '.') ov++;\n                }\n                if(can && ov >= bestOv) { if(ov > bestOv) { bestOv = ov; cands.clear(); } cands.push_back({r,c,d}); }\n            }\n            if(!cands.empty()) { auto [r,c,d] = cands[rng()%cands.size()]; for(int p = 0; p < (int)s.size(); p++) { int ni = d?(r+p)%N:r, nj = d?c:(c+p)%N; grid[ni][nj] = s[p]; } }\n        }\n        for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) if(grid[i][j] == '.') grid[i][j] = 'A' + rng()%8;\n        int score = 0; for(int i = 0; i < m; i++) if(get<0>(findMatch(grid, i)) >= 0) score++;\n        if(score > bestScore) { bestScore = score; memcpy(bestGrid, grid, sizeof(grid)); }\n    }\n    \n    char grid[N][N]; memcpy(grid, bestGrid, sizeof(grid));\n    vector<tuple<int,int,int>> matchPos(m);\n    for(int i = 0; i < m; i++) matchPos[i] = findMatch(grid, i);\n    int curScore = bestScore;\n    \n    while(true) {\n        double elapsed = chrono::duration<double>(chrono::high_resolution_clock::now() - start).count();\n        if(elapsed > 2.95) break;\n        double T = 1.5 * max(0.01, 1.0 - elapsed / 3.0);\n        \n        int ci = rng()%N, cj = rng()%N;\n        char old = grid[ci][cj], newc = 'A' + rng()%8;\n        if(newc == old) continue;\n        \n        grid[ci][cj] = newc;\n        int delta = 0;\n        vector<pair<int, tuple<int,int,int>>> changes;\n        \n        for(int idx = 0; idx < m; idx++) {\n            auto [r,c,d] = matchPos[idx];\n            int len = strs[idx].size();\n            if(r >= 0 && posContains(r, c, d, len, ci, cj)) {\n                if(!matchAt(grid, idx, r, c, d)) {\n                    auto nm = findMatch(grid, idx);\n                    changes.push_back({idx, nm});\n                    if(get<0>(nm) < 0) delta--;\n                }\n            } else if(r < 0) {\n                for(int p = 0; p < len; p++) {\n                    int sc = (cj - p + N) % N;\n                    if(matchAt(grid, idx, ci, sc, 0)) { delta++; changes.push_back({idx, {ci,sc,0}}); goto nxt; }\n                }\n                for(int p = 0; p < len; p++) {\n                    int sr = (ci - p + N) % N;\n                    if(matchAt(grid, idx, sr, cj, 1)) { delta++; changes.push_back({idx, {sr,cj,1}}); goto nxt; }\n                }\n                nxt:;\n            }\n        }\n        \n        if(delta >= 0 || (rng()&0xFFFF) < 65536.0 * exp(delta / T)) {\n            curScore += delta;\n            for(auto& [idx, pos] : changes) matchPos[idx] = pos;\n            if(curScore > bestScore) { bestScore = curScore; memcpy(bestGrid, grid, sizeof(grid)); }\n        } else grid[ci][cj] = old;\n    }\n    \n    for(int i = 0; i < N; i++) cout << string(bestGrid[i], bestGrid[i]+N) << '\\n';\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, si, sj;\nvector<string> grid;\n\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir_char[] = {'U', 'D', 'L', 'R'};\n\ninline bool is_road(int i, int j) {\n    return i >= 0 && i < N && j >= 0 && j < N && grid[i][j] != '#';\n}\n\npair<vector<vector<int>>, vector<vector<pair<int,int>>>> dijkstra(int si, int sj) {\n    vector<vector<int>> dist(N, vector<int>(N, INT_MAX));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1,-1}));\n    priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;\n    dist[si][sj] = 0; pq.push({0, si, sj});\n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top(); pq.pop();\n        if (d > dist[i][j]) continue;\n        for (int k = 0; k < 4; k++) {\n            int ni = i + dx[k], nj = j + dy[k];\n            if (is_road(ni, nj)) {\n                int c = grid[ni][nj] - '0';\n                if (dist[i][j] + c < dist[ni][nj]) {\n                    dist[ni][nj] = dist[i][j] + c;\n                    parent[ni][nj] = {i, j};\n                    pq.push({dist[ni][nj], ni, nj});\n                }\n            }\n        }\n    }\n    return {dist, parent};\n}\n\nstring get_path(int i1, int j1, int i2, int j2, vector<vector<pair<int,int>>>& parent) {\n    if (i1 == i2 && j1 == j2) return \"\";\n    string path;\n    int ci = i2, cj = j2;\n    while (ci != i1 || cj != j1) {\n        auto [pi, pj] = parent[ci][cj];\n        for (int k = 0; k < 4; k++) if (pi + dx[k] == ci && pj + dy[k] == cj) { path += dir_char[k]; break; }\n        ci = pi; cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint calc_path_time(const string& path) {\n    int time = 0, ci = si, cj = sj;\n    for (char c : path) {\n        if (c == 'U') ci--; else if (c == 'D') ci++; else if (c == 'L') cj--; else cj++;\n        time += grid[ci][cj] - '0';\n    }\n    return time;\n}\n\nstring solve(double alpha, int check_limit) {\n    vector<vector<bool>> visible(N, vector<bool>(N, false));\n    int visible_count = 0, total_roads = 0;\n    for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (is_road(i, j)) total_roads++;\n    \n    auto mark_visible = [&](int i, int j) {\n        if (!visible[i][j]) { visible[i][j] = true; visible_count++; }\n        for (int jj = j - 1; jj >= 0 && is_road(i, jj); jj--) if (!visible[i][jj]) { visible[i][jj] = true; visible_count++; }\n        for (int jj = j + 1; jj < N && is_road(i, jj); jj++) if (!visible[i][jj]) { visible[i][jj] = true; visible_count++; }\n        for (int ii = i - 1; ii >= 0 && is_road(ii, j); ii--) if (!visible[ii][j]) { visible[ii][j] = true; visible_count++; }\n        for (int ii = i + 1; ii < N && is_road(ii, j); ii++) if (!visible[ii][j]) { visible[ii][j] = true; visible_count++; }\n    };\n    \n    auto count_new_visible = [&](int i, int j) {\n        int cnt = !visible[i][j];\n        for (int jj = j - 1; jj >= 0 && is_road(i, jj); jj--) cnt += !visible[i][jj];\n        for (int jj = j + 1; jj < N && is_road(i, jj); jj++) cnt += !visible[i][jj];\n        for (int ii = i - 1; ii >= 0 && is_road(ii, j); ii--) cnt += !visible[ii][j];\n        for (int ii = i + 1; ii < N && is_road(ii, j); ii++) cnt += !visible[ii][j];\n        return cnt;\n    };\n    \n    auto calc_path_visibility = [&](int si, int sj, const string& path) {\n        auto vis = visible;\n        int cnt = 0, ci = si, cj = sj;\n        for (char c : path) {\n            if (c == 'U') ci--; else if (c == 'D') ci++; else if (c == 'L') cj--; else cj++;\n            if (!vis[ci][cj]) { vis[ci][cj] = true; cnt++; }\n            for (int jj = cj - 1; jj >= 0 && is_road(ci, jj); jj--) if (!vis[ci][jj]) { vis[ci][jj] = true; cnt++; }\n            for (int jj = cj + 1; jj < N && is_road(ci, jj); jj++) if (!vis[ci][jj]) { vis[ci][jj] = true; cnt++; }\n            for (int ii = ci - 1; ii >= 0 && is_road(ii, cj); ii--) if (!vis[ii][cj]) { vis[ii][cj] = true; cnt++; }\n            for (int ii = ci + 1; ii < N && is_road(ii, cj); ii++) if (!vis[ii][cj]) { vis[ii][cj] = true; cnt++; }\n        }\n        return cnt;\n    };\n    \n    auto [dist_from_start, parent_from_start] = dijkstra(si, sj);\n    int cur_i = si, cur_j = sj;\n    string result;\n    mark_visible(cur_i, cur_j);\n    \n    while (visible_count < total_roads) {\n        auto [dist, parent] = dijkstra(cur_i, cur_j);\n        \n        vector<tuple<double, int, int>> candidates;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (dist[i][j] == INT_MAX || dist[i][j] == 0) continue;\n                int nv = count_new_visible(i, j);\n                if (nv == 0) continue;\n                double cost = dist[i][j] + alpha * dist_from_start[i][j];\n                candidates.push_back({-(double)nv / cost, i, j});\n            }\n        }\n        \n        if (candidates.empty()) break;\n        sort(candidates.begin(), candidates.end());\n        \n        int best_i = -1, best_j = -1;\n        double best_score = -1e18;\n        string best_path;\n        \n        int check_count = min((int)candidates.size(), check_limit);\n        for (int c = 0; c < check_count; c++) {\n            auto [_, i, j] = candidates[c];\n            string path = get_path(cur_i, cur_j, i, j, parent);\n            double nv = (check_limit > 1) ? calc_path_visibility(cur_i, cur_j, path) : count_new_visible(i, j);\n            if (nv == 0) continue;\n            double cost = dist[i][j] + alpha * dist_from_start[i][j];\n            double score = nv / cost;\n            if (score > best_score) { best_score = score; best_i = i; best_j = j; best_path = path; }\n        }\n        \n        if (best_i == -1) break;\n        result += best_path;\n        int ti = cur_i, tj = cur_j;\n        for (char c : best_path) {\n            if (c == 'U') ti--; else if (c == 'D') ti++; else if (c == 'L') tj--; else tj++;\n            mark_visible(ti, tj);\n        }\n        cur_i = best_i; cur_j = best_j;\n    }\n    \n    if (cur_i != si || cur_j != sj) {\n        auto [dist, parent] = dijkstra(cur_i, cur_j);\n        result += get_path(cur_i, cur_j, si, sj, parent);\n    }\n    return result;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(nullptr);\n    cin >> N >> si >> sj;\n    grid.resize(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    \n    string best_result;\n    int best_time = INT_MAX;\n    \n    vector<double> alphas;\n    for (int i = 0; i <= 20; i++) alphas.push_back(i * 0.02);  // 0.0 to 0.4 step 0.02\n    alphas.push_back(0.45);\n    alphas.push_back(0.5);\n    \n    vector<int> check_limits = {1, 12, 20, 30};\n    \n    for (double alpha : alphas) {\n        for (int cl : check_limits) {\n            string result = solve(alpha, cl);\n            int time = calc_path_time(result);\n            if (time < best_time) { best_time = time; best_result = result; }\n        }\n    }\n    \n    cout << best_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    vector<vector<int>> deps(N), rdeps(N);\n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        deps[v].push_back(u);\n        rdeps[u].push_back(v);\n    }\n    \n    vector<int> taskStatus(N, -1);\n    vector<int> memberTask(M, -1), memberStartDay(M, 0);\n    \n    double initSkill = 40.0 / sqrt(K);\n    vector<vector<double>> skillEst(M, vector<double>(K, initSkill));\n    vector<vector<double>> skillLo(M, vector<double>(K, 0.0));\n    \n    auto estimateTime = [&](int task, int member) -> double {\n        double w = 0;\n        for (int k = 0; k < K; k++)\n            w += max(0.0, (double)d[task][k] - skillEst[member][k]);\n        return max(1.0, w);\n    };\n    \n    auto avgTime = [&](int task) -> double {\n        double sum = 0;\n        for (int j = 0; j < M; j++) sum += estimateTime(task, j);\n        return sum / M;\n    };\n    \n    vector<int> downstream(N, 0);\n    for (int i = N - 1; i >= 0; i--) {\n        downstream[i] = (int)rdeps[i].size();\n        for (int v : rdeps[i]) downstream[i] += downstream[v];\n    }\n    \n    vector<double> wdepth(N);\n    auto recalcDepth = [&]() {\n        for (int i = N - 1; i >= 0; i--) {\n            if (taskStatus[i] == 1) { wdepth[i] = 0; continue; }\n            wdepth[i] = avgTime(i);\n            double maxChild = 0;\n            for (int v : rdeps[i]) maxChild = max(maxChild, wdepth[v]);\n            wdepth[i] += maxChild;\n        }\n    };\n    recalcDepth();\n    \n    for (int day = 1; ; day++) {\n        if (day % 25 == 1) recalcDepth();\n        \n        vector<int> availTasks;\n        for (int i = 0; i < N; i++) {\n            if (taskStatus[i] != -1) continue;\n            bool ok = true;\n            for (int dep : deps[i])\n                if (taskStatus[dep] != 1) { ok = false; break; }\n            if (ok) availTasks.push_back(i);\n        }\n        \n        vector<int> freeMembers;\n        for (int j = 0; j < M; j++)\n            if (memberTask[j] == -1) freeMembers.push_back(j);\n        \n        vector<tuple<double, int, int>> candidates;\n        for (int task : availTasks) {\n            for (int member : freeMembers) {\n                double t = estimateTime(task, member);\n                double score = wdepth[task] / max(1.0, t) + 0.001 * downstream[task];\n                candidates.push_back({-score, task, member});\n            }\n        }\n        sort(candidates.begin(), candidates.end());\n        \n        vector<pair<int, int>> assignments;\n        vector<bool> usedMember(M, false), usedTask(N, false);\n        \n        for (auto& [score, task, member] : candidates) {\n            if (usedMember[member] || usedTask[task]) continue;\n            usedMember[member] = true;\n            usedTask[task] = true;\n            assignments.push_back({member + 1, task + 1});\n            taskStatus[task] = 0;\n            memberTask[member] = task;\n            memberStartDay[member] = day;\n        }\n        \n        cout << assignments.size();\n        for (auto& [a, b] : assignments) cout << \" \" << a << \" \" << b;\n        cout << \"\\n\";\n        cout.flush();\n        \n        int n; cin >> n;\n        if (n == -1) break;\n        \n        for (int i = 0; i < n; i++) {\n            int f; cin >> f; f--;\n            int task = memberTask[f];\n            int timeTaken = day - memberStartDay[f] + 1;\n            taskStatus[task] = 1;\n            memberTask[f] = -1;\n            \n            if (timeTaken == 1) {\n                for (int k = 0; k < K; k++) {\n                    skillLo[f][k] = max(skillLo[f][k], (double)d[task][k]);\n                    skillEst[f][k] = max(skillEst[f][k], (double)d[task][k]);\n                }\n            } else {\n                double wEst = (double)timeTaken;\n                double currW = 0;\n                for (int k = 0; k < K; k++)\n                    currW += max(0.0, (double)d[task][k] - skillEst[f][k]);\n                \n                if (currW > 0.5) {\n                    double factor = wEst / currW;\n                    factor = 0.65 * factor + 0.35;\n                    factor = max(0.5, min(1.6, factor));\n                    \n                    for (int k = 0; k < K; k++) {\n                        double gap = d[task][k] - skillEst[f][k];\n                        if (gap > 0) {\n                            double newSkill = d[task][k] - gap * factor;\n                            skillEst[f][k] = max(skillLo[f][k], newSkill);\n                        }\n                    }\n                } else if (wEst > 4) {\n                    double totalReq = 0;\n                    for (int k = 0; k < K; k++) totalReq += d[task][k];\n                    if (totalReq > 0.5) {\n                        for (int k = 0; k < K; k++) {\n                            double reduction = (wEst - 2) * d[task][k] / totalReq;\n                            skillEst[f][k] = max(skillLo[f][k], skillEst[f][k] - reduction);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1000, M = 50, CX = 400, CY = 400;\nint ordA[N], ordB[N], ordC[N], ordD[N];\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\ninline int dist(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint buildRoute(const vector<int>& sel, vector<pair<int,bool>>& ev) {\n    ev.clear();\n    ev.reserve(2 * M);\n    bool picked[N] = {}, done[N] = {};\n    int cx = CX, cy = CY, cost = 0;\n    \n    for (int i = 0; i < 2*M; i++) {\n        int best = -1, bd = 1e9;\n        bool isDel = false;\n        for (int j : sel) {\n            if (!picked[j]) {\n                int d = dist(cx, cy, ordA[j], ordB[j]);\n                if (d < bd) { bd = d; best = j; isDel = false; }\n            } else if (!done[j]) {\n                int d = dist(cx, cy, ordC[j], ordD[j]);\n                if (d < bd) { bd = d; best = j; isDel = true; }\n            }\n        }\n        cost += bd;\n        if (isDel) { cx = ordC[best]; cy = ordD[best]; done[best] = true; }\n        else { cx = ordA[best]; cy = ordB[best]; picked[best] = true; }\n        ev.push_back({best, isDel});\n    }\n    return cost + dist(cx, cy, CX, CY);\n}\n\nint calcCost(const vector<pair<int,bool>>& ev) {\n    int cx = CX, cy = CY, cost = 0;\n    for (auto& [idx, isDel] : ev) {\n        int nx = isDel ? ordC[idx] : ordA[idx];\n        int ny = isDel ? ordD[idx] : ordB[idx];\n        cost += dist(cx, cy, nx, ny);\n        cx = nx; cy = ny;\n    }\n    return cost + dist(cx, cy, CX, CY);\n}\n\nbool validSwap(vector<pair<int,bool>>& ev, int i, int j) {\n    swap(ev[i], ev[j]);\n    int pickPos[N];\n    memset(pickPos, -1, sizeof(pickPos));\n    for (int k = 0; k < (int)ev.size(); k++) {\n        if (!ev[k].second) pickPos[ev[k].first] = k;\n        else if (pickPos[ev[k].first] < 0 || pickPos[ev[k].first] > k) {\n            swap(ev[i], ev[j]);\n            return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    auto st = chrono::steady_clock::now();\n    for (int i = 0; i < N; i++) cin >> ordA[i] >> ordB[i] >> ordC[i] >> ordD[i];\n    \n    auto elapsed = [&]() {\n        return chrono::duration<double>(chrono::steady_clock::now() - st).count();\n    };\n    \n    vector<pair<int,int>> byDist(N);\n    for (int i = 0; i < N; i++) {\n        byDist[i] = {dist(CX, CY, ordA[i], ordB[i]) + dist(CX, CY, ordC[i], ordD[i]), i};\n    }\n    sort(byDist.begin(), byDist.end());\n    \n    vector<int> sel(M), unsel(N-M);\n    for (int i = 0; i < M; i++) sel[i] = byDist[i].second;\n    for (int i = 0; i < N-M; i++) unsel[i] = byDist[M+i].second;\n    \n    vector<pair<int,bool>> ev, bestEv;\n    int cost = buildRoute(sel, ev);\n    int bestCost = cost;\n    vector<int> bestSel = sel;\n    bestEv = ev;\n    \n    double temp = 3000.0;\n    \n    while (elapsed() < 1.8) {\n        int si = rng() % M;\n        int ui = rng() % (N-M);\n        swap(sel[si], unsel[ui]);\n        \n        int nc = buildRoute(sel, ev);\n        int delta = nc - cost;\n        \n        if (delta < 0 || (rng() % 10000) < 10000 * exp(-delta / temp)) {\n            cost = nc;\n            if (nc < bestCost) {\n                bestCost = nc;\n                bestSel = sel;\n                bestEv = ev;\n            }\n        } else {\n            swap(sel[si], unsel[ui]);\n        }\n        temp *= 0.99995;\n    }\n    \n    // Improved 2-opt: complete full passes, don't break early\n    bool improved = true;\n    while (improved && elapsed() < 1.95) {\n        improved = false;\n        for (int i = 0; i < 2*M - 1; i++) {\n            for (int j = i + 1; j < 2*M; j++) {\n                if (elapsed() > 1.95) break;\n                if (bestEv[i].first == bestEv[j].first) continue;\n                if (validSwap(bestEv, i, j)) {\n                    int nc = calcCost(bestEv);\n                    if (nc < bestCost) {\n                        bestCost = nc;\n                        improved = true;\n                    } else {\n                        swap(bestEv[i], bestEv[j]);\n                    }\n                }\n            }\n        }\n    }\n    \n    cout << M;\n    for (int x : bestSel) cout << \" \" << (x+1);\n    cout << \"\\n\" << (2*M+2) << \" \" << CX << \" \" << CY;\n    for (auto& [idx, isDel] : bestEv) {\n        if (isDel) cout << \" \" << ordC[idx] << \" \" << ordD[idx];\n        else cout << \" \" << ordA[idx] << \" \" << ordB[idx];\n    }\n    cout << \" \" << CX << \" \" << CY << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass UnionFind {\n    vector<int> parent, rank_;\npublic:\n    UnionFind(int n) : parent(n), rank_(n, 0) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    int find(int x) {\n        if (parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    bool unite(int x, int y) {\n        int px = find(x), py = find(y);\n        if (px == py) return false;\n        if (rank_[px] < rank_[py]) swap(px, py);\n        parent[py] = px;\n        if (rank_[px] == rank_[py]) rank_[px]++;\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 400, M = 1995;\n    \n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<int> u(M), v(M), d(M);\n    for (int i = 0; i < M; i++) {\n        cin >> u[i] >> v[i];\n        double dx = x[u[i]] - x[v[i]];\n        double dy = y[u[i]] - y[v[i]];\n        d[i] = (int)round(sqrt(dx * dx + dy * dy));\n    }\n    \n    UnionFind uf(N);\n    int components = N;\n    \n    for (int i = 0; i < M; i++) {\n        int l;\n        cin >> l;\n        \n        int pu = uf.find(u[i]);\n        int pv = uf.find(v[i]);\n        \n        bool already_connected = (pu == pv);\n        double ratio = (double)l / d[i];\n        \n        bool adopt = false;\n        \n        if (!already_connected) {\n            // Always accept excellent deals\n            if (ratio <= 1.5) {\n                adopt = true;\n            }\n            else {\n                int useful_remaining = 0;\n                int same_pair_remaining = 0;\n                \n                for (int j = i + 1; j < M; j++) {\n                    int uj = uf.find(u[j]);\n                    int vj = uf.find(v[j]);\n                    if (uj != vj) {\n                        useful_remaining++;\n                        if ((uj == pu && vj == pv) || (uj == pv && vj == pu)) {\n                            same_pair_remaining++;\n                        }\n                    }\n                }\n                \n                int needed = components - 1;\n                \n                if (same_pair_remaining == 0) {\n                    adopt = true;\n                }\n                else if (useful_remaining < needed * 2) {\n                    adopt = true;\n                }\n                else {\n                    // Expected minimum of (k+1) samples from [1,3] is 1 + 2/(k+2)\n                    double k = same_pair_remaining;\n                    double expected_min = 1.0 + 2.0 / (k + 2.0);\n                    double threshold = expected_min + 0.28;\n                    \n                    if (ratio <= threshold) {\n                        adopt = true;\n                    }\n                }\n            }\n        }\n        \n        if (adopt) {\n            uf.unite(u[i], v[i]);\n            components--;\n        }\n        \n        cout << (adopt ? 1 : 0) << \"\\n\" << flush;\n    }\n    \n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<array<int,3>> pets;\nvector<array<int,2>> humans;\nbool blocked[32][32];\n\nint dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};\nchar wc[] = {'u', 'd', 'l', 'r'}, mc[] = {'U', 'D', 'L', 'R'};\n\nbool pet_at(int x, int y) {\n    for (auto& p : pets) if (p[0] == x && p[1] == y) return true;\n    return false;\n}\n\nbool pet_adjacent(int x, int y) {\n    for (int d = 0; d < 4; d++) if (pet_at(x+dx[d], y+dy[d])) return true;\n    return pet_at(x, y);\n}\n\nbool can_place(int x, int y) {\n    if (x < 1 || x > 30 || y < 1 || y > 30 || blocked[x][y]) return false;\n    for (auto& h : humans) if (h[0] == x && h[1] == y) return false;\n    return !pet_adjacent(x, y);\n}\n\nbool passable(int x, int y) {\n    return x >= 1 && x <= 30 && y >= 1 && y <= 30 && !blocked[x][y];\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N; pets.resize(N);\n    for (int i = 0; i < N; i++) cin >> pets[i][0] >> pets[i][1] >> pets[i][2];\n    cin >> M; humans.resize(M);\n    for (int i = 0; i < M; i++) cin >> humans[i][0] >> humans[i][1];\n    \n    set<pair<int,int>> target;\n    for (int i = 1; i <= 30; i++) {\n        for (int c : {7, 14, 21, 28}) {\n            target.insert({i, c});\n            target.insert({c, i});\n        }\n    }\n    \n    for (int turn = 0; turn < 300; turn++) {\n        string action(M, '.');\n        set<pair<int,int>> will_block;\n        \n        for (int i = 0; i < M; i++) {\n            int hx = humans[i][0], hy = humans[i][1];\n            \n            // Try to build a target wall only\n            int bestd = -1;\n            for (int d = 0; d < 4; d++) {\n                int nx = hx + dx[d], ny = hy + dy[d];\n                if (target.count({nx, ny}) && can_place(nx, ny) && !will_block.count({nx, ny})) {\n                    bestd = d;\n                    break;\n                }\n            }\n            \n            if (bestd >= 0) {\n                action[i] = wc[bestd];\n                will_block.insert({hx + dx[bestd], hy + dy[bestd]});\n            } else {\n                // Check if we're adjacent to an unbuilt target (might be blocked by pet)\n                bool near_unbuilt_target = false;\n                for (int d = 0; d < 4; d++) {\n                    int nx = hx + dx[d], ny = hy + dy[d];\n                    if (nx >= 1 && nx <= 30 && ny >= 1 && ny <= 30 &&\n                        target.count({nx, ny}) && !blocked[nx][ny]) {\n                        near_unbuilt_target = true;\n                        break;\n                    }\n                }\n                \n                if (near_unbuilt_target) {\n                    // Wait for opportunity to build\n                    action[i] = '.';\n                } else {\n                    // Move toward closest unbuilt target\n                    int minD = INT_MAX;\n                    int moveD = -1;\n                    \n                    for (auto& [tx, ty] : target) {\n                        if (blocked[tx][ty]) continue;\n                        int dist = abs(hx-tx) + abs(hy-ty);\n                        if (dist > 0 && dist < minD) {\n                            minD = dist;\n                        }\n                    }\n                    \n                    for (int d = 0; d < 4; d++) {\n                        int nx = hx + dx[d], ny = hy + dy[d];\n                        if (!passable(nx, ny) || pet_at(nx, ny) || will_block.count({nx, ny})) continue;\n                        \n                        for (auto& [tx, ty] : target) {\n                            if (blocked[tx][ty]) continue;\n                            int newDist = abs(nx-tx) + abs(ny-ty);\n                            if (newDist < minD) {\n                                minD = newDist;\n                                moveD = d;\n                            }\n                        }\n                    }\n                    if (moveD >= 0) action[i] = mc[moveD];\n                }\n            }\n        }\n        \n        cout << action << \"\\n\" << flush;\n        \n        for (int i = 0; i < M; i++) {\n            char a = action[i];\n            for (int d = 0; d < 4; d++) {\n                if (a == wc[d]) blocked[humans[i][0]+dx[d]][humans[i][1]+dy[d]] = true;\n                if (a == mc[d]) { humans[i][0] += dx[d]; humans[i][1] += dy[d]; }\n            }\n        }\n        \n        for (int i = 0; i < N; i++) {\n            string s; cin >> s;\n            for (char c : s) {\n                if (c == 'U') pets[i][0]--;\n                else if (c == 'D') pets[i][0]++;\n                else if (c == 'L') pets[i][1]--;\n                else if (c == 'R') pets[i][1]++;\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N = 20;\nint si, sj, ti, tj;\ndouble p;\nbool hwall[20][19];\nbool vwall[19][20];\n\nbool canMove(int i, int j, char dir) {\n    if (dir == 'U') return i > 0 && !vwall[i-1][j];\n    if (dir == 'D') return i < 19 && !vwall[i][j];\n    if (dir == 'L') return j > 0 && !hwall[i][j-1];\n    if (dir == 'R') return j < 19 && !hwall[i][j];\n    return false;\n}\n\npair<int,int> doMove(int i, int j, char dir) {\n    if (!canMove(i, j, dir)) return {i, j};\n    if (dir == 'U') return {i-1, j};\n    if (dir == 'D') return {i+1, j};\n    if (dir == 'L') return {i, j-1};\n    if (dir == 'R') return {i, j+1};\n    return {i, j};\n}\n\ndouble prob[20][20], newProb[20][20];\n\ndouble evaluate(const string& s) {\n    if (s.empty() || s.size() > 200) return -1;\n    memset(prob, 0, sizeof(prob));\n    prob[si][sj] = 1.0;\n    double expectedScore = 0;\n    for (int t = 1; t <= (int)s.size(); t++) {\n        char dir = s[t-1];\n        memset(newProb, 0, sizeof(newProb));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (prob[i][j] < 1e-15) continue;\n                auto [ni, nj] = doMove(i, j, dir);\n                if (ni == ti && nj == tj) {\n                    expectedScore += (1-p) * prob[i][j] * (401 - t);\n                } else {\n                    newProb[ni][nj] += (1-p) * prob[i][j];\n                }\n                newProb[i][j] += p * prob[i][j];\n            }\n        }\n        memcpy(prob, newProb, sizeof(prob));\n    }\n    return expectedScore;\n}\n\nstring bfsWithOrder(vector<char>& order) {\n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1,-1}));\n    vector<vector<char>> fromDir(N, vector<char>(N, ' '));\n    queue<pair<int,int>> q;\n    q.push({si, sj});\n    dist[si][sj] = 0;\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        for (char d : order) {\n            auto [ni, nj] = doMove(i, j, d);\n            if (ni == i && nj == j) continue;\n            if (dist[ni][nj] == -1) {\n                dist[ni][nj] = dist[i][j] + 1;\n                parent[ni][nj] = {i, j};\n                fromDir[ni][nj] = d;\n                q.push({ni, nj});\n            }\n        }\n    }\n    string path;\n    int ci = ti, cj = tj;\n    while (ci != si || cj != sj) {\n        path += fromDir[ci][cj];\n        auto [pi, pj] = parent[ci][cj];\n        ci = pi; cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nmt19937 rng(42);\nstring best;\ndouble bestScore = -1;\nconst char dirs[] = {'U', 'D', 'L', 'R'};\nchrono::steady_clock::time_point startTime;\n\nbool timeUp(int ms) {\n    return chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() > ms;\n}\n\nvoid updateBest(const string& s, double score) {\n    if (score > bestScore) { bestScore = score; best = s; }\n}\n\nvoid localSearch(string& cur, double& curScore, int maxMs) {\n    while (!timeUp(maxMs)) {\n        bool improved = false;\n        \n        for (size_t i = 0; i < cur.size() && !improved; i++) {\n            string trial = cur.substr(0, i) + cur.substr(i + 1);\n            if (!trial.empty()) {\n                double score = evaluate(trial);\n                if (score > curScore) { cur = trial; curScore = score; improved = true; updateBest(cur, curScore); }\n            }\n        }\n        \n        for (size_t i = 0; i < cur.size() && !improved; i++) {\n            for (char d : dirs) {\n                if (d == cur[i]) continue;\n                string trial = cur; trial[i] = d;\n                double score = evaluate(trial);\n                if (score > curScore) { cur = trial; curScore = score; improved = true; updateBest(cur, curScore); break; }\n            }\n        }\n        \n        if (cur.size() < 200 && !improved) {\n            for (size_t i = 0; i <= cur.size() && !improved; i++) {\n                for (char d : dirs) {\n                    string trial = cur.substr(0, i) + d + cur.substr(i);\n                    double score = evaluate(trial);\n                    if (score > curScore) { cur = trial; curScore = score; improved = true; updateBest(cur, curScore); break; }\n                }\n            }\n        }\n        \n        if (cur.size() < 200 && !improved) {\n            for (size_t i = 0; i < cur.size() && !improved; i++) {\n                string trial = cur.substr(0, i+1) + cur[i] + cur.substr(i+1);\n                double score = evaluate(trial);\n                if (score > curScore) { cur = trial; curScore = score; improved = true; updateBest(cur, curScore); }\n            }\n        }\n        \n        for (int len = 2; len <= 5 && !improved; len++) {\n            for (size_t i = 0; i + len <= cur.size() && !improved; i++) {\n                string trial = cur.substr(0, i) + cur.substr(i + len);\n                if (!trial.empty()) {\n                    double score = evaluate(trial);\n                    if (score > curScore) { cur = trial; curScore = score; improved = true; updateBest(cur, curScore); }\n                }\n            }\n        }\n        \n        if (cur.size() < 195 && !improved) {\n            for (int len = 2; len <= 5 && !improved; len++) {\n                for (size_t i = 0; i + len <= cur.size() && !improved; i++) {\n                    string trial = cur.substr(0, i + len) + cur.substr(i, len) + cur.substr(i + len);\n                    if (trial.size() <= 200) {\n                        double score = evaluate(trial);\n                        if (score > curScore) { cur = trial; curScore = score; improved = true; updateBest(cur, curScore); }\n                    }\n                }\n            }\n        }\n        \n        if (!improved) break;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    startTime = chrono::steady_clock::now();\n    \n    cin >> si >> sj >> ti >> tj >> p;\n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < 19; j++) hwall[i][j] = (s[j] == '1');\n    }\n    for (int i = 0; i < 19; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) vwall[i][j] = (s[j] == '1');\n    }\n    \n    vector<char> order = {'U', 'D', 'L', 'R'};\n    set<string> pathSet;\n    for (int iter = 0; iter < 100; iter++) {\n        shuffle(order.begin(), order.end(), rng);\n        pathSet.insert(bfsWithOrder(order));\n    }\n    vector<string> paths(pathSet.begin(), pathSet.end());\n    sort(paths.begin(), paths.end(), [](const string& a, const string& b) { return a.size() < b.size(); });\n    \n    for (const string& path : paths) {\n        if (timeUp(700)) break;\n        int L = path.size();\n        \n        auto tryAdd = [&](const string& s) {\n            if (s.size() > 200 || s.empty()) return;\n            double score = evaluate(s);\n            updateBest(s, score);\n        };\n        \n        for (int rep = 1; rep * L <= 200; rep++) {\n            string r; for (char c : path) for (int i = 0; i < rep; i++) r += c;\n            tryAdd(r);\n        }\n        for (int rep = 1; rep * L <= 200; rep++) {\n            string r; for (int i = 0; i < rep; i++) r += path;\n            tryAdd(r);\n        }\n        for (int bonus = 1; bonus <= 12; bonus++) {\n            for (int base = 1; base * L <= 200; base++) {\n                string r; int ci = si, cj = sj;\n                for (char c : path) {\n                    auto [ni, nj] = doMove(ci, cj, c);\n                    int reps = !canMove(ni, nj, c) ? base + bonus : base;\n                    for (int i = 0; i < reps && r.size() < 200; i++) r += c;\n                    ci = ni; cj = nj;\n                }\n                tryAdd(r);\n            }\n        }\n        for (int pr = 1; pr <= 12; pr++) {\n            for (int mr = 1; mr * L * pr <= 200 && mr <= 12; mr++) {\n                string r;\n                for (int i = 0; i < pr; i++) for (char c : path) for (int j = 0; j < mr; j++) r += c;\n                tryAdd(r);\n            }\n        }\n        for (int sr = 1; sr <= 6; sr++) {\n            for (int er = sr; er <= 15; er++) {\n                string r;\n                for (int i = 0; i < L && r.size() < 200; i++) {\n                    int rep = sr + (er - sr) * i / max(1, L - 1);\n                    for (int j = 0; j < rep && r.size() < 200; j++) r += path[i];\n                }\n                tryAdd(r);\n            }\n        }\n    }\n    \n    string cur = best;\n    double curScore = bestScore;\n    localSearch(cur, curScore, 1400);\n    \n    while (!timeUp(1850)) {\n        cur = best;\n        curScore = bestScore;\n        \n        int ops = 1 + rng() % 4;\n        for (int i = 0; i < ops && cur.size() > 1; i++) {\n            int t = rng() % 5;\n            if (t == 0 && cur.size() > 1) cur.erase(rng() % cur.size(), 1);\n            else if (t == 1 && cur.size() < 200) cur.insert(rng() % (cur.size() + 1), 1, dirs[rng() % 4]);\n            else if (t == 2) cur[rng() % cur.size()] = dirs[rng() % 4];\n            else if (t == 3 && cur.size() < 200) { int pos = rng() % cur.size(); cur.insert(pos, 1, cur[pos]); }\n            else if (t == 4 && cur.size() >= 3) { int pos = rng() % (cur.size() - 2); cur.erase(pos, 2); }\n        }\n        \n        if (!cur.empty() && cur.size() <= 200) {\n            curScore = evaluate(cur);\n            if (curScore > bestScore * 0.95) localSearch(cur, curScore, 1850);\n        }\n    }\n    \n    cout << best << endl;\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nint tiles[N][N];\nint rotation[N][N];\n\nconst int di[] = {0, -1, 0, 1};\nconst int dj[] = {-1, 0, 1, 0};\n\nconst int to_arr[8][4] = {\n    {1, 0, -1, -1}, {3, -1, -1, 0}, {-1, -1, 3, 2}, {-1, 2, 1, -1},\n    {1, 0, 3, 2}, {3, 2, 1, 0}, {2, -1, 0, -1}, {-1, 3, -1, 1},\n};\n\ninline int getState(int i, int j) {\n    int t = tiles[i][j], r = rotation[i][j];\n    if (t < 4) return (t + r) % 4;\n    if (t < 6) return 4 + (t - 4 + r) % 2;\n    return 6 + (t - 6 + r) % 2;\n}\n\nint traceLoop(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd, length = 0;\n    do {\n        int state = getState(i, j);\n        int d2 = to_arr[state][d];\n        if (d2 == -1) return 0;\n        length++;\n        if (length > 4 * N * N) return 0;\n        i += di[d2]; j += dj[d2];\n        if ((unsigned)i >= N || (unsigned)j >= N) return 0;\n        d = (d2 + 2) % 4;\n    } while (i != si || j != sj || d != sd);\n    return length;\n}\n\npair<int, int> computeTopTwoLoops() {\n    static bool visited[N][N][4];\n    memset(visited, 0, sizeof(visited));\n    int top1 = 0, top2 = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int state = getState(i, j);\n            for (int d = 0; d < 4; d++) {\n                if (to_arr[state][d] == -1 || visited[i][j][d]) continue;\n                int len = traceLoop(i, j, d);\n                if (len > 0) {\n                    if (len > top1) { top2 = top1; top1 = len; }\n                    else if (len > top2) { top2 = len; }\n                    int ci = i, cj = j, cd = d;\n                    do {\n                        visited[ci][cj][cd] = true;\n                        int st = getState(ci, cj);\n                        int d2 = to_arr[st][cd];\n                        ci += di[d2]; cj += dj[d2];\n                        cd = (d2 + 2) % 4;\n                    } while (ci != i || cj != j || cd != d);\n                }\n            }\n        }\n    }\n    return {top1, top2};\n}\n\nint best_rotation[N][N];\nlong long best_score;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = s[j] - '0';\n            rotation[i][j] = 0;\n        }\n    }\n    \n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    \n    auto [l1, l2] = computeTopTwoLoops();\n    best_score = (long long)l1 * l2;\n    memcpy(best_rotation, rotation, sizeof(rotation));\n    long long current_score = best_score;\n    \n    const double TIME_LIMIT = 1.9;\n    \n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start_time).count();\n        if (elapsed > TIME_LIMIT) break;\n        \n        double T = 1000.0 * pow(0.0001, elapsed / TIME_LIMIT);\n        \n        int i = rng() % N, j = rng() % N;\n        int old_rot = rotation[i][j];\n        int new_rot = (old_rot + 1 + rng() % 3) % 4;\n        \n        rotation[i][j] = new_rot;\n        auto [nl1, nl2] = computeTopTwoLoops();\n        long long new_score = (long long)nl1 * nl2;\n        \n        double delta = (double)(new_score - current_score);\n        if (delta >= 0 || uniform_real_distribution<double>(0, 1)(rng) < exp(delta / T)) {\n            current_score = new_score;\n            if (new_score > best_score) {\n                best_score = new_score;\n                memcpy(best_rotation, rotation, sizeof(rotation));\n            }\n        } else {\n            rotation[i][j] = old_rot;\n        }\n    }\n    \n    string result;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            result += ('0' + best_rotation[i][j]);\n    cout << result << endl;\n    \n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dc_char[] = {'U', 'D', 'L', 'R'};\n\nint hexChar(char c) {\n    return (c >= '0' && c <= '9') ? c - '0' : c - 'a' + 10;\n}\n\nint calcScore(const vector<vector<int>>& board) {\n    vector<vector<int>> adj(N * N);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (board[i][j] == 0) continue;\n            if (i + 1 < N && board[i+1][j] != 0 && (board[i][j] & 8) && (board[i+1][j] & 2)) {\n                adj[i*N+j].push_back((i+1)*N+j);\n                adj[(i+1)*N+j].push_back(i*N+j);\n            }\n            if (j + 1 < N && board[i][j+1] != 0 && (board[i][j] & 4) && (board[i][j+1] & 1)) {\n                adj[i*N+j].push_back(i*N+j+1);\n                adj[i*N+j+1].push_back(i*N+j);\n            }\n        }\n    }\n    vector<bool> vis(N * N, false);\n    int maxTree = 0;\n    for (int s = 0; s < N * N; s++) {\n        if (vis[s] || board[s/N][s%N] == 0) continue;\n        int cnt = 0, edges = 0;\n        queue<int> q; q.push(s); vis[s] = true;\n        while (!q.empty()) {\n            int u = q.front(); q.pop(); cnt++;\n            edges += adj[u].size();\n            for (int v : adj[u]) if (!vis[v]) { vis[v] = true; q.push(v); }\n        }\n        if (edges / 2 == cnt - 1) maxTree = max(maxTree, cnt);\n    }\n    return maxTree;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    int er, ec;\n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) {\n            board[i][j] = hexChar(s[j]);\n            if (board[i][j] == 0) { er = i; ec = j; }\n        }\n    }\n    \n    string best, cur;\n    int bestScore = calcScore(board), curScore = bestScore;\n    auto bestBoard = board; int bestEr = er, bestEc = ec;\n    \n    mt19937 rng(42);\n    auto start = chrono::steady_clock::now();\n    \n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count() < 2800) {\n        if (cur.size() >= (size_t)T || bestScore >= N * N - 1) break;\n        \n        vector<int> valid;\n        for (int d = 0; d < 4; d++) {\n            int nr = er + dr[d], nc = ec + dc[d];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N) valid.push_back(d);\n        }\n        int d = valid[rng() % valid.size()];\n        int nr = er + dr[d], nc = ec + dc[d];\n        \n        swap(board[er][ec], board[nr][nc]);\n        cur += dc_char[d];\n        int newScore = calcScore(board);\n        \n        double temp = 1.0 - (double)cur.size() / T;\n        bool accept = newScore > curScore || (rng() % 1000 < 100 * temp);\n        \n        if (accept) {\n            er = nr; ec = nc; curScore = newScore;\n            if (curScore > bestScore || (curScore == bestScore && cur.size() < best.size())) {\n                bestScore = curScore; best = cur;\n                bestBoard = board; bestEr = er; bestEc = ec;\n            }\n        } else {\n            cur.pop_back();\n            swap(board[er][ec], board[nr][nc]);\n        }\n        \n        if (cur.size() > T / 2 && rng() % 100 < 5) {\n            board = bestBoard; er = bestEr; ec = bestEc;\n            cur = best; curScore = bestScore;\n        }\n    }\n    \n    cout << best << endl;\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nint N, K;\nvector<int> a(10);\nvector<pair<ll, ll>> berries;\nvector<array<ll, 4>> cuts;\nvector<vector<int>> sides;\n\ninline int side(ll x1, ll y1, ll x2, ll y2, ll px, ll py) {\n    __int128 cross = (__int128)(x2 - x1) * (py - y1) - (__int128)(y2 - y1) * (px - x1);\n    if (cross > 0) return 1;\n    if (cross < 0) return -1;\n    return 0;\n}\n\nint calcScore() {\n    int numCuts = cuts.size();\n    unordered_map<uint64_t, int> pieceCount;\n    pieceCount.reserve(N);\n    \n    for (int j = 0; j < N; j++) {\n        bool onLine = false;\n        uint64_t h = 0;\n        for (int i = 0; i < numCuts; i++) {\n            if (sides[i][j] == 0) { onLine = true; break; }\n            h = h * 3ULL + (uint64_t)(sides[i][j] + 1);\n        }\n        if (!onLine) pieceCount[h]++;\n    }\n    \n    vector<int> b(11, 0);\n    for (auto& [sig, cnt] : pieceCount) {\n        if (cnt >= 1 && cnt <= 10) b[cnt]++;\n    }\n    \n    int total = 0;\n    for (int d = 1; d <= 10; d++) total += min(a[d-1], b[d]);\n    return total;\n}\n\nvoid updateSides(int idx) {\n    while ((int)sides.size() <= idx) sides.push_back(vector<int>(N));\n    for (int j = 0; j < N; j++) {\n        sides[idx][j] = side(cuts[idx][0], cuts[idx][1], cuts[idx][2], cuts[idx][3],\n                            berries[j].first, berries[j].second);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> K;\n    for (int i = 0; i < 10; i++) cin >> a[i];\n    \n    berries.resize(N);\n    for (int i = 0; i < N; i++) cin >> berries[i].first >> berries[i].second;\n    \n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    auto randLine = [&]() -> array<ll, 4> {\n        ll px = (ll)(rng() % 20001) - 10000;\n        ll py = (ll)(rng() % 20001) - 10000;\n        ll qx = (ll)(rng() % 20001) - 10000;\n        ll qy = (ll)(rng() % 20001) - 10000;\n        while (px == qx && py == qy) { qx = (ll)(rng() % 20001) - 10000; qy = (ll)(rng() % 20001) - 10000; }\n        return {px, py, qx, qy};\n    };\n    \n    auto perpBisector = [&](int i, int j) -> array<ll, 4> {\n        if (i == j) return randLine();\n        ll dx = berries[j].first - berries[i].first;\n        ll dy = berries[j].second - berries[i].second;\n        ll mx = berries[i].first + berries[j].first;\n        ll my = berries[i].second + berries[j].second;\n        return {mx - dy * 1000, my + dx * 1000, mx + dy * 1000, my - dx * 1000};\n    };\n    \n    auto radialLine = [&](double angle) -> array<ll, 4> {\n        ll px = (ll)(cos(angle) * 15000);\n        ll py = (ll)(sin(angle) * 15000);\n        if (px == 0 && py == 0) px = 1;\n        return {px, py, -px, -py};\n    };\n    \n    auto genLine = [&]() -> array<ll, 4> {\n        int strat = rng() % 5;\n        if (strat == 0) return randLine();\n        else if (strat <= 2) return perpBisector(rng() % N, rng() % N);\n        else if (strat == 3) return radialLine((double)(rng() % 10000) / 10000.0 * M_PI * 2);\n        else {\n            int b1 = rng() % N, b2 = rng() % N;\n            if (b1 != b2) return {berries[b1].first, berries[b1].second, berries[b2].first, berries[b2].second};\n            return randLine();\n        }\n    };\n    \n    int bestScore = 0;\n    vector<array<ll, 4>> bestCuts;\n    \n    auto start = chrono::steady_clock::now();\n    \n    for (int restart = 0; ; restart++) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration_cast<chrono::milliseconds>(now - start).count();\n        if (elapsed > 2850) break;\n        \n        cuts.clear();\n        sides.clear();\n        int numCuts = 25 + rng() % 35;\n        \n        for (int i = 0; i < numCuts; i++) {\n            cuts.push_back(genLine());\n            updateSides(i);\n        }\n        \n        int curScore = calcScore();\n        if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n        \n        for (int iter = 0; ; iter++) {\n            now = chrono::steady_clock::now();\n            elapsed = chrono::duration_cast<chrono::milliseconds>(now - start).count();\n            if (elapsed > 2850) break;\n            \n            double progress = elapsed / 2850.0;\n            double temp = 3.0 * (1.0 - progress) + 0.1;\n            int moveType = rng() % 100;\n            \n            if (moveType < 75 && !cuts.empty()) {\n                int idx = rng() % cuts.size();\n                auto oldCut = cuts[idx];\n                auto oldSide = sides[idx];\n                \n                cuts[idx] = genLine();\n                updateSides(idx);\n                \n                int newScore = calcScore();\n                if (newScore > curScore || (double)(rng() % 1000000) / 1000000.0 < exp((newScore - curScore) / temp)) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else {\n                    cuts[idx] = oldCut;\n                    sides[idx] = oldSide;\n                }\n            } else if (moveType < 90 && cuts.size() < (size_t)min(K, 80)) {\n                cuts.push_back(genLine());\n                updateSides(cuts.size() - 1);\n                \n                int newScore = calcScore();\n                if (newScore >= curScore) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else {\n                    cuts.pop_back();\n                    sides.pop_back();\n                }\n            } else if (cuts.size() > 10) {\n                int idx = rng() % cuts.size();\n                auto oldCut = cuts[idx];\n                auto oldSide = sides[idx];\n                cuts.erase(cuts.begin() + idx);\n                sides.erase(sides.begin() + idx);\n                \n                int newScore = calcScore();\n                if (newScore >= curScore) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else {\n                    cuts.insert(cuts.begin() + idx, oldCut);\n                    sides.insert(sides.begin() + idx, oldSide);\n                }\n            }\n        }\n    }\n    \n    cout << bestCuts.size() << \"\\n\";\n    for (auto& c : bestCuts) cout << c[0] << \" \" << c[1] << \" \" << c[2] << \" \" << c[3] << \"\\n\";\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, c;\nset<pair<int,int>> dots;\nset<tuple<int,int,int,int>> usedSegs;\nvector<array<int, 8>> ops;\n\nbool inGrid(int x, int y) { return x >= 0 && x < N && y >= 0 && y < N; }\nlong long wt(int x, int y) { return (long long)(x-c)*(x-c) + (long long)(y-c)*(y-c) + 1; }\n\nvoid addSeg(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g == 0) return;\n    dx /= g; dy /= g;\n    for (int i = 0; i < g; i++) {\n        int a = x1+i*dx, b = y1+i*dy, e = a+dx, f = b+dy;\n        if (a > e || (a == e && b > f)) { swap(a,e); swap(b,f); }\n        usedSegs.insert({a,b,e,f});\n    }\n}\n\nbool segUsed(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g == 0) return true;\n    dx /= g; dy /= g;\n    for (int i = 0; i < g; i++) {\n        int a = x1+i*dx, b = y1+i*dy, e = a+dx, f = b+dy;\n        if (a > e || (a == e && b > f)) { swap(a,e); swap(b,f); }\n        if (usedSegs.count({a,b,e,f})) return true;\n    }\n    return false;\n}\n\nbool dotOnSeg(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g <= 1) return false;\n    dx /= g; dy /= g;\n    for (int i = 1; i < g; i++)\n        if (dots.count({x1+i*dx, y1+i*dy})) return true;\n    return false;\n}\n\nbool isValidRect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    int v1x = x2-x1, v1y = y2-y1;\n    int v2x = x3-x2, v2y = y3-y2;\n    if (v1x == 0 && v1y == 0) return false;\n    if (v2x == 0 && v2y == 0) return false;\n    if (v1x*v2x + v1y*v2y != 0) return false;\n    bool axis1 = (v1x == 0 || v1y == 0);\n    bool diag1 = (abs(v1x) == abs(v1y));\n    if (!axis1 && !diag1) return false;\n    bool axis2 = (v2x == 0 || v2y == 0);\n    bool diag2 = (abs(v2x) == abs(v2y));\n    if (!axis2 && !diag2) return false;\n    if (x4 != x1 + v2x || y4 != y1 + v2y) return false;\n    return true;\n}\n\nbool tryAdd(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (!inGrid(x1,y1) || dots.count({x1,y1})) return false;\n    if (!dots.count({x2,y2}) || !dots.count({x3,y3}) || !dots.count({x4,y4})) return false;\n    set<pair<int,int>> pts = {{x1,y1},{x2,y2},{x3,y3},{x4,y4}};\n    if (pts.size() != 4) return false;\n    if (!isValidRect(x1,y1,x2,y2,x3,y3,x4,y4)) return false;\n    if (dotOnSeg(x1,y1,x2,y2) || dotOnSeg(x2,y2,x3,y3) || \n        dotOnSeg(x3,y3,x4,y4) || dotOnSeg(x4,y4,x1,y1)) return false;\n    if (segUsed(x1,y1,x2,y2) || segUsed(x2,y2,x3,y3) || \n        segUsed(x3,y3,x4,y4) || segUsed(x4,y4,x1,y1)) return false;\n    \n    dots.insert({x1,y1});\n    addSeg(x1,y1,x2,y2); addSeg(x2,y2,x3,y3);\n    addSeg(x3,y3,x4,y4); addSeg(x4,y4,x1,y1);\n    ops.push_back({x1,y1,x2,y2,x3,y3,x4,y4});\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    c = (N-1) / 2;\n    for (int i = 0; i < M; i++) { int x, y; cin >> x >> y; dots.insert({x, y}); }\n    \n    auto tstart = chrono::steady_clock::now();\n    mt19937 rng(42);\n    \n    int fails = 0;\n    while (chrono::duration<double>(chrono::steady_clock::now() - tstart).count() < 4.5) {\n        vector<pair<int,int>> dl(dots.begin(), dots.end());\n        shuffle(dl.begin(), dl.end(), rng);\n        int sz = min((int)dl.size(), 100);\n        \n        vector<tuple<long long, array<int,8>>> candidates;\n        \n        for (int i = 0; i < sz; i++) {\n            for (int j = 0; j < sz; j++) {\n                if (i == j) continue;\n                for (int k = 0; k < sz; k++) {\n                    if (k == i || k == j) continue;\n                    auto [ax, ay] = dl[i];\n                    auto [bx, by] = dl[j];\n                    auto [cx, cy] = dl[k];\n                    \n                    // Try: new point D, with corners D-A-B-C (A opposite to C, B opposite to D)\n                    // D = A + C - B\n                    int dx = ax + cx - bx, dy = ay + cy - by;\n                    if (inGrid(dx, dy) && !dots.count({dx, dy})) {\n                        long long w = wt(dx, dy);\n                        candidates.push_back({w, {dx, dy, ax, ay, bx, by, cx, cy}});\n                    }\n                }\n            }\n        }\n        \n        sort(candidates.begin(), candidates.end(), greater<>());\n        \n        bool found = false;\n        for (auto& [w, arr] : candidates) {\n            if (tryAdd(arr[0],arr[1],arr[2],arr[3],arr[4],arr[5],arr[6],arr[7])) {\n                found = true;\n                break;\n            }\n        }\n        \n        if (!found) {\n            if (++fails > 200) break;\n        } else {\n            fails = 0;\n        }\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto& op : ops) {\n        for (int i = 0; i < 8; i++) cout << op[i] << \" \\n\"[i==7];\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 10;\n\nstruct State {\n    int grid[N][N];\n    \n    State() { memset(grid, 0, sizeof(grid)); }\n    \n    int countEmpty() const {\n        int cnt = 0;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] == 0) cnt++;\n        return cnt;\n    }\n    \n    void place(int p, int flavor) {\n        int cnt = 0;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] == 0 && ++cnt == p) { grid[i][j] = flavor; return; }\n    }\n    \n    void tilt(int dir) {\n        if (dir == 0) {\n            for (int j = 0; j < N; j++) {\n                int w = 0;\n                for (int i = 0; i < N; i++) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[w++][j] = v; }\n            }\n        } else if (dir == 1) {\n            for (int j = 0; j < N; j++) {\n                int w = N - 1;\n                for (int i = N - 1; i >= 0; i--) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[w--][j] = v; }\n            }\n        } else if (dir == 2) {\n            for (int i = 0; i < N; i++) {\n                int w = 0;\n                for (int j = 0; j < N; j++) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[i][w++] = v; }\n            }\n        } else {\n            for (int i = 0; i < N; i++) {\n                int w = N - 1;\n                for (int j = N - 1; j >= 0; j--) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[i][w--] = v; }\n            }\n        }\n    }\n    \n    long long calcScore() const {\n        bool vis[N][N] = {};\n        long long sum = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (grid[i][j] && !vis[i][j]) {\n                    int f = grid[i][j], sz = 0;\n                    int stk[100], top = 0;\n                    stk[top++] = i * N + j;\n                    vis[i][j] = true;\n                    while (top > 0) {\n                        int pos = stk[--top];\n                        int x = pos / N, y = pos % N;\n                        sz++;\n                        if (x > 0 && !vis[x-1][y] && grid[x-1][y] == f) { vis[x-1][y] = true; stk[top++] = (x-1)*N+y; }\n                        if (x < N-1 && !vis[x+1][y] && grid[x+1][y] == f) { vis[x+1][y] = true; stk[top++] = (x+1)*N+y; }\n                        if (y > 0 && !vis[x][y-1] && grid[x][y-1] == f) { vis[x][y-1] = true; stk[top++] = x*N+y-1; }\n                        if (y < N-1 && !vis[x][y+1] && grid[x][y+1] == f) { vis[x][y+1] = true; stk[top++] = x*N+y+1; }\n                    }\n                    sum += (long long)sz * sz;\n                }\n            }\n        }\n        return sum;\n    }\n};\n\nmt19937 rng(12345);\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int f[101];\n    for (int t = 1; t <= 100; t++) cin >> f[t];\n    \n    State state;\n    \n    for (int t = 1; t <= 100; t++) {\n        int p; cin >> p;\n        state.place(p, f[t]);\n        \n        int remaining = 100 - t;\n        int depth = min(13, remaining);\n        int numSims;\n        if (t <= 40) numSims = 32;\n        else if (t <= 80) numSims = 28;\n        else numSims = 20;\n        \n        int bestDir = 0;\n        long long bestScore = -1;\n        \n        for (int dir = 0; dir < 4; dir++) {\n            long long totalScore = 0;\n            \n            for (int sim = 0; sim < numSims; sim++) {\n                State s = state;\n                s.tilt(dir);\n                \n                for (int step = 1; step <= depth && t + step <= 100; step++) {\n                    int empty = s.countEmpty();\n                    if (empty == 0) break;\n                    int randPos = (rng() % empty) + 1;\n                    s.place(randPos, f[t + step]);\n                    \n                    int simBest = 0;\n                    long long simBestScore = -1;\n                    for (int d = 0; d < 4; d++) {\n                        State tmp = s;\n                        tmp.tilt(d);\n                        long long sc = tmp.calcScore();\n                        if (sc > simBestScore) { simBestScore = sc; simBest = d; }\n                    }\n                    s.tilt(simBest);\n                }\n                totalScore += s.calcScore();\n            }\n            \n            if (totalScore > bestScore) {\n                bestScore = totalScore;\n                bestDir = dir;\n            }\n        }\n        \n        state.tilt(bestDir);\n        const char dirChar[] = {'F', 'B', 'L', 'R'};\n        cout << dirChar[bestDir] << '\\n' << flush;\n    }\n    \n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\ndouble eps;\n\nvector<int> get_sorted_degrees(const string& s) {\n    vector<int> deg(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 (s[idx++] == '1') {\n                deg[i]++;\n                deg[j]++;\n            }\n        }\n    }\n    sort(deg.begin(), deg.end());\n    return deg;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    cin >> M >> eps;\n    \n    // Better N selection based on theoretical analysis\n    // Need larger N for higher noise to maintain distinguishability\n    double noise_factor = (eps < 0.001) ? 1.0 : 1.0 / max(0.2, 1.0 - 2.0 * eps);\n    \n    // Base N on M and noise\n    if (eps < 0.01) {\n        N = (int)ceil(sqrt(2.0 * M)) + 2;\n    } else if (eps < 0.05) {\n        N = (int)ceil(sqrt(2.5 * M)) + 4;\n    } else if (eps < 0.15) {\n        N = (int)ceil(sqrt(3.0 * M * noise_factor)) + 8;\n    } else if (eps < 0.25) {\n        N = (int)ceil(sqrt(4.0 * M * noise_factor)) + 15;\n    } else if (eps < 0.35) {\n        N = (int)ceil(sqrt(5.0 * M * noise_factor)) + 25;\n    } else {\n        N = (int)ceil(sqrt(6.0 * M * noise_factor)) + 35;\n    }\n    \n    N = max(N, (int)(2.0 * sqrt(M)));\n    N = max(N, 8);\n    N = min(N, 100);\n    \n    cout << N << \"\\n\";\n    \n    int total = N * (N - 1) / 2;\n    \n    vector<string> G(M);\n    vector<vector<double>> expected_deg(M);\n    \n    // Create M graphs with linearly spaced edge counts\n    for (int i = 0; i < M; i++) {\n        string s(total, '0');\n        long long edges = (M > 1) ? ((long long)i * total / (M - 1)) : 0;\n        \n        // Fill edges in a pattern that creates varied degree distribution\n        int idx = 0;\n        int filled = 0;\n        for (int a = 0; a < N && filled < edges; a++) {\n            for (int b = a + 1; b < N && filled < edges; b++) {\n                int pos = a * (2 * N - a - 1) / 2 + (b - a - 1);\n                s[pos] = '1';\n                filled++;\n            }\n        }\n        \n        G[i] = s;\n        \n        // Compute expected degree sequence after noise\n        vector<int> deg = get_sorted_degrees(s);\n        expected_deg[i].resize(N);\n        double transform = 1.0 - 2.0 * eps;\n        double base = (N - 1) * eps;\n        for (int j = 0; j < N; j++) {\n            expected_deg[i][j] = deg[j] * transform + base;\n        }\n        \n        cout << s << \"\\n\";\n    }\n    cout.flush();\n    \n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n        \n        vector<int> deg_h = get_sorted_degrees(H);\n        \n        int best = 0;\n        double best_score = 1e18;\n        \n        for (int i = 0; i < M; i++) {\n            // Weighted L2 distance - weight more heavily at extremes\n            double score = 0;\n            for (int j = 0; j < N; j++) {\n                double diff = deg_h[j] - expected_deg[i][j];\n                // Weight endpoints more (more informative)\n                double weight = 1.0 + 0.5 * (abs(j - N/2.0) / (N/2.0));\n                score += weight * diff * diff;\n            }\n            \n            if (score < best_score) {\n                best_score = score;\n                best = i;\n            }\n        }\n        \n        cout << best << \"\\n\";\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, D, K;\nvector<array<int,3>> edges;\nvector<vector<pair<int,int>>> adj;\nvector<vector<int>> adjEdge;\nmt19937 rng(42);\nconst long long INF = 1e9;\n\nvector<long long> dijkstraMask(int src, const vector<bool>& excl) {\n    vector<long long> dist(N, INF);\n    priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> pq;\n    dist[src] = 0;\n    pq.push({0, src});\n    while (!pq.empty()) {\n        auto [d, u] = pq.top(); pq.pop();\n        if (d > dist[u]) continue;\n        for (size_t i = 0; i < adj[u].size(); i++) {\n            if (excl[adjEdge[u][i]]) continue;\n            auto [v, w] = adj[u][i];\n            if (dist[u] + w < dist[v]) {\n                dist[v] = dist[u] + w;\n                pq.push({dist[v], v});\n            }\n        }\n    }\n    return dist;\n}\n\nint numSamples;\nvector<int> samples;\nvector<vector<long long>> origDist;\nvector<int> assign_;\nvector<int> cnt;\n\ndouble evalDay(int d) {\n    vector<bool> excl(M, false);\n    for (int e = 0; e < M; e++) if (assign_[e] == d) excl[e] = true;\n    double tot = 0;\n    for (int i = 0; i < numSamples; i++) {\n        auto dist = dijkstraMask(samples[i], excl);\n        for (int v = 0; v < N; v++) if (v != samples[i])\n            tot += min(dist[v], INF) - origDist[i][v];\n    }\n    return tot;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    auto start = chrono::steady_clock::now();\n    \n    cin >> N >> M >> D >> K;\n    edges.resize(M); adj.resize(N); adjEdge.resize(N);\n    \n    for (int i = 0; i < M; i++) {\n        int u, v, w; cin >> u >> v >> w; u--; v--;\n        edges[i] = {u, v, w};\n        adj[u].push_back({v, w}); adj[v].push_back({u, w});\n        adjEdge[u].push_back(i); adjEdge[v].push_back(i);\n    }\n    for (int i = 0; i < N; i++) { int x, y; cin >> x >> y; }\n    \n    vector<bool> noEdge(M, false);\n    vector<long long> crit(M);\n    for (int e = 0; e < M; e++) {\n        noEdge[e] = true;\n        auto dist = dijkstraMask(edges[e][0], noEdge);\n        crit[e] = dist[edges[e][1]] - edges[e][2];\n        noEdge[e] = false;\n    }\n    \n    numSamples = min(55, N);\n    samples.resize(N); iota(samples.begin(), samples.end(), 0);\n    shuffle(samples.begin(), samples.end(), rng);\n    samples.resize(numSamples);\n    \n    origDist.resize(numSamples);\n    for (int i = 0; i < numSamples; i++) origDist[i] = dijkstraMask(samples[i], noEdge);\n    \n    double globalBest = 1e18;\n    vector<int> globalBestAssign;\n    \n    for (int restart = 0; restart < 3; restart++) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > 5.0) break;\n        \n        vector<int> order(M); iota(order.begin(), order.end(), 0);\n        if (restart == 0) {\n            sort(order.begin(), order.end(), [&](int a, int b) { return crit[a] > crit[b]; });\n        } else {\n            shuffle(order.begin(), order.end(), rng);\n            sort(order.begin(), order.end(), [&](int a, int b) { return crit[a] > crit[b]; });\n        }\n        \n        assign_.assign(M, 0);\n        cnt.assign(D + 1, 0);\n        vector<set<int>> dayVertices(D + 1);\n        \n        for (int e : order) {\n            int u = edges[e][0], v = edges[e][1];\n            int best = 1, bestScore = INT_MAX;\n            for (int d = 1; d <= D; d++) {\n                if (cnt[d] >= K) continue;\n                int conflict = (dayVertices[d].count(u) ? 1 : 0) + (dayVertices[d].count(v) ? 1 : 0);\n                int score = conflict * 10000 + cnt[d] + (restart > 0 ? (int)(rng() % 100) : 0);\n                if (score < bestScore) { bestScore = score; best = d; }\n            }\n            assign_[e] = best; cnt[best]++;\n            dayVertices[best].insert(u); dayVertices[best].insert(v);\n        }\n        \n        vector<double> dayCost(D + 1);\n        double cur = 0;\n        for (int d = 1; d <= D; d++) { dayCost[d] = evalDay(d); cur += dayCost[d]; }\n        \n        double bestScore = cur;\n        vector<int> bestAssign = assign_;\n        double temp = max(1.0, cur / D / 3);\n        int noImprove = 0;\n        \n        while (true) {\n            now = chrono::steady_clock::now();\n            elapsed = chrono::duration<double>(now - start).count();\n            double timePerRestart = 5.3 / 3;\n            if (elapsed > (restart + 1) * timePerRestart || elapsed > 5.3) break;\n            \n            if (noImprove > 500) {\n                temp = max(temp, bestScore / D / 10);\n                noImprove = 0;\n            }\n            \n            int worstDay = 1;\n            for (int d = 2; d <= D; d++) if (dayCost[d] > dayCost[worstDay]) worstDay = d;\n            \n            int moveType = rng() % 5;\n            \n            if (moveType < 2) {\n                int e1 = rng() % M, e2 = rng() % M;\n                if (assign_[e1] == assign_[e2]) continue;\n                int d1 = assign_[e1], d2 = assign_[e2];\n                \n                swap(assign_[e1], assign_[e2]);\n                double nc1 = evalDay(d1), nc2 = evalDay(d2);\n                double delta = (nc1 + nc2) - (dayCost[d1] + dayCost[d2]);\n                \n                if (delta < 0 || (double)(rng() % 1000000) / 1000000 < exp(-delta / temp)) {\n                    dayCost[d1] = nc1; dayCost[d2] = nc2; cur += delta;\n                    if (cur < bestScore) { bestScore = cur; bestAssign = assign_; noImprove = 0; }\n                    else noImprove++;\n                } else { swap(assign_[e1], assign_[e2]); noImprove++; }\n            } else if (moveType == 2) {\n                int e = rng() % M;\n                int oldD = assign_[e], newD = rng() % D + 1;\n                if (newD == oldD || cnt[newD] >= K) continue;\n                \n                assign_[e] = newD; cnt[oldD]--; cnt[newD]++;\n                double nc1 = evalDay(oldD), nc2 = evalDay(newD);\n                double delta = (nc1 + nc2) - (dayCost[oldD] + dayCost[newD]);\n                \n                if (delta < 0 || (double)(rng() % 1000000) / 1000000 < exp(-delta / temp)) {\n                    dayCost[oldD] = nc1; dayCost[newD] = nc2; cur += delta;\n                    if (cur < bestScore) { bestScore = cur; bestAssign = assign_; noImprove = 0; }\n                    else noImprove++;\n                } else { assign_[e] = oldD; cnt[oldD]++; cnt[newD]--; noImprove++; }\n            } else {\n                vector<int> worstEdges;\n                for (int e = 0; e < M; e++) if (assign_[e] == worstDay) worstEdges.push_back(e);\n                if (worstEdges.empty()) continue;\n                int e = worstEdges[rng() % worstEdges.size()];\n                int newD = rng() % D + 1;\n                if (newD == worstDay || cnt[newD] >= K) continue;\n                \n                assign_[e] = newD; cnt[worstDay]--; cnt[newD]++;\n                double nc1 = evalDay(worstDay), nc2 = evalDay(newD);\n                double delta = (nc1 + nc2) - (dayCost[worstDay] + dayCost[newD]);\n                \n                if (delta < 0 || (double)(rng() % 1000000) / 1000000 < exp(-delta / temp)) {\n                    dayCost[worstDay] = nc1; dayCost[newD] = nc2; cur += delta;\n                    if (cur < bestScore) { bestScore = cur; bestAssign = assign_; noImprove = 0; }\n                    else noImprove++;\n                } else { assign_[e] = worstDay; cnt[worstDay]++; cnt[newD]--; noImprove++; }\n            }\n            temp *= 0.999995;\n            if (temp < 0.1) temp = 0.1;\n        }\n        \n        if (bestScore < globalBest) {\n            globalBest = bestScore;\n            globalBestAssign = bestAssign;\n        }\n    }\n    \n    for (int i = 0; i < M; i++) cout << globalBestAssign[i] << \" \\n\"[i == M-1];\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nint D;\nstring f[2][15], r[2][15];\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D;\n    for (int i = 0; i < 2; i++) {\n        for (int k = 0; k < D; k++) cin >> f[i][k];\n        for (int k = 0; k < D; k++) cin >> r[i][k];\n    }\n    \n    vector<int> b[2];\n    for (int i = 0; i < 2; i++) b[i].assign(D * D * D, 0);\n    \n    auto idx = [&](int x, int y, int z) { return x * D * D + y * D + z; };\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    int n = 0;\n    \n    // Step 1: Create large shared blocks from cells valid in both at same position\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                bool v0 = (f[0][z][x] == '1' && r[0][z][y] == '1');\n                bool v1 = (f[1][z][x] == '1' && r[1][z][y] == '1');\n                if (v0 && v1 && b[0][idx(x,y,z)] == 0) {\n                    n++;\n                    queue<tuple<int,int,int>> q;\n                    q.push({x, y, z});\n                    b[0][idx(x,y,z)] = b[1][idx(x,y,z)] = n;\n                    while (!q.empty()) {\n                        auto [cx, cy, cz] = q.front(); q.pop();\n                        for (int d = 0; d < 6; d++) {\n                            int nx = cx + dx[d], ny = cy + dy[d], nz = cz + dz[d];\n                            if (nx >= 0 && nx < D && ny >= 0 && ny < D && nz >= 0 && nz < D) {\n                                bool nv0 = (f[0][nz][nx] == '1' && r[0][nz][ny] == '1');\n                                bool nv1 = (f[1][nz][nx] == '1' && r[1][nz][ny] == '1');\n                                if (nv0 && nv1 && b[0][idx(nx,ny,nz)] == 0) {\n                                    b[0][idx(nx,ny,nz)] = b[1][idx(nx,ny,nz)] = n;\n                                    q.push({nx, ny, nz});\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    // Step 2: Find remaining constraints for each arrangement\n    vector<tuple<int,int,int>> extra[2];\n    for (int arr = 0; arr < 2; arr++) {\n        set<int> needFront, needRight;\n        for (int z = 0; z < D; z++) {\n            for (int x = 0; x < D; x++) if (f[arr][z][x] == '1') needFront.insert(z * D + x);\n            for (int y = 0; y < D; y++) if (r[arr][z][y] == '1') needRight.insert(z * D + y);\n        }\n        \n        // Remove constraints already satisfied by shared blocks\n        for (int x = 0; x < D; x++) {\n            for (int y = 0; y < D; y++) {\n                for (int z = 0; z < D; z++) {\n                    if (b[arr][idx(x,y,z)] > 0) {\n                        needFront.erase(z * D + x);\n                        needRight.erase(z * D + y);\n                    }\n                }\n            }\n        }\n        \n        // Greedily pick unit blocks for remaining constraints\n        while (!needFront.empty() || !needRight.empty()) {\n            int bestX = -1, bestY = -1, bestZ = -1, bestScore = -1;\n            for (int z = 0; z < D; z++) {\n                for (int x = 0; x < D; x++) {\n                    if (f[arr][z][x] != '1') continue;\n                    for (int y = 0; y < D; y++) {\n                        if (r[arr][z][y] != '1') continue;\n                        int score = 0;\n                        if (needFront.count(z * D + x)) score++;\n                        if (needRight.count(z * D + y)) score++;\n                        if (score > bestScore) {\n                            bestScore = score;\n                            bestX = x; bestY = y; bestZ = z;\n                        }\n                    }\n                }\n            }\n            if (bestScore <= 0) break;\n            extra[arr].push_back({bestX, bestY, bestZ});\n            needFront.erase(bestZ * D + bestX);\n            needRight.erase(bestZ * D + bestY);\n        }\n    }\n    \n    // Step 3: Assign unit blocks (shared between arrangements)\n    int m1 = extra[0].size(), m2 = extra[1].size();\n    int totalExtra = max(m1, m2);\n    \n    for (int i = 0; i < m1; i++) {\n        auto [x, y, z] = extra[0][i];\n        b[0][idx(x,y,z)] = n + 1 + i;\n    }\n    for (int i = 0; i < m2; i++) {\n        auto [x, y, z] = extra[1][i];\n        b[1][idx(x,y,z)] = n + 1 + i;\n    }\n    \n    n += totalExtra;\n    \n    cout << n << \"\\n\";\n    for (int i = 0; i < 2; i++) {\n        for (int j = 0; j < D * D * D; j++) {\n            if (j) cout << \" \";\n            cout << b[i][j];\n        }\n        cout << \"\\n\";\n    }\n    \n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, K;\nvector<pair<int,int>> V, R;\nvector<tuple<int,int,long long>> E;\nvector<vector<pair<int,int>>> adj;\nvector<vector<long long>> distVV;\nvector<vector<int>> parentV;\n\ndouble getDist(int i, int k) {\n    double dx = V[i].first - R[k].first, dy = V[i].second - R[k].second;\n    return sqrt(dx*dx + dy*dy);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    V.resize(N); R.resize(K); E.resize(M); adj.resize(N);\n    \n    for(int i = 0; i < N; i++) cin >> V[i].first >> V[i].second;\n    for(int j = 0; j < M; j++) {\n        int u, v; long long w;\n        cin >> u >> v >> w; u--; v--;\n        E[j] = {u, v, w};\n        adj[u].push_back({v, j});\n        adj[v].push_back({u, j});\n    }\n    for(int k = 0; k < K; k++) cin >> R[k].first >> R[k].second;\n    \n    // Precompute distances\n    vector<vector<double>> distVR(N, vector<double>(K));\n    for(int i = 0; i < N; i++)\n        for(int k = 0; k < K; k++)\n            distVR[i][k] = getDist(i, k);\n    \n    // All-pairs shortest paths\n    distVV.assign(N, vector<long long>(N, LLONG_MAX/2));\n    parentV.assign(N, vector<int>(N, -1));\n    \n    for(int s = 0; s < N; s++) {\n        distVV[s][s] = 0;\n        priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> pq;\n        pq.push({0, s});\n        while(!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if(d > distVV[s][u]) continue;\n            for(auto [v, eid] : adj[u]) {\n                long long w = get<2>(E[eid]);\n                if(distVV[s][u] + w < distVV[s][v]) {\n                    distVV[s][v] = distVV[s][u] + w;\n                    parentV[s][v] = u;\n                    pq.push({distVV[s][v], v});\n                }\n            }\n        }\n    }\n    \n    auto computeP = [&](const vector<int>& asgn) {\n        vector<int> P(N, 0);\n        for(int k = 0; k < K; k++) {\n            int v = asgn[k];\n            P[v] = max(P[v], (int)ceil(distVR[v][k] - 1e-9));\n        }\n        return P;\n    };\n    \n    auto buildTree = [&](const vector<int>& P) {\n        vector<int> B(M, 0);\n        for(int i = 0; i < N; i++) if(P[i] > 0) {\n            int cur = i;\n            while(cur != 0 && parentV[0][cur] != -1) {\n                int p = parentV[0][cur];\n                for(auto& [nxt, eid] : adj[cur]) if(nxt == p) { B[eid] = 1; break; }\n                cur = p;\n            }\n        }\n        return B;\n    };\n    \n    auto getReachable = [&](const vector<int>& B) {\n        vector<int> reach; vector<bool> vis(N, false);\n        queue<int> q; q.push(0); vis[0] = true;\n        while(!q.empty()) {\n            int u = q.front(); q.pop(); reach.push_back(u);\n            for(auto& [v, eid] : adj[u]) if(B[eid] && !vis[v]) { vis[v] = true; q.push(v); }\n        }\n        return reach;\n    };\n    \n    auto calcCost = [&](const vector<int>& P, const vector<int>& B) {\n        long long cost = 0;\n        for(int i = 0; i < N; i++) cost += (long long)P[i] * P[i];\n        for(int j = 0; j < M; j++) if(B[j]) cost += get<2>(E[j]);\n        return cost;\n    };\n    \n    vector<int> bestP(N), bestB(M), bestAsgn(K);\n    long long bestCost = LLONG_MAX;\n    \n    for(double factor : {0.0, 0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0}) {\n        vector<int> asgn(K);\n        for(int k = 0; k < K; k++) {\n            int best = -1; double bestScore = 1e18;\n            for(int i = 0; i < N; i++) {\n                if(distVR[i][k] > 5000) continue;\n                double score = distVR[i][k] * distVR[i][k] + factor * distVV[0][i];\n                if(score < bestScore) { bestScore = score; best = i; }\n            }\n            asgn[k] = best;\n        }\n        \n        for(int phase = 0; phase < 3; phase++) {\n            auto P = computeP(asgn);\n            auto B = buildTree(P);\n            \n            for(int iter = 0; iter < 20; iter++) {\n                auto reach = getReachable(B);\n                bool improved = false;\n                for(int k = 0; k < K; k++) {\n                    double curD = distVR[asgn[k]][k];\n                    for(int v : reach) {\n                        if(distVR[v][k] < curD - 0.01 && distVR[v][k] <= 5000) {\n                            asgn[k] = v; curD = distVR[v][k]; improved = true;\n                        }\n                    }\n                }\n                if(!improved) break;\n                P = computeP(asgn); B = buildTree(P);\n            }\n            \n            // Outlier optimization\n            for(int iter = 0; iter < 10; iter++) {\n                auto reach = getReachable(B);\n                vector<vector<int>> vRes(N);\n                for(int k = 0; k < K; k++) vRes[asgn[k]].push_back(k);\n                \n                bool improved = false;\n                for(int v : reach) {\n                    if(vRes[v].size() <= 1) continue;\n                    int fk = -1; double maxD = 0;\n                    for(int k : vRes[v]) if(distVR[v][k] > maxD) { maxD = distVR[v][k]; fk = k; }\n                    \n                    for(int nv : reach) {\n                        if(nv == v || distVR[nv][fk] > 5000) continue;\n                        double newMaxV = 0;\n                        for(int k : vRes[v]) if(k != fk) newMaxV = max(newMaxV, distVR[v][k]);\n                        double oldMaxNV = 0;\n                        for(int k : vRes[nv]) oldMaxNV = max(oldMaxNV, distVR[nv][k]);\n                        double newMaxNV = max(oldMaxNV, distVR[nv][fk]);\n                        double delta = (newMaxV*newMaxV - maxD*maxD) + (newMaxNV*newMaxNV - oldMaxNV*oldMaxNV);\n                        if(delta < -1) { asgn[fk] = nv; improved = true; break; }\n                    }\n                }\n                if(!improved) break;\n                P = computeP(asgn); B = buildTree(P);\n            }\n        }\n        \n        auto P = computeP(asgn);\n        auto B = buildTree(P);\n        long long cost = calcCost(P, B);\n        if(cost < bestCost) { bestCost = cost; bestP = P; bestB = B; bestAsgn = asgn; }\n    }\n    \n    for(int i = 0; i < N; i++) cout << bestP[i] << \" \\n\"[i==N-1];\n    for(int j = 0; j < M; j++) cout << bestB[j] << \" \\n\"[j==M-1];\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nint b[N][N];\nvector<tuple<int, int, int, int>> ops;\n\nvoid do_swap(int x1, int y1, int x2, int y2) {\n    ops.push_back({x1, y1, x2, y2});\n    swap(b[x1][y1], b[x2][y2]);\n}\n\nvoid sift_down(int x, int y) {\n    while (x < N - 1) {\n        int min_child_y = (b[x + 1][y + 1] < b[x + 1][y]) ? (y + 1) : y;\n        if (b[x][y] > b[x + 1][min_child_y]) {\n            do_swap(x, y, x + 1, min_child_y);\n            x = x + 1;\n            y = min_child_y;\n        } else {\n            break;\n        }\n    }\n}\n\nbool has_violation(int x, int y) {\n    if (x >= N - 1) return false;\n    return b[x][y] > b[x + 1][y] || b[x][y] > b[x + 1][y + 1];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int x = 0; x < N; x++) {\n        for (int y = 0; y <= x; y++) {\n            cin >> b[x][y];\n        }\n    }\n    \n    // Process violations iteratively - prioritize by value (larger values first)\n    bool changed = true;\n    while (changed) {\n        changed = false;\n        // Collect all violations with their values\n        vector<tuple<int, int, int>> violations; // (value, x, y)\n        for (int x = N - 2; x >= 0; x--) {\n            for (int y = 0; y <= x; y++) {\n                if (has_violation(x, y)) {\n                    violations.push_back({b[x][y], x, y});\n                }\n            }\n        }\n        \n        // Sort by value descending (fix larger values first)\n        sort(violations.rbegin(), violations.rend());\n        \n        for (auto& [val, x, y] : violations) {\n            if (has_violation(x, y)) {\n                sift_down(x, y);\n                changed = true;\n            }\n        }\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto& [x1, y1, x2, y2] : ops) {\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;\nint ex, ey;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nvector<vector<int>> grid;\n\nvector<pair<int,int>> findReachableEmpty() {\n    vector<pair<int,int>> result;\n    vector<vector<bool>> vis(D, vector<bool>(D, false));\n    queue<pair<int,int>> q;\n    q.push({ex, ey});\n    vis[ex][ey] = true;\n    \n    while (!q.empty()) {\n        int x = q.front().first, y = q.front().second;\n        q.pop();\n        \n        // This is an empty square (entrance or regular empty)\n        if (!(x == ex && y == ey)) {\n            result.push_back({x, y});\n        }\n        \n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx >= 0 && nx < D && ny >= 0 && ny < D && !vis[nx][ny] && grid[nx][ny] == -1) {\n                vis[nx][ny] = true;\n                q.push({nx, ny});\n            }\n        }\n    }\n    return result;\n}\n\nvector<pair<int,int>> findReachableContainers() {\n    vector<pair<int,int>> result;\n    vector<vector<bool>> vis(D, vector<bool>(D, false));\n    queue<pair<int,int>> q;\n    q.push({ex, ey});\n    vis[ex][ey] = true;\n    \n    while (!q.empty()) {\n        int x = q.front().first, y = q.front().second;\n        q.pop();\n        \n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx >= 0 && nx < D && ny >= 0 && ny < D && !vis[nx][ny] && grid[nx][ny] != -2) {\n                vis[nx][ny] = true;\n                if (grid[nx][ny] >= 0) {\n                    // This is a container adjacent to reachable empty square\n                    result.push_back({nx, ny});\n                } else {\n                    // This is an empty square, continue searching\n                    q.push({nx, ny});\n                }\n            }\n        }\n    }\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D >> N;\n    ex = 0;\n    ey = (D - 1) / 2;\n    \n    grid.assign(D, vector<int>(D, -1));\n    \n    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n        grid[x][y] = -2;\n    }\n    \n    int total = D * D - 1 - N;\n    \n    // Placement phase\n    for (int iter = 0; iter < total; iter++) {\n        int t;\n        cin >> t;\n        \n        vector<pair<int,int>> reach = findReachableEmpty();\n        \n        // Simple strategy: place at the last reachable position (furthest from entrance in BFS order)\n        pair<int,int> best = reach.back();\n        \n        grid[best.first][best.second] = t;\n        cout << best.first << \" \" << best.second << endl;\n    }\n    \n    // Transport phase\n    for (int iter = 0; iter < total; iter++) {\n        vector<pair<int,int>> reachable = findReachableContainers();\n        \n        // Find container with smallest number\n        pair<int,int> best = reachable[0];\n        for (auto& pos : reachable) {\n            if (grid[pos.first][pos.second] < grid[best.first][best.second]) {\n                best = pos;\n            }\n        }\n        \n        cout << best.first << \" \" << best.second << \"\\n\";\n        grid[best.first][best.second] = -1;\n    }\n    \n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint n, m;\nint dx[] = {0, 0, 1, -1};\nint dy[] = {1, -1, 0, 0};\n\nset<int> adjToZero;\nset<pair<int,int>> required;\n\nbool quickConnectivityCheck(vector<vector<int>>& grid, int i, int j) {\n    int c = grid[i][j];\n    vector<pair<int,int>> neighbors;\n    for (int d = 0; d < 4; d++) {\n        int ni = i + dx[d], nj = j + dy[d];\n        if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] == c) {\n            neighbors.push_back({ni, nj});\n        }\n    }\n    if (neighbors.size() <= 1) return false; // Might disconnect\n    if (neighbors.size() >= 3) return true;  // Likely safe\n    // For 2 neighbors, check if they're adjacent to each other\n    int di = abs(neighbors[0].first - neighbors[1].first);\n    int dj = abs(neighbors[0].second - neighbors[1].second);\n    return (di + dj == 1); // Adjacent = safe\n}\n\nbool fullConnectivityCheck(vector<vector<int>>& grid, int c) {\n    int si = -1, sj = -1, total = 0;\n    for (int x = 0; x < n; x++) for (int y = 0; y < n; y++) {\n        if (grid[x][y] == c) { if (si < 0) { si = x; sj = y; } total++; }\n    }\n    if (total == 0) return true;\n    vector<vector<bool>> vis(n, vector<bool>(n));\n    queue<pair<int,int>> q; q.push({si, sj}); vis[si][sj] = true;\n    int found = 1;\n    while (!q.empty()) {\n        auto [x, y] = q.front(); q.pop();\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx >= 0 && nx < n && ny >= 0 && ny < n && !vis[nx][ny] && grid[nx][ny] == c) {\n                vis[nx][ny] = true; found++; q.push({nx, ny});\n            }\n        }\n    }\n    return found == total;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> n >> m;\n    vector<vector<int>> orig(n, vector<int>(n));\n    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cin >> orig[i][j];\n    \n    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++)\n        if (i == 0 || i == n-1 || j == 0 || j == n-1) adjToZero.insert(orig[i][j]);\n    \n    map<pair<int,int>, int> initEdge;\n    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) {\n        int c = orig[i][j];\n        if (i == 0 || i == n-1 || j == 0 || j == n-1) initEdge[{0,c}]++;\n        if (j+1 < n && orig[i][j+1] != c) initEdge[{min(c,orig[i][j+1]), max(c,orig[i][j+1])}]++;\n        if (i+1 < n && orig[i+1][j] != c) initEdge[{min(c,orig[i+1][j]), max(c,orig[i+1][j])}]++;\n    }\n    for (auto& [p, cnt] : initEdge) if (cnt > 0) required.insert(p);\n    \n    vector<int> initCount(m+1);\n    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) initCount[orig[i][j]]++;\n    \n    auto start = chrono::steady_clock::now();\n    vector<vector<int>> best = orig;\n    int bestScore = 0;\n    \n    auto output = [&](vector<vector<int>>& g) {\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < n; j++) { cout << g[i][j]; if (j < n-1) cout << \" \"; }\n            cout << \"\\n\";\n        }\n        cout.flush();\n    };\n    \n    output(best);\n    \n    for (int seed = 0; seed < 200; seed++) {\n        auto elapsed = chrono::steady_clock::now() - start;\n        if (chrono::duration_cast<chrono::milliseconds>(elapsed).count() > 1900) break;\n        \n        auto grid = orig;\n        auto edgeCount = initEdge;\n        auto colorCount = initCount;\n        \n        mt19937 rng(seed * 7919 + 42);\n        \n        for (int iter = 0; iter < 200; iter++) {\n            vector<tuple<int,int,int,int>> cands; // priority, random, i, j\n            for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) {\n                if (grid[i][j] == 0) continue;\n                bool adj0 = (i == 0 || i == n-1 || j == 0 || j == n-1);\n                for (int d = 0; d < 4 && !adj0; d++) {\n                    int ni = i + dx[d], nj = j + dy[d];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] == 0) adj0 = true;\n                }\n                if (adj0) {\n                    int pri = colorCount[grid[i][j]] * 100 + (quickConnectivityCheck(grid, i, j) ? 50 : 0);\n                    cands.push_back({pri, (int)(rng() % 1000), i, j});\n                }\n            }\n            if (cands.empty()) break;\n            \n            sort(cands.rbegin(), cands.rend());\n            \n            int removed = 0;\n            for (auto [pri, r, i, j] : cands) {\n                int c = grid[i][j];\n                if (c == 0 || colorCount[c] <= 1) continue;\n                \n                bool canRemove = true;\n                for (int d = 0; d < 4 && canRemove; d++) {\n                    int ni = i + dx[d], nj = j + dy[d];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                        int nc = grid[ni][nj];\n                        if (nc != 0 && adjToZero.find(nc) == adjToZero.end()) canRemove = false;\n                    }\n                }\n                if (!canRemove) continue;\n                \n                bool touchesZero = (i == 0 || i == n-1 || j == 0 || j == n-1);\n                for (int d = 0; d < 4 && !touchesZero; d++) {\n                    int ni = i + dx[d], nj = j + dy[d];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && grid[ni][nj] == 0) touchesZero = true;\n                }\n                if (!touchesZero) continue;\n                \n                map<pair<int,int>, int> delta;\n                if (i == 0 || i == n-1 || j == 0 || j == n-1) delta[{0, c}]--;\n                for (int d = 0; d < 4; d++) {\n                    int ni = i + dx[d], nj = j + dy[d];\n                    if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                        int nc = grid[ni][nj];\n                        if (nc != c && nc != 0) { delta[{min(c,nc), max(c,nc)}]--; delta[{0, nc}]++; }\n                    }\n                }\n                \n                bool wouldBreak = false;\n                for (auto& [e, d] : delta)\n                    if (required.count(e) && edgeCount[e] + d <= 0) { wouldBreak = true; break; }\n                if (wouldBreak) continue;\n                \n                grid[i][j] = 0;\n                if (!fullConnectivityCheck(grid, c)) { grid[i][j] = c; continue; }\n                \n                for (auto& [e, d] : delta) edgeCount[e] += d;\n                colorCount[c]--;\n                removed++;\n            }\n            if (removed == 0) break;\n        }\n        \n        int sc = 0;\n        for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (grid[i][j] == 0) sc++;\n        if (sc > bestScore) { bestScore = sc; best = grid; output(best); }\n    }\n    \n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, D, Q;\nint query_count = 0;\n\nchar query(const vector<int>& L, const vector<int>& R) {\n    cout << L.size() << \" \" << R.size();\n    for (int x : L) cout << \" \" << x;\n    for (int x : R) cout << \" \" << x;\n    cout << \"\\n\" << flush;\n    char c;\n    cin >> c;\n    query_count++;\n    return c;\n}\n\nvector<int> sorted_items;\n\nvoid merge_sort(int l, int r) {\n    if (r - l <= 1 || query_count >= Q) return;\n    int m = (l + r) / 2;\n    merge_sort(l, m);\n    merge_sort(m, r);\n    \n    vector<int> left(sorted_items.begin() + l, sorted_items.begin() + m);\n    vector<int> right(sorted_items.begin() + m, sorted_items.begin() + r);\n    \n    int i = 0, j = 0, k = l;\n    while (i < (int)left.size() && j < (int)right.size()) {\n        if (query_count >= Q) {\n            while (i < (int)left.size()) sorted_items[k++] = left[i++];\n            while (j < (int)right.size()) sorted_items[k++] = right[j++];\n            return;\n        }\n        char c = query({left[i]}, {right[j]});\n        if (c != '>') sorted_items[k++] = left[i++];\n        else sorted_items[k++] = right[j++];\n    }\n    while (i < (int)left.size()) sorted_items[k++] = left[i++];\n    while (j < (int)right.size()) sorted_items[k++] = right[j++];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> D >> Q;\n    \n    sorted_items.resize(N);\n    iota(sorted_items.begin(), sorted_items.end(), 0);\n    merge_sort(0, N);\n    \n    vector<int> rank_of(N);\n    for (int i = 0; i < N; i++) rank_of[sorted_items[i]] = i;\n    \n    // Weight estimation\n    vector<double> w(N);\n    for (int i = 0; i < N; i++) w[i] = i + 1;\n    \n    int remaining = Q - query_count;\n    int est_budget = remaining / 3;\n    \n    for (int j = N - 1; j >= 1 && est_budget > 0; j--) {\n        int lo = 1, hi = j;\n        while (lo < hi && est_budget > 0 && query_count < Q) {\n            int mid = (lo + hi) / 2;\n            vector<int> L, R = {sorted_items[j]};\n            for (int t = 0; t < mid; t++) L.push_back(sorted_items[t]);\n            char c = query(L, R);\n            est_budget--;\n            if (c == '>' || c == '=') hi = mid;\n            else lo = mid + 1;\n        }\n        double sum = 0;\n        for (int t = 0; t < lo; t++) sum += w[t];\n        w[j] = max(w[j], sum);\n    }\n    \n    // Greedy assignment\n    vector<double> set_weight(D, 0);\n    vector<int> assignment(N);\n    vector<vector<int>> sets(D);\n    \n    for (int i = N - 1; i >= 0; i--) {\n        int item = sorted_items[i];\n        int best = 0;\n        for (int j = 1; j < D; j++)\n            if (set_weight[j] < set_weight[best]) best = j;\n        assignment[item] = best;\n        set_weight[best] += w[i];\n        sets[best].push_back(item);\n    }\n    \n    // Local search on all pairs - move lightest item from heavy to light\n    bool improved = true;\n    while (improved && query_count + 3 < Q) {\n        improved = false;\n        \n        for (int a = 0; a < D && query_count + 3 < Q; a++) {\n            for (int b = a + 1; b < D && query_count + 3 < Q; b++) {\n                if (sets[a].empty() || sets[b].empty()) continue;\n                \n                char cmp = query(sets[a], sets[b]);\n                if (cmp == '=') continue;\n                \n                int heavy = (cmp == '>') ? a : b;\n                int light = (cmp == '>') ? b : a;\n                \n                if (sets[heavy].size() <= 1) continue;\n                \n                // Find lightest item in heavy set\n                int min_item = sets[heavy][0];\n                int min_rank = rank_of[min_item];\n                for (int item : sets[heavy]) {\n                    if (rank_of[item] < min_rank) {\n                        min_rank = rank_of[item];\n                        min_item = item;\n                    }\n                }\n                \n                // Try moving it\n                vector<int> new_heavy, new_light = sets[light];\n                for (int item : sets[heavy])\n                    if (item != min_item) new_heavy.push_back(item);\n                new_light.push_back(min_item);\n                \n                if (new_heavy.empty()) continue;\n                \n                char new_cmp = query(new_heavy, new_light);\n                \n                // Accept if balanced or flipped (improvement)\n                if (new_cmp == '=' || new_cmp != cmp) {\n                    sets[heavy] = new_heavy;\n                    sets[light] = new_light;\n                    assignment[min_item] = light;\n                    set_weight[heavy] -= w[min_rank];\n                    set_weight[light] += w[min_rank];\n                    improved = true;\n                }\n            }\n        }\n    }\n    \n    while (query_count < Q) query({sorted_items[0]}, {sorted_items[1]});\n    \n    for (int i = 0; i < N; i++)\n        cout << assignment[i] << \" \\n\"[i == N - 1];\n    \n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct State {\n    vector<vector<int>> stacks;\n    vector<int> pos;\n    vector<int> stack_min;\n    \n    void init(const vector<vector<int>>& init_stacks, int n, int m) {\n        stacks = init_stacks;\n        pos.resize(n + 1);\n        stack_min.resize(m, INT_MAX);\n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < (int)stacks[i].size(); j++) {\n                pos[stacks[i][j]] = i;\n                stack_min[i] = min(stack_min[i], stacks[i][j]);\n            }\n        }\n    }\n    \n    void updateMin(int i) {\n        stack_min[i] = INT_MAX;\n        for (int b : stacks[i]) {\n            stack_min[i] = min(stack_min[i], b);\n        }\n    }\n};\n\nint simulate(const vector<vector<int>>& init_stacks, int n, int m, \n             vector<pair<int,int>>& ops, mt19937& rng, int noise_level, bool random_mode) {\n    \n    State state;\n    state.init(init_stacks, n, m);\n    \n    ops.clear();\n    int total_energy = 0;\n    \n    uniform_int_distribution<int> noise_dist(0, noise_level);\n    uniform_int_distribution<int> random_dest(0, m - 2);\n    \n    for (int v = 1; v <= n; v++) {\n        int stack_id = state.pos[v];\n        \n        int idx = 0;\n        while (state.stacks[stack_id][idx] != v) idx++;\n        \n        if (idx < (int)state.stacks[stack_id].size() - 1) {\n            int move_start = idx + 1;\n            int bottom_box = state.stacks[stack_id][move_start];\n            \n            int max_moving = 0;\n            int min_moving = INT_MAX;\n            int cnt = (int)state.stacks[stack_id].size() - move_start;\n            \n            for (int j = move_start; j < (int)state.stacks[stack_id].size(); j++) {\n                int b = state.stacks[stack_id][j];\n                max_moving = max(max_moving, b);\n                min_moving = min(min_moving, b);\n            }\n            \n            int best_dest = -1;\n            int best_score = INT_MIN;\n            \n            if (random_mode && (rng() % 10) == 0) {\n                // Occasionally pick random destination\n                int r = random_dest(rng);\n                best_dest = (r >= stack_id) ? r + 1 : r;\n            } else {\n                for (int i = 0; i < m; i++) {\n                    if (i == stack_id) continue;\n                    \n                    int score = 0;\n                    \n                    if (state.stacks[i].empty()) {\n                        score = n * 3 + (n - min_moving);\n                    } else {\n                        int min_in_dest = state.stack_min[i];\n                        \n                        if (min_in_dest > min_moving) {\n                            score = n * 3;\n                            if (state.stacks[i].back() > max_moving) {\n                                score += 50;\n                            }\n                        } else {\n                            score = min_in_dest;\n                            score -= cnt * 3;\n                        }\n                    }\n                    \n                    score -= (int)state.stacks[i].size() * 2;\n                    \n                    if (noise_level > 0) {\n                        score += noise_dist(rng);\n                    }\n                    \n                    if (score > best_score) {\n                        best_score = score;\n                        best_dest = i;\n                    }\n                }\n            }\n            \n            total_energy += cnt + 1;\n            ops.push_back({bottom_box, best_dest + 1});\n            \n            for (int j = move_start; j < (int)state.stacks[stack_id].size(); j++) {\n                int b = state.stacks[stack_id][j];\n                state.stacks[best_dest].push_back(b);\n                state.pos[b] = best_dest;\n            }\n            state.stacks[stack_id].resize(move_start);\n            \n            state.updateMin(stack_id);\n            state.updateMin(best_dest);\n        }\n        \n        ops.push_back({v, 0});\n        state.stacks[stack_id].pop_back();\n        state.updateMin(stack_id);\n    }\n    \n    return total_energy;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n, m;\n    cin >> n >> m;\n    \n    vector<vector<int>> init_stacks(m);\n    \n    for (int i = 0; i < m; i++) {\n        int h = n / m;\n        for (int j = 0; j < h; j++) {\n            int x;\n            cin >> x;\n            init_stacks[i].push_back(x);\n        }\n    }\n    \n    vector<pair<int, int>> best_ops;\n    int best_energy = INT_MAX;\n    \n    auto start_time = chrono::steady_clock::now();\n    \n    // Noise levels to try\n    vector<int> noise_levels = {0, 5, 10, 15, 20, 25, 30, 40, 50, 70};\n    \n    int seed = 0;\n    int level_idx = 0;\n    \n    while (true) {\n        auto current_time = chrono::steady_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1900) break;\n        \n        int noise_level = noise_levels[level_idx % noise_levels.size()];\n        bool random_mode = (seed % 20 == 19);  // 5% random mode\n        \n        mt19937 rng(seed);\n        vector<pair<int, int>> ops;\n        int energy = simulate(init_stacks, n, m, ops, rng, noise_level, random_mode);\n        \n        if (energy < best_energy) {\n            best_energy = energy;\n            best_ops = ops;\n        }\n        \n        seed++;\n        level_idx++;\n    }\n    \n    for (auto& [a, b] : best_ops) {\n        cout << a << \" \" << b << \"\\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;\nlong long totalD;\nmt19937 rng(42);\n\nint di[] = {0, 1, 0, -1};\nint dj[] = {1, 0, -1, 0};\nchar dirChar[] = {'R', 'D', 'L', 'U'};\n\nbool canMove(int i, int j, int dir) {\n    int ni = i + di[dir], nj = j + dj[dir];\n    if (ni < 0 || ni >= N || nj < 0 || nj >= N) return false;\n    if (dir == 0) return v[i][j] == '0';\n    if (dir == 1) return h[i][j] == '0';\n    if (dir == 2) return j > 0 && v[i][j-1] == '0';\n    return i > 0 && h[i-1][j] == '0';\n}\n\nlong double fastEvaluate(const string& path) {\n    int L = path.size();\n    vector<vector<long long>> contrib(N, vector<long long>(N, 0));\n    long long contribSum = 0;\n    int ci = 0, cj = 0;\n    \n    auto move = [&](int t, char c) {\n        int dir = (c == 'R') ? 0 : (c == 'D') ? 1 : (c == 'L') ? 2 : 3;\n        ci += di[dir]; cj += dj[dir];\n        contribSum -= contrib[ci][cj];\n        contrib[ci][cj] = (long long)d[ci][cj] * t;\n        contribSum += contrib[ci][cj];\n    };\n    \n    for (int t = 1; t <= L; t++) move(t, path[t-1]);\n    \n    long double totalSum = 0;\n    for (int t = L + 1; t <= 2 * L; t++) {\n        totalSum += (long long)totalD * t - contribSum;\n        move(t, path[(t-1) % L]);\n    }\n    return totalSum / L;\n}\n\nvector<vector<int>> getVisitCounts(const string& path) {\n    vector<vector<int>> cnt(N, vector<int>(N, 0));\n    int ci = 0, cj = 0;\n    cnt[0][0] = 1;\n    for (char c : path) {\n        int dir = (c == 'R') ? 0 : (c == 'D') ? 1 : (c == 'L') ? 2 : 3;\n        ci += di[dir]; cj += dj[dir];\n        cnt[ci][cj]++;\n    }\n    return cnt;\n}\n\nstring generatePath(int mode) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    string path;\n    \n    function<void(int, int)> dfs = [&](int i, int j) {\n        visited[i][j] = true;\n        vector<pair<int, int>> children;\n        for (int dir = 0; dir < 4; dir++) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj] && canMove(i, j, dir)) {\n                children.push_back({d[ni][nj], dir});\n            }\n        }\n        if (mode == 0) sort(children.begin(), children.end());\n        else if (mode == 1) sort(children.rbegin(), children.rend());\n        else shuffle(children.begin(), children.end(), rng);\n        \n        for (auto& [dval, dir] : children) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (!visited[ni][nj]) {\n                path += dirChar[dir];\n                dfs(ni, nj);\n                path += dirChar[(dir + 2) % 4];\n            }\n        }\n    };\n    dfs(0, 0);\n    return path;\n}\n\nvector<vector<int>> dist0;\nvector<tuple<int,int,int,string>> allLoops;\n\nvoid precomputeLoops() {\n    dist0.assign(N, vector<int>(N, -1));\n    queue<pair<int,int>> bfs;\n    bfs.push({0, 0});\n    dist0[0][0] = 0;\n    vector<vector<int>> par(N, vector<int>(N, -1));\n    par[0][0] = -2;\n    \n    while (!bfs.empty()) {\n        auto [i, j] = bfs.front(); bfs.pop();\n        for (int dir = 0; dir < 4; dir++) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && dist0[ni][nj] == -1 && canMove(i, j, dir)) {\n                dist0[ni][nj] = dist0[i][j] + 1;\n                par[ni][nj] = (dir + 2) % 4;\n                bfs.push({ni, nj});\n            }\n        }\n    }\n    \n    for (int ti = 0; ti < N; ti++) {\n        for (int tj = 0; tj < N; tj++) {\n            if (ti == 0 && tj == 0) continue;\n            string toTarget, fromTarget;\n            int ci = ti, cj = tj;\n            while (ci != 0 || cj != 0) {\n                int pdir = par[ci][cj];\n                fromTarget += dirChar[pdir];\n                toTarget += dirChar[(pdir + 2) % 4];\n                ci += di[pdir]; cj += dj[pdir];\n            }\n            reverse(toTarget.begin(), toTarget.end());\n            allLoops.push_back({d[ti][tj], ti, tj, toTarget + fromTarget});\n        }\n    }\n    sort(allLoops.rbegin(), allLoops.rend());\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> 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    totalD = 0;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n            totalD += d[i][j];\n        }\n    \n    precomputeLoops();\n    \n    string bestPath;\n    long double bestScore = 1e18;\n    vector<pair<long double, string>> topPaths;\n    \n    auto tryPath = [&](const string& path) -> long double {\n        if (path.size() > 100000) return 1e18;\n        long double score = fastEvaluate(path);\n        if (score < bestScore) {\n            bestScore = score;\n            bestPath = path;\n        }\n        return score;\n    };\n    \n    for (int mode = 0; mode < 2; mode++) {\n        string p = generatePath(mode);\n        long double s = tryPath(p);\n        topPaths.push_back({s, p});\n    }\n    \n    auto startTime = chrono::steady_clock::now();\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() < 1200) {\n        string p = generatePath(2);\n        long double s = tryPath(p);\n        topPaths.push_back({s, p});\n    }\n    \n    sort(topPaths.begin(), topPaths.end());\n    if (topPaths.size() > 6) topPaths.resize(6);\n    \n    // Loop addition on top paths\n    for (auto& [baseScore, basePath] : topPaths) {\n        string current = basePath;\n        long double curScore = baseScore;\n        \n        for (int iter = 0; iter < 20; iter++) {\n            bool improved = false;\n            auto visits = getVisitCounts(current);\n            \n            // Sort loops by d/visits ratio for this path\n            vector<pair<double, int>> priorities;\n            for (int i = 0; i < (int)allLoops.size(); i++) {\n                auto& [dval, ti, tj, loop] = allLoops[i];\n                double priority = (double)dval / max(1, visits[ti][tj]);\n                priorities.push_back({priority, i});\n            }\n            sort(priorities.rbegin(), priorities.rend());\n            \n            for (auto& [pri, idx] : priorities) {\n                auto& [dval, ti, tj, loop] = allLoops[idx];\n                if (current.size() + loop.size() > 100000) continue;\n                string candidate = current + loop;\n                long double score = fastEvaluate(candidate);\n                if (score < curScore) {\n                    curScore = score;\n                    current = candidate;\n                    improved = true;\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestPath = current;\n                    }\n                    break;\n                }\n            }\n            if (!improved) break;\n        }\n    }\n    \n    // Multi-loop to same cell\n    for (int c = 0; c < min(8, (int)allLoops.size()); c++) {\n        auto& [dval, ti, tj, loop] = allLoops[c];\n        string candidate = bestPath;\n        for (int rep = 1; rep <= 30 && candidate.size() + loop.size() <= 100000; rep++) {\n            candidate += loop;\n            long double score = tryPath(candidate);\n        }\n    }\n    \n    cout << bestPath << endl;\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, si, sj;\nmap<char, vector<pair<int,int>>> charPos;\n\nint overlap(const string& a, const string& b) {\n    int maxOv = min(a.length(), b.length());\n    for (int ov = maxOv; ov >= 1; ov--) {\n        bool match = true;\n        int aStart = a.length() - ov;\n        for (int k = 0; k < ov && match; k++) {\n            if (a[aStart + k] != b[k]) match = false;\n        }\n        if (match) return ov;\n    }\n    return 0;\n}\n\nstring buildSuperstring(vector<string> remaining) {\n    while (remaining.size() > 1) {\n        int bestOv = -1, bestI = -1, bestJ = -1;\n        \n        for (int i = 0; i < (int)remaining.size(); i++) {\n            for (int j = 0; j < (int)remaining.size(); j++) {\n                if (i != j) {\n                    int ov = overlap(remaining[i], remaining[j]);\n                    if (ov > bestOv) { bestOv = ov; bestI = i; bestJ = j; }\n                }\n            }\n        }\n        \n        string merged = remaining[bestI] + remaining[bestJ].substr(bestOv);\n        \n        vector<string> newRemaining;\n        newRemaining.reserve(remaining.size() - 1);\n        for (int k = 0; k < (int)remaining.size(); k++) {\n            if (k != bestI && k != bestJ) {\n                newRemaining.push_back(move(remaining[k]));\n            }\n        }\n        newRemaining.push_back(move(merged));\n        remaining = move(newRemaining);\n    }\n    return remaining[0];\n}\n\npair<int, vector<pair<int,int>>> computePath(const string& ss) {\n    int n = ss.length();\n    if (n == 0) return {0, {}};\n    \n    vector<vector<int>> dp(n);\n    \n    for (int pos = n - 1; pos >= 0; pos--) {\n        char c = ss[pos];\n        const auto& positions = charPos[c];\n        int sz = positions.size();\n        dp[pos].assign(sz, 0);\n        \n        if (pos < n - 1) {\n            char nc = ss[pos + 1];\n            const auto& nextPositions = charPos[nc];\n            for (int idx = 0; idx < sz; idx++) {\n                int r = positions[idx].first, col = positions[idx].second;\n                int best = INT_MAX;\n                for (size_t nidx = 0; nidx < nextPositions.size(); nidx++) {\n                    int nr = nextPositions[nidx].first, ncol = nextPositions[nidx].second;\n                    best = min(best, abs(nr - r) + abs(ncol - col) + 1 + dp[pos + 1][nidx]);\n                }\n                dp[pos][idx] = best;\n            }\n        }\n    }\n    \n    const auto& pos0 = charPos[ss[0]];\n    int bestCost = INT_MAX;\n    for (size_t idx = 0; idx < pos0.size(); idx++) {\n        int dist = abs(pos0[idx].first - si) + abs(pos0[idx].second - sj) + 1;\n        bestCost = min(bestCost, dist + dp[0][idx]);\n    }\n    \n    vector<pair<int,int>> path(n);\n    int curI = si, curJ = sj;\n    for (int pos = 0; pos < n; pos++) {\n        const auto& positions = charPos[ss[pos]];\n        int best = INT_MAX, bIdx = 0;\n        for (size_t idx = 0; idx < positions.size(); idx++) {\n            int r = positions[idx].first, col = positions[idx].second;\n            int total = abs(r - curI) + abs(col - curJ) + 1 + dp[pos][idx];\n            if (total < best) { best = total; bIdx = idx; }\n        }\n        path[pos] = positions[bIdx];\n        curI = path[pos].first;\n        curJ = path[pos].second;\n    }\n    \n    return {bestCost, path};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> si >> sj;\n    for (int i = 0; i < N; i++) {\n        string row; cin >> row;\n        for (int j = 0; j < N; j++)\n            charPos[row[j]].push_back({i, j});\n    }\n    \n    vector<string> t(M);\n    for (int i = 0; i < M; i++) cin >> t[i];\n    \n    mt19937 rng(12345);\n    vector<pair<int,int>> bestPath;\n    int bestCost = INT_MAX;\n    \n    auto startTime = chrono::steady_clock::now();\n    \n    for (int iter = 0; ; iter++) {\n        if (iter > 0) {\n            auto elapsed = chrono::duration_cast<chrono::milliseconds>(\n                chrono::steady_clock::now() - startTime).count();\n            if (elapsed > 1850) break;\n        }\n        \n        vector<string> input = t;\n        if (iter == 1) {\n            sort(input.begin(), input.end());\n        } else if (iter == 2) {\n            sort(input.begin(), input.end(), greater<string>());\n        } else if (iter == 3) {\n            sort(input.begin(), input.end(), [](const string& a, const string& b) {\n                return a.back() < b.back();\n            });\n        } else if (iter == 4) {\n            sort(input.begin(), input.end(), [](const string& a, const string& b) {\n                return a[0] < b[0];\n            });\n        } else if (iter > 4) {\n            shuffle(input.begin(), input.end(), rng);\n        }\n        \n        string ss = buildSuperstring(input);\n        auto [cost, path] = computePath(ss);\n        \n        if (cost < bestCost) {\n            bestCost = cost;\n            bestPath = path;\n        }\n    }\n    \n    for (auto& [i, j] : bestPath)\n        cout << i << \" \" << j << \"\\n\";\n    \n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\ndouble eps;\nvector<vector<pair<int,int>>> shapes;\nmap<pair<int,int>, int> drilled;\nset<pair<int,int>> confirmed_oil, confirmed_no_oil;\nint qcount = 0;\nint maxQ;\n\nint queryDrill(int i, int j) {\n    pair<int,int> key = make_pair(i, j);\n    if (drilled.count(key)) return drilled[key];\n    cout << \"q 1 \" << i << \" \" << j << \"\\n\" << flush;\n    qcount++;\n    int v; cin >> v;\n    drilled[key] = v;\n    if (v > 0) confirmed_oil.insert(key);\n    else confirmed_no_oil.insert(key);\n    return v;\n}\n\nint queryDivine(const vector<pair<int,int>>& cells) {\n    cout << \"q \" << cells.size();\n    for (auto& c : cells) cout << \" \" << c.first << \" \" << c.second;\n    cout << \"\\n\" << flush;\n    qcount++;\n    int v; cin >> v;\n    return v;\n}\n\nint submit(set<pair<int,int>> oil) {\n    for (auto& c : confirmed_oil) oil.insert(c);\n    cout << \"a \" << oil.size();\n    for (auto& c : oil) cout << \" \" << c.first << \" \" << c.second;\n    cout << \"\\n\" << flush;\n    qcount++;\n    int r; cin >> r;\n    return r;\n}\n\nvector<vector<set<pair<int,int>>>> placements;\n\nvoid filterPlacements() {\n    for (int m = 0; m < M; m++) {\n        vector<set<pair<int,int>>> valid;\n        for (auto& p : placements[m]) {\n            bool ok = true;\n            for (auto& c : confirmed_no_oil)\n                if (p.count(c)) { ok = false; break; }\n            if (ok) valid.push_back(p);\n        }\n        if (!valid.empty()) placements[m] = valid;\n    }\n}\n\nbool allUnique() {\n    for (int m = 0; m < M; m++)\n        if (placements[m].size() > 1) return false;\n    return true;\n}\n\nset<pair<int,int>> getAnswer() {\n    set<pair<int,int>> answer;\n    for (int m = 0; m < M; m++)\n        if (!placements[m].empty())\n            for (auto& c : placements[m][0]) answer.insert(c);\n    return answer;\n}\n\nset<pair<int,int>> getPossible() {\n    set<pair<int,int>> possible;\n    for (int m = 0; m < M; m++)\n        for (auto& p : placements[m])\n            for (auto& c : p) possible.insert(c);\n    return possible;\n}\n\npair<int,int> getBestCell(const vector<vector<double>>& prob) {\n    map<pair<int,int>, vector<int>> cellCounts;\n    \n    for (int m = 0; m < M; m++) {\n        for (auto& p : placements[m])\n            for (auto& c : p) {\n                if (cellCounts.find(c) == cellCounts.end())\n                    cellCounts[c] = vector<int>(M, 0);\n                cellCounts[c][m]++;\n            }\n    }\n    \n    pair<int,int> best = {-1, -1};\n    double bestScore = -1e18;\n    \n    for (auto& kv : cellCounts) {\n        pair<int,int> cell = kv.first;\n        vector<int>& counts = kv.second;\n        \n        if (drilled.count(cell)) continue;\n        \n        double p = prob[cell.first][cell.second];\n        \n        bool valid = true;\n        for (int m = 0; m < M; m++) {\n            if ((int)placements[m].size() - counts[m] <= 0) {\n                valid = false; break;\n            }\n        }\n        if (!valid) continue;\n        \n        // Entropy-based scoring: prefer cells that split placements evenly\n        double entropyGain = 0;\n        for (int m = 0; m < M; m++) {\n            int sz = placements[m].size();\n            if (sz <= 1) continue;\n            double ratio = (double)counts[m] / sz;\n            // Binary entropy approximation\n            double h = ratio * (1 - ratio) * 4; // peaks at 0.5\n            entropyGain += h * log((double)sz);\n        }\n        \n        // Weight by probability of no oil (since that's when we eliminate)\n        double score = (1.0 - p) * entropyGain;\n        \n        // Tie-breaker: total elimination potential\n        double totalElim = 0;\n        for (int m = 0; m < M; m++)\n            totalElim += counts[m];\n        score += totalElim * 0.001;\n        \n        if (score > bestScore) {\n            bestScore = score;\n            best = cell;\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> eps;\n    maxQ = 2 * N * N;\n    shapes.resize(M);\n    \n    for (int m = 0; m < M; m++) {\n        int d; cin >> d;\n        shapes[m].resize(d);\n        for (int i = 0; i < d; i++)\n            cin >> shapes[m][i].first >> shapes[m][i].second;\n    }\n    \n    placements.resize(M);\n    for (int m = 0; m < M; m++) {\n        int maxI = 0, maxJ = 0;\n        for (auto& c : shapes[m]) {\n            maxI = max(maxI, c.first);\n            maxJ = max(maxJ, c.second);\n        }\n        for (int di = 0; di + maxI < N; di++)\n            for (int dj = 0; dj + maxJ < N; dj++) {\n                set<pair<int,int>> cells;\n                for (auto& c : shapes[m])\n                    cells.insert({di + c.first, dj + c.second});\n                placements[m].push_back(cells);\n            }\n    }\n    \n    vector<vector<double>> prob(N, vector<double>(N, 0.3));\n    \n    // Row divination only if eps is reasonable\n    if (eps <= 0.15) {\n        for (int i = 0; i < N; i++) {\n            vector<pair<int,int>> row;\n            for (int j = 0; j < N; j++) row.push_back({i, j});\n            int est = queryDivine(row);\n            double denom = max(0.01, 1.0 - 2.0 * eps);\n            double trueEst = max(0.0, (est - N * eps) / denom);\n            for (int j = 0; j < N; j++)\n                prob[i][j] = min(0.9, max(0.1, trueEst / N));\n        }\n        \n        // Column divination only for very low eps\n        if (eps <= 0.05) {\n            for (int j = 0; j < N; j++) {\n                vector<pair<int,int>> col;\n                for (int i = 0; i < N; i++) col.push_back({i, j});\n                int est = queryDivine(col);\n                double denom = max(0.01, 1.0 - 2.0 * eps);\n                double trueEst = max(0.0, (est - N * eps) / denom);\n                for (int i = 0; i < N; i++)\n                    prob[i][j] = (prob[i][j] + min(0.9, max(0.1, trueEst / N))) / 2.0;\n            }\n        }\n    }\n    \n    while (qcount < maxQ - 5 && !allUnique()) {\n        filterPlacements();\n        auto cell = getBestCell(prob);\n        if (cell.first < 0) break;\n        queryDrill(cell.first, cell.second);\n    }\n    \n    filterPlacements();\n    set<pair<int,int>> answer = allUnique() ? getAnswer() : getPossible();\n    for (auto& c : confirmed_no_oil) answer.erase(c);\n    \n    if (!submit(answer)) {\n        while (qcount < maxQ - 2) {\n            filterPlacements();\n            if (allUnique()) break;\n            auto cell = getBestCell(prob);\n            if (cell.first < 0) {\n                auto possible = getPossible();\n                for (auto& c : possible)\n                    if (!drilled.count(c)) { cell = c; break; }\n            }\n            if (cell.first < 0) break;\n            queryDrill(cell.first, cell.second);\n        }\n        filterPlacements();\n        answer = allUnique() ? getAnswer() : getPossible();\n        for (auto& c : confirmed_no_oil) answer.erase(c);\n        if (!submit(answer)) submit(confirmed_oil);\n    }\n    \n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    for (int d = 0; d < D; d++) {\n        vector<int> h(N);\n        int totalH = 0;\n        \n        // Calculate minimum height needed for each reservation\n        for (int k = 0; k < N; k++) {\n            h[k] = (a[d][k] + W - 1) / W;  // ceil(a[k] / W)\n            if (h[k] == 0) h[k] = 1;\n            totalH += h[k];\n        }\n        \n        if (totalH > W) {\n            int excess = totalH - W;\n            \n            // Reduce heights, always picking the one with largest slack (minimum penalty)\n            while (excess > 0) {\n                int bestK = -1;\n                int maxSlack = INT_MIN;\n                \n                for (int k = 0; k < N; k++) {\n                    if (h[k] > 1) {\n                        int slack = h[k] * W - a[d][k];\n                        if (slack > maxSlack) {\n                            maxSlack = slack;\n                            bestK = k;\n                        }\n                    }\n                }\n                \n                if (bestK == -1) break;\n                h[bestK]--;\n                excess--;\n            }\n        } else if (totalH < W) {\n            int extra = W - totalH;\n            // Distribute extra space to larger reservations\n            while (extra > 0) {\n                for (int k = N - 1; k >= 0 && extra > 0; k--) {\n                    h[k]++;\n                    extra--;\n                }\n            }\n        }\n        \n        // Output rectangles\n        int y = 0;\n        for (int k = 0; k < N; k++) {\n            cout << y << \" 0 \" << y + h[k] << \" \" << W << \"\\n\";\n            y += h[k];\n        }\n    }\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long P = 998244353;\nint N, M, K;\nvector<vector<long long>> a_init;\nvector<array<array<long long, 3>, 3>> stamps;\n\nvoid applyOp(vector<vector<long long>>& a, int m, int p, int q) {\n    for (int i = 0; i < 3; i++)\n        for (int j = 0; j < 3; j++)\n            a[p+i][q+j] = (a[p+i][q+j] + stamps[m][i][j]) % P;\n}\n\nlong long calcGain(const vector<vector<long long>>& a, int m, int p, int q) {\n    long long gain = 0;\n    for (int i = 0; i < 3; i++)\n        for (int j = 0; j < 3; j++)\n            gain += (a[p+i][q+j] + stamps[m][i][j]) % P - a[p+i][q+j];\n    return gain;\n}\n\nlong long calcScore(const vector<vector<long long>>& a) {\n    long long s = 0;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            s += a[i][j];\n    return s;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    cin >> N >> M >> K;\n    a_init.assign(N, vector<long long>(N));\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            cin >> a_init[i][j];\n            a_init[i][j] %= P;\n        }\n    \n    stamps.resize(M);\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    auto start = chrono::steady_clock::now();\n    auto elapsed = [&]() { return chrono::duration<double>(chrono::steady_clock::now() - start).count(); };\n    \n    vector<tuple<int,int,int>> best_ops;\n    long long best_score = calcScore(a_init);\n    \n    mt19937 rng(42);\n    \n    for (int trial = 0; elapsed() < 1.9; trial++) {\n        vector<tuple<int,int,int>> ops;\n        auto a = a_init;\n        \n        // Randomized greedy\n        for (int op = 0; op < K; op++) {\n            vector<tuple<long long, int, int, int>> cands;\n            for (int m = 0; m < M; m++)\n                for (int p = 0; p <= N-3; p++)\n                    for (int q = 0; q <= N-3; q++) {\n                        long long gain = calcGain(a, m, p, q);\n                        if (gain > 0) cands.push_back({gain, m, p, q});\n                    }\n            if (cands.empty()) break;\n            sort(cands.rbegin(), cands.rend());\n            int pick = (trial == 0) ? 0 : rng() % min((int)cands.size(), 2 + trial / 3);\n            auto [g, m, p, q] = cands[pick];\n            applyOp(a, m, p, q);\n            ops.push_back({m, p, q});\n        }\n        \n        long long score = calcScore(a);\n        \n        // Local optimization passes\n        for (int iter = 0; iter < 5 && elapsed() < 1.9; iter++) {\n            bool improved = false;\n            \n            // Try replacing each operation\n            for (int idx = 0; idx < (int)ops.size() && elapsed() < 1.9; idx++) {\n                auto orig = ops[idx];\n                auto a2 = a_init;\n                for (int k = 0; k < (int)ops.size(); k++)\n                    if (k != idx) {\n                        auto [m,p,q] = ops[k];\n                        applyOp(a2, m, p, q);\n                    }\n                \n                long long bestGain = 0;\n                int bm=-1, bp=-1, bq=-1;\n                for (int m = 0; m < M; m++)\n                    for (int p = 0; p <= N-3; p++)\n                        for (int q = 0; q <= N-3; q++) {\n                            long long gain = calcGain(a2, m, p, q);\n                            if (gain > bestGain) { bestGain = gain; bm=m; bp=p; bq=q; }\n                        }\n                \n                if (bm != -1) {\n                    auto newOp = make_tuple(bm, bp, bq);\n                    if (newOp != orig) {\n                        ops[idx] = newOp;\n                        a = a2;\n                        applyOp(a, bm, bp, bq);\n                        long long newScore = calcScore(a);\n                        if (newScore > score) {\n                            score = newScore;\n                            improved = true;\n                        }\n                    }\n                }\n            }\n            \n            // Try removing operations\n            for (int idx = (int)ops.size()-1; idx >= 0 && elapsed() < 1.9; idx--) {\n                auto a2 = a_init;\n                for (int k = 0; k < (int)ops.size(); k++)\n                    if (k != idx) {\n                        auto [m,p,q] = ops[k];\n                        applyOp(a2, m, p, q);\n                    }\n                long long newScore = calcScore(a2);\n                if (newScore >= score) {\n                    ops.erase(ops.begin() + idx);\n                    a = a2;\n                    score = newScore;\n                    improved = true;\n                }\n            }\n            \n            // Try adding more operations\n            while (ops.size() < (size_t)K && elapsed() < 1.9) {\n                long long bestGain = 0;\n                int bm=-1, bp=-1, bq=-1;\n                for (int m = 0; m < M; m++)\n                    for (int p = 0; p <= N-3; p++)\n                        for (int q = 0; q <= N-3; q++) {\n                            long long gain = calcGain(a, m, p, q);\n                            if (gain > bestGain) { bestGain = gain; bm=m; bp=p; bq=q; }\n                        }\n                if (bm == -1) break;\n                applyOp(a, bm, bp, bq);\n                ops.push_back({bm, bp, bq});\n                score += bestGain;\n                improved = true;\n            }\n            \n            if (!improved) break;\n        }\n        \n        if (score > best_score) {\n            best_score = score;\n            best_ops = ops;\n        }\n    }\n    \n    cout << best_ops.size() << \"\\n\";\n    for (auto& [m,p,q] : best_ops) cout << m << \" \" << p << \" \" << q << \"\\n\";\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 5;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n; cin >> n;\n    int A[N][N];\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            cin >> A[i][j];\n    \n    string ans[N];\n    int grid[N][N]; memset(grid, -1, sizeof(grid));\n    int cr = 0, cc = 0, hold = -1;\n    int next_in[N] = {0};\n    int next_needed[N]; // next container needed for each row\n    for (int i = 0; i < N; i++) next_needed[i] = i * N;\n    \n    for (int t = 0; t < 9000; t++) {\n        // Step 1: Bring in containers\n        for (int i = 0; i < N; i++) {\n            if (next_in[i] < N && grid[i][0] == -1) {\n                bool blocked = (cr == i && cc == 0 && hold != -1);\n                if (!blocked) grid[i][0] = A[i][next_in[i]++];\n            }\n        }\n        \n        char moves[N];\n        for (int c = 0; c < N; c++) moves[c] = '.';\n        \n        if (t == 0) {\n            for (int c = 1; c < N; c++) moves[c] = 'B';\n        }\n        \n        if (hold == -1) {\n            if (grid[cr][cc] != -1) {\n                moves[0] = 'P';\n            } else {\n                // Find best container to pick up\n                // Priority: containers that are \"ready\" (next needed for their row)\n                int best_r = -1, best_c = -1;\n                int best_score = -1000000;\n                \n                for (int i = 0; i < N; i++) {\n                    for (int j = 0; j < N; j++) {\n                        if (grid[i][j] != -1) {\n                            int cont = grid[i][j];\n                            int target_row = cont / N;\n                            int dist = abs(i - cr) + abs(j - cc);\n                            \n                            int score = -dist * 10;\n                            \n                            // Bonus if this container is next needed for its row\n                            if (cont == next_needed[target_row]) {\n                                score += 1000;\n                            }\n                            // Small bonus for lower container numbers\n                            score -= cont;\n                            \n                            if (score > best_score) {\n                                best_score = score;\n                                best_r = i; best_c = j;\n                            }\n                        }\n                    }\n                }\n                \n                if (best_r != -1) {\n                    if (best_r > cr) moves[0] = 'D';\n                    else if (best_r < cr) moves[0] = 'U';\n                    else if (best_c > cc) moves[0] = 'R';\n                    else if (best_c < cc) moves[0] = 'L';\n                }\n            }\n        } else {\n            int target_row = hold / N;\n            if (cr != target_row) {\n                if (target_row > cr) moves[0] = 'D';\n                else moves[0] = 'U';\n            } else if (cc < N-1) {\n                moves[0] = 'R';\n            } else {\n                moves[0] = 'Q';\n            }\n        }\n        \n        // Execute\n        if (moves[0] == 'P') { hold = grid[cr][cc]; grid[cr][cc] = -1; }\n        else if (moves[0] == 'Q') { \n            int target_row = hold / N;\n            if (cr == target_row && cc == N-1) {\n                // Update next_needed when dispatching\n                if (hold == next_needed[target_row]) {\n                    next_needed[target_row]++;\n                }\n            }\n            grid[cr][cc] = hold; \n            hold = -1; \n        }\n        else if (moves[0] == 'R') cc++;\n        else if (moves[0] == 'L') cc--;\n        else if (moves[0] == 'U') cr--;\n        else if (moves[0] == 'D') cr++;\n        \n        // Step 3: Dispatch\n        for (int i = 0; i < N; i++) grid[i][N-1] = -1;\n        \n        for (int c = 0; c < N; c++) ans[c] += moves[c];\n        \n        // Check if done\n        bool done = true;\n        for (int i = 0; i < N; i++) if (next_in[i] < N) done = false;\n        if (hold != -1) done = false;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] != -1) done = false;\n        if (done) break;\n    }\n    \n    for (int i = 0; i < N; i++) cout << ans[i] << \"\\n\";\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nvector<vector<int>> h;\nvector<string> ops;\nint cx = 0, cy = 0;\nint load = 0;\n\nvoid do_load(int d) {\n    if (d <= 0) return;\n    ops.push_back(\"+\" + to_string(d));\n    load += d;\n    h[cx][cy] -= d;\n}\n\nvoid do_unload(int d) {\n    if (d <= 0) return;\n    ops.push_back(\"-\" + to_string(d));\n    load -= d;\n    h[cx][cy] += d;\n}\n\nvoid move_one(char dir) {\n    ops.push_back(string(1, dir));\n    if (dir == 'U') cx--;\n    else if (dir == 'D') cx++;\n    else if (dir == 'L') cy--;\n    else if (dir == 'R') cy++;\n}\n\nvoid process_cell() {\n    if (h[cx][cy] > 0) do_load(h[cx][cy]);\n    if (h[cx][cy] < 0 && load > 0) do_unload(min(load, -h[cx][cy]));\n}\n\n// Calculate work done on path considering load state\nint calc_path_work(int fx, int fy, int tx, int ty, int init_load, bool vert_first) {\n    int work = 0;\n    int sim_load = init_load;\n    int x = fx, y = fy;\n    \n    auto process = [&](int px, int py) {\n        if (h[px][py] > 0) {\n            work += h[px][py];\n            sim_load += h[px][py];\n        } else if (h[px][py] < 0 && sim_load > 0) {\n            int unload = min(sim_load, -h[px][py]);\n            work += unload;\n            sim_load -= unload;\n        }\n    };\n    \n    if (vert_first) {\n        while (x != tx) { x += (tx > x) ? 1 : -1; process(x, y); }\n        while (y != ty) { y += (ty > y) ? 1 : -1; process(x, y); }\n    } else {\n        while (y != ty) { y += (ty > y) ? 1 : -1; process(x, y); }\n        while (x != tx) { x += (tx > x) ? 1 : -1; process(x, y); }\n    }\n    return work;\n}\n\nint best_path_work(int fx, int fy, int tx, int ty, int init_load) {\n    return max(calc_path_work(fx, fy, tx, ty, init_load, true),\n               calc_path_work(fx, fy, tx, ty, init_load, false));\n}\n\nvoid move_to(int tx, int ty) {\n    int vert_work = calc_path_work(cx, cy, tx, ty, load, true);\n    int horiz_work = calc_path_work(cx, cy, tx, ty, load, false);\n    \n    if (vert_work >= horiz_work) {\n        while (cx < tx) { move_one('D'); process_cell(); }\n        while (cx > tx) { move_one('U'); process_cell(); }\n        while (cy < ty) { move_one('R'); process_cell(); }\n        while (cy > ty) { move_one('L'); process_cell(); }\n    } else {\n        while (cy < ty) { move_one('R'); process_cell(); }\n        while (cy > ty) { move_one('L'); process_cell(); }\n        while (cx < tx) { move_one('D'); process_cell(); }\n        while (cx > tx) { move_one('U'); process_cell(); }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    h.resize(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    while (true) {\n        if (load == 0) {\n            int si = -1, sj = -1;\n            int best_score = INT_MIN;\n            \n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h[i][j] > 0) {\n                        int dist = abs(i - cx) + abs(j - cy);\n                        int path_work = best_path_work(cx, cy, i, j, 0);\n                        int target_amt = h[i][j];\n                        // Score: path work + target amount - distance penalty\n                        int score = path_work * 3 + target_amt - dist * 5;\n                        if (score > best_score) {\n                            best_score = score;\n                            si = i; sj = j;\n                        }\n                    }\n                }\n            }\n            \n            if (si == -1) break;\n            \n            move_to(si, sj);\n            if (h[cx][cy] > 0) do_load(h[cx][cy]);\n        } else {\n            int ti = -1, tj = -1;\n            int best_score = INT_MIN;\n            \n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (h[i][j] < 0) {\n                        int dist = abs(i - cx) + abs(j - cy);\n                        int path_work = best_path_work(cx, cy, i, j, load);\n                        int target_amt = -h[i][j];\n                        int score = path_work * 3 + min(target_amt, load) - dist * 5;\n                        if (score > best_score) {\n                            best_score = score;\n                            ti = i; tj = j;\n                        }\n                    }\n                }\n            }\n            \n            if (ti == -1) break;\n            \n            move_to(ti, tj);\n            if (h[cx][cy] < 0 && load > 0) {\n                do_unload(min(load, -h[cx][cy]));\n            }\n        }\n    }\n    \n    for (const auto& op : ops) {\n        cout << op << \"\\n\";\n    }\n    \n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \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, 0));\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    for (int t = 0; t < T; t++) {\n        vector<int> maxVal(M, 0);\n        for (int l = 0; l < M; l++) {\n            for (int i = 0; i < seed_count; i++) {\n                maxVal[l] = max(maxVal[l], X[i][l]);\n            }\n        }\n        \n        auto getValue = [&](int idx) {\n            int total = 0;\n            for (int l = 0; l < M; l++) total += X[idx][l];\n            return total;\n        };\n        \n        auto getMaxCount = [&](int idx) {\n            int cnt = 0;\n            for (int l = 0; l < M; l++) {\n                if (X[idx][l] == maxVal[l]) cnt++;\n            }\n            return cnt;\n        };\n        \n        // Calculate sum of max values that this seed has\n        auto getMaxSum = [&](int idx) {\n            int sum = 0;\n            for (int l = 0; l < M; l++) {\n                if (X[idx][l] == maxVal[l]) sum += X[idx][l];\n            }\n            return sum;\n        };\n        \n        // Selection: value + strong max bonus\n        vector<pair<double, int>> seed_scores(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            double score = getValue(i) + getMaxCount(i) * 1000.0;\n            seed_scores[i] = {score, i};\n        }\n        \n        sort(seed_scores.begin(), seed_scores.end(), greater<pair<double, int>>());\n        \n        vector<int> selected(N * N);\n        for (int i = 0; i < N * N; i++) {\n            selected[i] = seed_scores[i].second;\n        }\n        \n        // Placement: prioritize seeds with many max values and high maxSum\n        sort(selected.begin(), selected.end(), [&](int a, int b) {\n            // Primary: weighted score combining value and max importance\n            double sa = getValue(a) + getMaxCount(a) * 400.0 + getMaxSum(a) * 2.0;\n            double sb = getValue(b) + getMaxCount(b) * 400.0 + getMaxSum(b) * 2.0;\n            if (sa != sb) return sa > sb;\n            return getValue(a) > getValue(b);\n        });\n        \n        vector<pair<int, int>> pos_order;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                pos_order.push_back({i, j});\n            }\n        }\n        \n        double cx = (N - 1) / 2.0;\n        double cy = (N - 1) / 2.0;\n        sort(pos_order.begin(), pos_order.end(), [&](auto& a, auto& b) {\n            double da = abs(a.first - cx) + abs(a.second - cy);\n            double db = abs(b.first - cx) + abs(b.second - cy);\n            if (da != db) return da < db;\n            if (a.first != b.first) return a.first < b.first;\n            return a.second < b.second;\n        });\n        \n        vector<vector<int>> A(N, vector<int>(N, -1));\n        for (int i = 0; i < N * N; i++) {\n            A[pos_order[i].first][pos_order[i].second] = selected[i];\n        }\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << A[i][j];\n                if (j < N - 1) cout << \" \";\n                else cout << \"\\n\";\n            }\n        }\n        cout.flush();\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\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, V;\nconst int DX[] = {0, 1, 0, -1};\nconst int DY[] = {1, 0, -1, 0};\n\nint rx, ry;\nvector<int> dirs;\nvector<int> lens;\nvector<bool> holding;\nint numF;\n\npair<int,int> fingertip(int i) { \n    return {rx + DX[dirs[i]] * lens[i], ry + DY[dirs[i]] * lens[i]}; \n}\nbool valid(int x, int y) { return x >= 0 && x < N && y >= 0 && y < N; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> V;\n    vector<string> grid(N), target(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    for (int i = 0; i < N; i++) cin >> target[i];\n    \n    numF = V - 1;\n    \n    // Use varied edge lengths for better coverage\n    lens.resize(numF);\n    for (int i = 0; i < numF; i++) {\n        lens[i] = min(i + 1, N - 1);\n    }\n    \n    cout << numF + 1 << \"\\n\";\n    for (int i = 0; i < numF; i++) cout << \"0 \" << lens[i] << \"\\n\";\n    \n    // Calculate centroid for better starting position\n    set<pair<int,int>> pickup, dropS;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] == '1' && target[i][j] == '0') pickup.insert({i, j});\n            if (target[i][j] == '1' && grid[i][j] == '0') dropS.insert({i, j});\n        }\n    \n    int sumX = 0, sumY = 0, cnt = 0;\n    for (auto& p : pickup) { sumX += p.first; sumY += p.second; cnt++; }\n    for (auto& p : dropS) { sumX += p.first; sumY += p.second; cnt++; }\n    \n    rx = cnt > 0 ? sumX / cnt : N / 2;\n    ry = cnt > 0 ? sumY / cnt : N / 2;\n    rx = max(0, min(N - 1, rx));\n    ry = max(0, min(N - 1, ry));\n    \n    cout << rx << \" \" << ry << \"\\n\";\n    \n    dirs.assign(numF, 0);\n    holding.assign(numF, false);\n    \n    vector<string> ops;\n    \n    while (ops.size() < 95000 && (!pickup.empty() || !dropS.empty() || \n           any_of(holding.begin(), holding.end(), [](bool h){return h;}))) {\n        \n        vector<char> rot(numF, '.'), act(numF, '.');\n        bool acted = false;\n        \n        for (int i = 0; i < numF; i++) {\n            auto [fx, fy] = fingertip(i);\n            if (!valid(fx, fy)) continue;\n            if (!holding[i] && pickup.count({fx, fy})) {\n                act[i] = 'P'; pickup.erase({fx, fy}); holding[i] = true; acted = true;\n            } else if (holding[i] && dropS.count({fx, fy})) {\n                act[i] = 'P'; dropS.erase({fx, fy}); holding[i] = false; acted = true;\n            }\n        }\n        if (acted) {\n            string s = \".\";\n            for (int i = 0; i < numF; i++) s += '.';\n            s += '.';\n            for (int i = 0; i < numF; i++) s += act[i];\n            ops.push_back(s);\n            continue;\n        }\n        \n        int bestF = -1, bestDir = 0, bestCost = INT_MAX;\n        pair<int,int> bestTarget;\n        \n        for (int i = 0; i < numF; i++) {\n            auto& targets = holding[i] ? dropS : pickup;\n            if (targets.empty()) continue;\n            \n            for (auto& t : targets) {\n                for (int d = 0; d < 4; d++) {\n                    int nrx = t.first - DX[d] * lens[i];\n                    int nry = t.second - DY[d] * lens[i];\n                    if (!valid(nrx, nry)) continue;\n                    int diff = (d - dirs[i] + 4) % 4;\n                    int rotCost = min(diff, 4 - diff);\n                    int cost = abs(nrx - rx) + abs(nry - ry) + rotCost;\n                    if (cost < bestCost) {\n                        bestCost = cost; bestF = i;\n                        bestTarget = t; bestDir = d;\n                    }\n                }\n            }\n        }\n        \n        if (bestF == -1) break;\n        \n        int trx = bestTarget.first - DX[bestDir] * lens[bestF];\n        int tr_y = bestTarget.second - DY[bestDir] * lens[bestF];\n        char mv = '.';\n        \n        if (rx < trx && valid(rx + 1, ry)) { mv = 'D'; rx++; }\n        else if (rx > trx && valid(rx - 1, ry)) { mv = 'U'; rx--; }\n        else if (ry < tr_y && valid(rx, ry + 1)) { mv = 'R'; ry++; }\n        else if (ry > tr_y && valid(rx, ry - 1)) { mv = 'L'; ry--; }\n        \n        if (dirs[bestF] != bestDir) {\n            int diff = (bestDir - dirs[bestF] + 4) % 4;\n            if (diff == 1) { rot[bestF] = 'R'; dirs[bestF] = (dirs[bestF] + 1) % 4; }\n            else if (diff == 3) { rot[bestF] = 'L'; dirs[bestF] = (dirs[bestF] + 3) % 4; }\n            else { rot[bestF] = 'R'; dirs[bestF] = (dirs[bestF] + 1) % 4; }\n        }\n        \n        if (mv == '.' && rot[bestF] == '.') {\n            if (valid(rx + 1, ry)) { mv = 'D'; rx++; }\n            else if (valid(rx - 1, ry)) { mv = 'U'; rx--; }\n            else if (valid(rx, ry + 1)) { mv = 'R'; ry++; }\n            else if (valid(rx, ry - 1)) { mv = 'L'; ry--; }\n            else { rot[bestF] = 'R'; dirs[bestF] = (dirs[bestF] + 1) % 4; }\n        }\n        \n        string s; s += mv;\n        for (int i = 0; i < numF; i++) s += rot[i];\n        s += '.';\n        for (int i = 0; i < numF; i++) s += act[i];\n        ops.push_back(s);\n    }\n    \n    for (auto& op : ops) cout << op << \"\\n\";\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::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    for (int i = 0; i < N; i++) cin >> mackerel[i].first >> mackerel[i].second;\n    for (int i = 0; i < N; i++) cin >> sardine[i].first >> sardine[i].second;\n    \n    vector<int> xs, ys;\n    for (auto& p : mackerel) { xs.push_back(p.first); ys.push_back(p.second); }\n    for (auto& p : sardine) { xs.push_back(p.first); ys.push_back(p.second); }\n    \n    sort(xs.begin(), xs.end()); xs.erase(unique(xs.begin(), xs.end()), xs.end());\n    sort(ys.begin(), ys.end()); ys.erase(unique(ys.begin(), ys.end()), ys.end());\n    \n    int nx = xs.size(), ny = ys.size();\n    map<int, int> x_idx, y_idx;\n    for (int i = 0; i < nx; i++) x_idx[xs[i]] = i;\n    for (int i = 0; i < ny; i++) y_idx[ys[i]] = i;\n    \n    vector<vector<int>> grid(ny + 1, vector<int>(nx + 1, 0));\n    for (auto& p : mackerel) grid[y_idx[p.second] + 1][x_idx[p.first] + 1]++;\n    for (auto& p : sardine) grid[y_idx[p.second] + 1][x_idx[p.first] + 1]--;\n    for (int i = 1; i <= ny; i++)\n        for (int j = 1; j <= nx; j++)\n            grid[i][j] += grid[i-1][j] + grid[i][j-1] - grid[i-1][j-1];\n    \n    auto query = [&](int y1, int x1, int y2, int x2) -> int {\n        if (x1 > x2 || y1 > y2) return 0;\n        return grid[y2+1][x2+1] - grid[y1][x2+1] - grid[y2+1][x1] + grid[y1][x1];\n    };\n    \n    int best_score = 0, bx1 = 0, by1 = 0, bx2 = 0, by2 = 0;\n    mt19937 rng(42);\n    vector<tuple<int,int,int,int,int>> candidates;\n    \n    for (int iter = 0; iter < 500000; iter++) {\n        int i1 = rng() % N, i2 = rng() % N;\n        int x1i = x_idx[mackerel[i1].first], y1i = y_idx[mackerel[i1].second];\n        int x2i = x_idx[mackerel[i2].first], y2i = y_idx[mackerel[i2].second];\n        if (x1i > x2i) swap(x1i, x2i);\n        if (y1i > y2i) swap(y1i, y2i);\n        int score = query(y1i, x1i, y2i, x2i);\n        if (score > best_score - 100) candidates.push_back({score, x1i, y1i, x2i, y2i});\n        if (score > best_score) { best_score = score; bx1 = x1i; by1 = y1i; bx2 = x2i; by2 = y2i; }\n    }\n    \n    sort(candidates.rbegin(), candidates.rend());\n    if (candidates.size() > 80) candidates.resize(80);\n    \n    for (auto& [sc, cx1, cy1, cx2, cy2] : candidates) {\n        for (int round = 0; round < 3; round++) {\n            for (int x = 0; x <= cx2; x++) if (query(cy1, x, cy2, cx2) > query(cy1, cx1, cy2, cx2)) cx1 = x;\n            for (int x = cx1; x < nx; x++) if (query(cy1, cx1, cy2, x) > query(cy1, cx1, cy2, cx2)) cx2 = x;\n            for (int y = 0; y <= cy2; y++) if (query(y, cx1, cy2, cx2) > query(cy1, cx1, cy2, cx2)) cy1 = y;\n            for (int y = cy1; y < ny; y++) if (query(cy1, cx1, y, cx2) > query(cy1, cx1, cy2, cx2)) cy2 = y;\n        }\n        if (query(cy1, cx1, cy2, cx2) > best_score) {\n            best_score = query(cy1, cx1, cy2, cx2); bx1 = cx1; by1 = cy1; bx2 = cx2; by2 = cy2;\n        }\n    }\n    \n    int l_type = 0, lcx = 0, lcy = 0, l_score = best_score;\n    \n    for (int iter = 0; iter < 100000 && bx2 > bx1 + 1 && by2 > by1 + 1; iter++) {\n        int corner = rng() % 4;\n        int cx = bx1 + 1 + rng() % (bx2 - bx1 - 1);\n        int cy = by1 + 1 + rng() % (by2 - by1 - 1);\n        int cut = 0;\n        switch (corner) {\n            case 0: cut = query(by1, bx1, cy - 1, cx - 1); break;\n            case 1: cut = query(by1, cx + 1, cy - 1, bx2); break;\n            case 2: cut = query(cy + 1, cx + 1, by2, bx2); break;\n            case 3: cut = query(cy + 1, bx1, by2, cx - 1); break;\n        }\n        if (best_score - cut > l_score) { l_score = best_score - cut; l_type = corner + 1; lcx = cx; lcy = cy; }\n    }\n    \n    if (l_score <= 0) { cout << \"4\\n0 0\\n1 0\\n1 1\\n0 1\\n\"; return 0; }\n    \n    int ox1 = xs[bx1], oy1 = ys[by1], ox2 = xs[bx2], oy2 = ys[by2];\n    \n    if (l_type == 0) {\n        cout << \"4\\n\" << ox1 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy2 << \"\\n\" << ox1 << \" \" << oy2 << \"\\n\";\n    } else {\n        int ocx = xs[lcx], ocy = ys[lcy];\n        cout << \"6\\n\";\n        if (l_type == 1) cout << ocx << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy2 << \"\\n\" << ox1 << \" \" << oy2 << \"\\n\" << ox1 << \" \" << ocy << \"\\n\" << ocx << \" \" << ocy << \"\\n\";\n        else if (l_type == 2) cout << ox1 << \" \" << oy1 << \"\\n\" << ocx << \" \" << oy1 << \"\\n\" << ocx << \" \" << ocy << \"\\n\" << ox2 << \" \" << ocy << \"\\n\" << ox2 << \" \" << oy2 << \"\\n\" << ox1 << \" \" << oy2 << \"\\n\";\n        else if (l_type == 3) cout << ox1 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << ocy << \"\\n\" << ocx << \" \" << ocy << \"\\n\" << ocx << \" \" << oy2 << \"\\n\" << ox1 << \" \" << oy2 << \"\\n\";\n        else cout << ox1 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy2 << \"\\n\" << ocx << \" \" << oy2 << \"\\n\" << ocx << \" \" << ocy << \"\\n\" << ox1 << \" \" << ocy << \"\\n\";\n    }\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nlong long sigma;\nvector<long long> w, h;\n\nstruct PlacedRect { long long x1, y1, x2, y2; int id; };\n\npair<long long, long long> simulate(const vector<tuple<int,int,char,int>>& ops) {\n    vector<PlacedRect> placed;\n    long long W = 0, H = 0;\n    for (auto& [p, r, d, b] : ops) {\n        long long rw = w[p], rh = h[p];\n        if (r) swap(rw, rh);\n        long long x = 0, y = 0;\n        if (d == 'U') {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n            for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n        } else {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n            for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n        }\n        placed.push_back({x, y, x + rw, y + rh, p});\n        W = max(W, x + rw); H = max(H, y + rh);\n    }\n    return {W, H};\n}\n\nmt19937 rng(42);\n\nvector<tuple<int,int,char,int>> genGreedy(double wBias, int maxBase = 15) {\n    vector<tuple<int,int,char,int>> ops;\n    vector<PlacedRect> placed;\n    long long curW = 0, curH = 0;\n    \n    for (int i = 0; i < N; i++) {\n        double best = 1e18; \n        tuple<int,char,int> bc = {0,'U',-1};\n        \n        for (int r = 0; r < 2; r++) {\n            long long rw = w[i], rh = h[i]; \n            if (r) swap(rw, rh);\n            \n            for (char d : {'U','L'}) {\n                for (int b = -1; b < i; b++) {\n                    if (b >= 0 && i - b > maxBase) continue;\n                    \n                    long long x = 0, y = 0;\n                    if (d == 'U') {\n                        if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n                        for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n                    } else {\n                        if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n                        for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n                    }\n                    double sc = wBias * max(curW, x+rw) + max(curH, y+rh);\n                    if (sc < best) { best = sc; bc = {r, d, b}; }\n                }\n            }\n        }\n        \n        auto [r, d, b] = bc;\n        long long rw = w[i], rh = h[i]; if (r) swap(rw, rh);\n        long long x = 0, y = 0;\n        if (d == 'U') {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n            for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n        } else {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n            for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n        }\n        placed.push_back({x, y, x+rw, y+rh, i}); \n        curW = max(curW, x+rw); curH = max(curH, y+rh);\n        ops.push_back({i, r, d, b});\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> genShelf(double widthFactor, int rotMode) {\n    long long totalArea = 0;\n    for (int i = 0; i < N; i++) totalArea += w[i] * h[i];\n    long long targetW = max(1LL, (long long)(sqrt((double)totalArea) * widthFactor));\n    \n    vector<tuple<int,int,char,int>> ops;\n    long long curX = 0;\n    int lastInShelf = -1, shelfStart = -1;\n    \n    for (int i = 0; i < N; i++) {\n        int r = (rotMode == 0) ? 0 : (rotMode == 1) ? 1 : (h[i] > w[i] ? 1 : 0);\n        long long rw = w[i], rh = h[i]; if (r) swap(rw, rh);\n        \n        if (curX + rw > targetW && lastInShelf >= 0) {\n            ops.push_back({i, r, 'L', shelfStart});\n            shelfStart = i; curX = rw; lastInShelf = i;\n        } else {\n            if (lastInShelf < 0) {\n                ops.push_back({i, r, 'U', -1});\n                shelfStart = i;\n            } else {\n                ops.push_back({i, r, 'U', lastInShelf});\n            }\n            curX += rw; lastInShelf = i;\n        }\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> genStrip(char dir, int rotMode) {\n    vector<tuple<int,int,char,int>> ops;\n    for (int i = 0; i < N; i++) {\n        int r = (rotMode == 0) ? 0 : (rotMode == 1) ? 1 : \n                ((dir == 'U') ? (w[i] < h[i] ? 1 : 0) : (h[i] < w[i] ? 1 : 0));\n        ops.push_back({i, r, dir, -1});\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> mutate(vector<tuple<int,int,char,int>> ops, int intensity) {\n    int numMut = 1 + rng() % (intensity + 1);\n    for (int m = 0; m < numMut; m++) {\n        int i = rng() % N;\n        auto& [p, r, d, b] = ops[i];\n        int choice = rng() % 3;\n        if (choice == 0) r = 1 - r;\n        else if (choice == 1) d = (d == 'U') ? 'L' : 'U';\n        else if (i > 0) b = (int)(rng() % (i + 1)) - 1;\n    }\n    return ops;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> T >> sigma;\n    w.resize(N); h.resize(N);\n    for (int i = 0; i < N; i++) cin >> w[i] >> h[i];\n    \n    auto startTime = chrono::steady_clock::now();\n    vector<pair<long long, vector<tuple<int,int,char,int>>>> candidates;\n    \n    auto addCandidate = [&](vector<tuple<int,int,char,int>> ops) {\n        auto [sw, sh] = simulate(ops);\n        candidates.push_back({sw + sh, ops});\n    };\n    \n    // Diverse greedy with different biases\n    for (double bias : {0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.5, 2.0}) {\n        addCandidate(genGreedy(bias));\n    }\n    \n    // Shelf packing with different widths\n    for (double wf : {0.6, 0.8, 1.0, 1.2, 1.5, 2.0}) {\n        for (int rm = 0; rm < 3; rm++) {\n            addCandidate(genShelf(wf, rm));\n        }\n    }\n    \n    // Strip packing\n    for (char d : {'U', 'L'}) {\n        for (int rm = 0; rm < 3; rm++) {\n            addCandidate(genStrip(d, rm));\n        }\n    }\n    \n    sort(candidates.begin(), candidates.end());\n    auto bestOps = candidates[0].second;\n    long long bestSim = candidates[0].first;\n    \n    // Hill climbing with time limit\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - startTime).count() > 2500) break;\n        if ((int)candidates.size() >= T * 3) break;\n        \n        int srcIdx = (rng() % 100 < 70) ? 0 : rng() % min((int)candidates.size(), 10);\n        int intensity = 1 + (rng() % 3);\n        auto ops = mutate(candidates[srcIdx].second, intensity);\n        auto [sw, sh] = simulate(ops);\n        \n        if (sw + sh <= bestSim * 1.05) {\n            candidates.push_back({sw + sh, ops});\n            if (sw + sh < bestSim) { \n                bestSim = sw + sh; \n                bestOps = ops;\n            }\n        }\n    }\n    \n    sort(candidates.begin(), candidates.end());\n    \n    // Remove duplicates\n    vector<pair<long long, vector<tuple<int,int,char,int>>>> unique_cands;\n    set<vector<tuple<int,int,char,int>>> seen;\n    for (auto& c : candidates) {\n        if (seen.find(c.second) == seen.end()) {\n            seen.insert(c.second);\n            unique_cands.push_back(c);\n        }\n        if ((int)unique_cands.size() >= T) break;\n    }\n    candidates = unique_cands;\n    \n    // Fill remaining slots\n    while ((int)candidates.size() < T) {\n        auto ops = mutate(bestOps, 2);\n        auto [sw, sh] = simulate(ops);\n        candidates.push_back({sw + sh, ops});\n    }\n    \n    sort(candidates.begin(), candidates.end());\n    \n    for (int t = 0; t < T; t++) {\n        auto& ops = candidates[t].second;\n        cout << ops.size() << \"\\n\";\n        for (auto& [p, r, d, b] : ops) cout << p << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        cout.flush();\n        long long W, H; 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<int> parent_arr;\nvector<int> depth_arr;\nvector<vector<int>> children;\nvector<int> sub_h;\n\nlong long compute_score() {\n    long long score = 0;\n    for (int i = 0; i < N; i++) {\n        score += (long long)(depth_arr[i] + 1) * A[i];\n    }\n    return score;\n}\n\nvoid rebuild_all() {\n    for (int i = 0; i < N; i++) children[i].clear();\n    for (int i = 0; i < N; i++) {\n        if (parent_arr[i] != -1) {\n            children[parent_arr[i]].push_back(i);\n        }\n    }\n    \n    fill(depth_arr.begin(), depth_arr.end(), -1);\n    queue<int> q;\n    for (int i = 0; i < N; i++) {\n        if (parent_arr[i] == -1) {\n            depth_arr[i] = 0;\n            q.push(i);\n        }\n    }\n    while (!q.empty()) {\n        int u = q.front(); q.pop();\n        for (int c : children[u]) {\n            depth_arr[c] = depth_arr[u] + 1;\n            q.push(c);\n        }\n    }\n    \n    function<int(int)> calc = [&](int v) -> int {\n        int h = 0;\n        for (int c : children[v]) h = max(h, 1 + calc(c));\n        return sub_h[v] = h;\n    };\n    for (int i = 0; i < N; i++) {\n        if (parent_arr[i] == -1) calc(i);\n    }\n}\n\nvoid dfs(int u) {\n    vector<pair<int, int>> neighbors;\n    for (int v : adj[u]) {\n        if (depth_arr[v] == -1) {\n            neighbors.push_back({-A[v], v});\n        }\n    }\n    sort(neighbors.begin(), neighbors.end());\n    \n    for (auto& [neg_beauty, v] : neighbors) {\n        if (depth_arr[v] == -1 && depth_arr[u] < H) {\n            parent_arr[v] = u;\n            depth_arr[v] = depth_arr[u] + 1;\n            dfs(v);\n        }\n    }\n}\n\nbool is_ancestor(int anc, int desc) {\n    while (desc != -1) {\n        if (desc == anc) return true;\n        desc = parent_arr[desc];\n    }\n    return false;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    auto start_time = chrono::steady_clock::now();\n    auto elapsed = [&]() {\n        return chrono::duration_cast<chrono::milliseconds>(\n            chrono::steady_clock::now() - start_time).count();\n    };\n    \n    cin >> N >> M >> H;\n    \n    A.resize(N);\n    for (int i = 0; i < N; i++) cin >> A[i];\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    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    parent_arr.resize(N);\n    depth_arr.resize(N);\n    children.resize(N);\n    sub_h.resize(N);\n    \n    vector<int> best_parent(N, -1);\n    long long best_score = 0;\n    \n    mt19937 rng(54321);\n    \n    // Multiple restarts\n    for (int trial = 0; trial < 300 && elapsed() < 600; trial++) {\n        fill(parent_arr.begin(), parent_arr.end(), -1);\n        fill(depth_arr.begin(), depth_arr.end(), -1);\n        \n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        \n        if (trial == 0) {\n            sort(order.begin(), order.end(), [&](int a, int b) { return A[a] < A[b]; });\n        } else if (trial == 1) {\n            sort(order.begin(), order.end(), [&](int a, int b) { return adj[a].size() < adj[b].size(); });\n        } else {\n            vector<int> keys(N);\n            for (int i = 0; i < N; i++) keys[i] = A[i] + (rng() % 80);\n            sort(order.begin(), order.end(), [&](int a, int b) { return keys[a] < keys[b]; });\n        }\n        \n        for (int start : order) {\n            if (depth_arr[start] != -1) continue;\n            depth_arr[start] = 0;\n            parent_arr[start] = -1;\n            dfs(start);\n        }\n        \n        long long score = compute_score();\n        if (score > best_score) {\n            best_score = score;\n            best_parent = parent_arr;\n        }\n    }\n    \n    parent_arr = best_parent;\n    rebuild_all();\n    best_score = compute_score();\n    \n    // Local search with multiple strategies\n    for (int phase = 0; phase < 10 && elapsed() < 1850; phase++) {\n        vector<int> vorder(N);\n        iota(vorder.begin(), vorder.end(), 0);\n        \n        if (phase % 3 == 0) {\n            sort(vorder.begin(), vorder.end(), [&](int a, int b) { return A[a] > A[b]; });\n        } else if (phase % 3 == 1) {\n            sort(vorder.begin(), vorder.end(), [&](int a, int b) { return depth_arr[a] < depth_arr[b]; });\n        } else {\n            shuffle(vorder.begin(), vorder.end(), rng);\n        }\n        \n        bool improved = true;\n        while (improved && elapsed() < 1850) {\n            improved = false;\n            \n            for (int v : vorder) {\n                if (elapsed() > 1850) break;\n                \n                int cur_depth = depth_arr[v];\n                int best_new_parent = -1;\n                int best_gain = 0;\n                \n                for (int u : adj[v]) {\n                    if (u == parent_arr[v]) continue;\n                    if (is_ancestor(v, u)) continue;\n                    \n                    int new_depth = depth_arr[u] + 1;\n                    if (new_depth + sub_h[v] <= H) {\n                        int gain = (new_depth - cur_depth) * A[v];\n                        // Also account for descendants\n                        function<int(int, int)> desc_gain = [&](int node, int delta) -> int {\n                            int g = delta * A[node];\n                            for (int c : children[node]) g += desc_gain(c, delta);\n                            return g;\n                        };\n                        int total_gain = desc_gain(v, new_depth - cur_depth);\n                        \n                        if (total_gain > best_gain) {\n                            best_gain = total_gain;\n                            best_new_parent = u;\n                        }\n                    }\n                }\n                \n                if (best_new_parent != -1) {\n                    parent_arr[v] = best_new_parent;\n                    rebuild_all();\n                    improved = true;\n                }\n            }\n        }\n        \n        long long cur_score = compute_score();\n        if (cur_score > best_score) {\n            best_score = cur_score;\n            best_parent = parent_arr;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) {\n        cout << best_parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nint oni_r[50], oni_c[50];\nint valid_cnt[50], valid[50][4], dist[50][4];\nint asgn[50], batch_max[80];\n\ninline int get_key(int k, int d) { return d * 20 + ((d <= 1) ? oni_c[k] : oni_r[k]); }\n\nint full_cost() {\n    memset(batch_max, 0, sizeof(batch_max));\n    for (int k = 0; k < M; k++) {\n        int key = get_key(k, asgn[k]);\n        batch_max[key] = max(batch_max[key], dist[k][asgn[k]]);\n    }\n    int t = 0; for (int i = 0; i < 80; i++) t += batch_max[i];\n    return 2 * t;\n}\n\nint try_change(int k, int new_d) {\n    int old_d = asgn[k];\n    if (old_d == new_d) return 0;\n    int old_key = get_key(k, old_d), new_key = get_key(k, new_d);\n    int old_cost = 2 * (batch_max[old_key] + batch_max[new_key]);\n    \n    int new_old_max = 0;\n    for (int i = 0; i < M; i++) if (i != k && get_key(i, asgn[i]) == old_key)\n        new_old_max = max(new_old_max, dist[i][asgn[i]]);\n    int new_new_max = max(batch_max[new_key], dist[k][new_d]);\n    \n    return 2 * (new_old_max + new_new_max) - old_cost;\n}\n\nvoid apply_change(int k, int new_d) {\n    int old_key = get_key(k, asgn[k]), new_key = get_key(k, new_d);\n    asgn[k] = new_d;\n    int new_old_max = 0;\n    for (int i = 0; i < M; i++) if (get_key(i, asgn[i]) == old_key)\n        new_old_max = max(new_old_max, dist[i][asgn[i]]);\n    batch_max[old_key] = new_old_max;\n    batch_max[new_key] = max(batch_max[new_key], dist[k][new_d]);\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n    auto start = chrono::steady_clock::now();\n    auto elapsed = [&]() { return chrono::duration<double>(chrono::steady_clock::now() - start).count(); };\n    \n    cin >> N;\n    vector<string> board(N);\n    for (int i = 0; i < N; i++) cin >> board[i];\n    \n    for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (board[i][j] == 'x') {\n        oni_r[M] = i; oni_c[M] = j; M++;\n    }\n    \n    for (int k = 0; k < M; k++) {\n        int r = oni_r[k], c = oni_c[k];\n        bool ok = true; for (int i = 0; i < r && ok; i++) if (board[i][c] == 'o') ok = false;\n        if (ok) { valid[k][valid_cnt[k]] = 0; dist[k][0] = r + 1; valid_cnt[k]++; }\n        ok = true; for (int i = r+1; i < N && ok; i++) if (board[i][c] == 'o') ok = false;\n        if (ok) { valid[k][valid_cnt[k]] = 1; dist[k][1] = N - r; valid_cnt[k]++; }\n        ok = true; for (int j = 0; j < c && ok; j++) if (board[r][j] == 'o') ok = false;\n        if (ok) { valid[k][valid_cnt[k]] = 2; dist[k][2] = c + 1; valid_cnt[k]++; }\n        ok = true; for (int j = c+1; j < N && ok; j++) if (board[r][j] == 'o') ok = false;\n        if (ok) { valid[k][valid_cnt[k]] = 3; dist[k][3] = N - c; valid_cnt[k]++; }\n    }\n    \n    mt19937 rng(42);\n    int best_asgn[50], best_cost = INT_MAX;\n    \n    auto local_search = [&]() {\n        int cur = full_cost();\n        for (int it = 0; it < 30; it++) {\n            bool imp = false;\n            for (int k = 0; k < M; k++) for (int vi = 0; vi < valid_cnt[k]; vi++) {\n                int d = valid[k][vi]; if (d == asgn[k]) continue;\n                int delta = try_change(k, d);\n                if (delta < 0) { apply_change(k, d); cur += delta; imp = true; }\n            }\n            if (!imp) break;\n        }\n        if (cur < best_cost) { best_cost = cur; memcpy(best_asgn, asgn, sizeof(asgn)); }\n    };\n    \n    // Initial: minimum individual distance\n    for (int k = 0; k < M; k++) {\n        int bd = valid[k][0];\n        for (int vi = 0; vi < valid_cnt[k]; vi++) if (dist[k][valid[k][vi]] < dist[k][bd]) bd = valid[k][vi];\n        asgn[k] = bd;\n    }\n    local_search();\n    \n    // Prefer each direction\n    for (int p = 0; p < 4; p++) {\n        for (int k = 0; k < M; k++) {\n            asgn[k] = valid[k][0];\n            for (int vi = 0; vi < valid_cnt[k]; vi++) if (valid[k][vi] == p) { asgn[k] = p; break; }\n        }\n        local_search();\n    }\n    \n    // Greedy incremental\n    vector<int> order(M); iota(order.begin(), order.end(), 0);\n    for (int t = 0; t < 30 && elapsed() < 0.3; t++) {\n        shuffle(order.begin(), order.end(), rng);\n        memset(asgn, -1, sizeof(asgn)); memset(batch_max, 0, sizeof(batch_max));\n        for (int k : order) {\n            int bd = valid[k][0], bc = INT_MAX;\n            for (int vi = 0; vi < valid_cnt[k]; vi++) {\n                int d = valid[k][vi], key = get_key(k, d);\n                int add = max(0, dist[k][d] - batch_max[key]);\n                if (add < bc) { bc = add; bd = d; }\n            }\n            asgn[k] = bd; batch_max[get_key(k, bd)] = max(batch_max[get_key(k, bd)], dist[k][bd]);\n        }\n        local_search();\n    }\n    \n    // SA with restarts\n    memcpy(asgn, best_asgn, sizeof(asgn)); full_cost();\n    int cur_cost = best_cost;\n    double temp = 10.0;\n    int no_improve = 0;\n    while (elapsed() < 1.9) {\n        int k = rng() % M;\n        if (valid_cnt[k] <= 1) continue;\n        int new_d = valid[k][rng() % valid_cnt[k]];\n        if (new_d == asgn[k]) continue;\n        int delta = try_change(k, new_d);\n        if (delta < 0 || (rng() % 10000) < 10000 * exp(-delta / temp)) {\n            apply_change(k, new_d); cur_cost += delta;\n            if (cur_cost < best_cost) { best_cost = cur_cost; memcpy(best_asgn, asgn, sizeof(asgn)); no_improve = 0; }\n            else no_improve++;\n        } else no_improve++;\n        temp *= 0.999995;\n        if (no_improve > 50000) { memcpy(asgn, best_asgn, sizeof(asgn)); full_cost(); cur_cost = best_cost; temp = 5.0; no_improve = 0; }\n    }\n    \n    map<int, int> batches;\n    for (int k = 0; k < M; k++) batches[get_key(k, best_asgn[k])] = max(batches[get_key(k, best_asgn[k])], dist[k][best_asgn[k]]);\n    \n    for (auto& [key, mx] : batches) {\n        int dir = key / 20, idx = key % 20;\n        char c1 = (dir == 0 ? 'U' : dir == 1 ? 'D' : dir == 2 ? 'L' : 'R');\n        char c2 = (dir == 0 ? 'D' : dir == 1 ? 'U' : dir == 2 ? 'R' : 'L');\n        for (int t = 0; t < mx; t++) cout << c1 << \" \" << idx << \"\\n\";\n        for (int t = 0; t < mx; t++) cout << c2 << \" \" << idx << \"\\n\";\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, L;\nvector<int> T;\n\nlong long simulate(const vector<int>& a, const vector<int>& b, vector<int>& t) {\n    fill(t.begin(), t.end(), 0);\n    int x = 0;\n    for (int week = 0; week < L; week++) {\n        t[x]++;\n        x = (t[x] & 1) ? a[x] : b[x];\n    }\n    long long error = 0;\n    for (int i = 0; i < N; i++) error += abs(t[i] - T[i]);\n    return error;\n}\n\nvoid runOptimization(mt19937& rng, const vector<int>& weighted, const vector<int>& sorted_idx,\n                     vector<int>& best_a, vector<int>& best_b, long long& global_best,\n                     double time_limit, chrono::steady_clock::time_point start) {\n    vector<int> t(N);\n    \n    for (int restart = 0; ; restart++) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > time_limit) break;\n        \n        vector<int> a(N), b(N);\n        \n        if (restart == 0) {\n            for (int i = 0; i < N; i++) {\n                a[sorted_idx[i]] = sorted_idx[(i + 1) % N];\n                b[sorted_idx[i]] = sorted_idx[(i + 1) % N];\n            }\n        } else if (restart == 1) {\n            for (int i = 0; i < N; i++) {\n                a[sorted_idx[i]] = sorted_idx[(i + 1) % N];\n                b[sorted_idx[i]] = sorted_idx[(i + 2) % N];\n            }\n        } else if (restart % 3 == 0 && global_best < LLONG_MAX) {\n            a = best_a; b = best_b;\n            for (int k = 0; k < N/4; k++) {\n                int idx = rng() % N;\n                a[idx] = weighted[rng() % weighted.size()];\n                b[idx] = weighted[rng() % weighted.size()];\n            }\n        } else {\n            for (int i = 0; i < N; i++) {\n                a[i] = weighted[rng() % weighted.size()];\n                b[i] = weighted[rng() % weighted.size()];\n            }\n        }\n        \n        long long cur_error = simulate(a, b, t);\n        long long local_best = cur_error;\n        vector<int> local_a = a, local_b = b;\n        \n        double restart_budget = min(0.25, (time_limit - elapsed) * 0.6);\n        double restart_start = elapsed;\n        \n        while (true) {\n            now = chrono::steady_clock::now();\n            elapsed = chrono::duration<double>(now - start).count();\n            if (elapsed > time_limit || elapsed - restart_start > restart_budget) break;\n            \n            double progress = (elapsed - restart_start) / restart_budget;\n            double temp = 2500.0 * pow(0.0001, progress);\n            \n            int i = rng() % N;\n            int old_a = a[i], old_b = b[i];\n            \n            int choice = rng() % 4;\n            if (choice == 0) a[i] = weighted[rng() % weighted.size()];\n            else if (choice == 1) b[i] = weighted[rng() % weighted.size()];\n            else if (choice == 2) a[i] = rng() % N;\n            else b[i] = rng() % N;\n            \n            long long new_error = simulate(a, b, t);\n            double delta = new_error - cur_error;\n            \n            if (delta <= 0 || exp(-delta / temp) > (rng() % 1000000) / 1000000.0) {\n                cur_error = new_error;\n                if (new_error < local_best) {\n                    local_best = new_error;\n                    local_a = a; local_b = b;\n                }\n            } else {\n                a[i] = old_a; b[i] = old_b;\n            }\n        }\n        \n        if (local_best < global_best) {\n            global_best = local_best;\n            best_a = local_a; best_b = local_b;\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> L;\n    T.resize(N);\n    for (int i = 0; i < N; i++) cin >> T[i];\n    \n    vector<int> weighted;\n    for (int i = 0; i < N; i++) {\n        int cnt = max(1, T[i] / 100);\n        for (int j = 0; j < cnt; j++) weighted.push_back(i);\n    }\n    \n    vector<int> sorted_idx(N);\n    iota(sorted_idx.begin(), sorted_idx.end(), 0);\n    sort(sorted_idx.begin(), sorted_idx.end(), [](int x, int y) { return T[x] > T[y]; });\n    \n    vector<int> best_a(N), best_b(N);\n    long long global_best = LLONG_MAX;\n    \n    auto start = chrono::steady_clock::now();\n    \n    vector<int> seeds = {12345, 67890, 11111, 99999};\n    for (int seed : seeds) {\n        mt19937 rng(seed);\n        runOptimization(rng, weighted, sorted_idx, best_a, best_b, global_best, 1.9, start);\n    }\n    \n    for (int i = 0; i < N; i++) cout << best_a[i] << \" \" << best_b[i] << \"\\n\";\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nint queries_used = 0;\nint Q_limit;\n\nvector<pair<int,int>> query(vector<int>& cities) {\n    if (queries_used >= Q_limit || cities.size() < 2) return {};\n    cout << \"? \" << cities.size();\n    for (int c : cities) cout << \" \" << c;\n    cout << endl;\n    \n    vector<pair<int,int>> edges;\n    for (size_t i = 0; i + 1 < cities.size(); i++) {\n        int a, b;\n        cin >> a >> b;\n        edges.emplace_back(a, b);\n    }\n    queries_used++;\n    return edges;\n}\n\ndouble estDist(double x1, double y1, double x2, double y2) {\n    double dx = x1 - x2, dy = y1 - y2;\n    return sqrt(dx*dx + dy*dy);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    Q_limit = Q;\n    \n    vector<int> G(M);\n    for (int i = 0; i < M; i++) cin >> G[i];\n    \n    vector<double> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        x[i] = (lx + rx) / 2.0;\n        y[i] = (ly + ry) / 2.0;\n    }\n    \n    // Greedy nearest-neighbor grouping\n    vector<bool> used(N, false);\n    vector<vector<int>> groups(M);\n    \n    vector<int> groupOrder(M);\n    iota(groupOrder.begin(), groupOrder.end(), 0);\n    sort(groupOrder.begin(), groupOrder.end(), [&](int a, int b) {\n        return G[a] > G[b];\n    });\n    \n    for (int gi : groupOrder) {\n        int g = G[gi];\n        double cx = 0, cy = 0;\n        int cnt = 0;\n        for (int i = 0; i < N; i++) {\n            if (!used[i]) { cx += x[i]; cy += y[i]; cnt++; }\n        }\n        if (cnt > 0) { cx /= cnt; cy /= cnt; }\n        \n        int start = -1;\n        double minD = 1e18;\n        for (int i = 0; i < N; i++) {\n            if (!used[i]) {\n                double d = estDist(x[i], y[i], cx, cy);\n                if (d < minD) { minD = d; start = i; }\n            }\n        }\n        \n        groups[gi].push_back(start);\n        used[start] = true;\n        \n        while ((int)groups[gi].size() < g) {\n            int best = -1;\n            double bestD = 1e18;\n            for (int i = 0; i < N; i++) {\n                if (used[i]) continue;\n                double minDistToGroup = 1e18;\n                for (int c : groups[gi]) {\n                    minDistToGroup = min(minDistToGroup, estDist(x[i], y[i], x[c], y[c]));\n                }\n                if (minDistToGroup < bestD) {\n                    bestD = minDistToGroup;\n                    best = i;\n                }\n            }\n            groups[gi].push_back(best);\n            used[best] = true;\n        }\n    }\n    \n    // Local TSP-like reordering within each group\n    for (int k = 0; k < M; k++) {\n        int g = groups[k].size();\n        if (g <= 2) continue;\n        \n        vector<int> ordered;\n        vector<bool> inOrder(g, false);\n        ordered.push_back(0);\n        inOrder[0] = true;\n        \n        while ((int)ordered.size() < g) {\n            int last = ordered.back();\n            int best = -1;\n            double bestD = 1e18;\n            for (int i = 0; i < g; i++) {\n                if (inOrder[i]) continue;\n                double d = estDist(x[groups[k][last]], y[groups[k][last]], \n                                   x[groups[k][i]], y[groups[k][i]]);\n                if (d < bestD) { bestD = d; best = i; }\n            }\n            ordered.push_back(best);\n            inOrder[best] = true;\n        }\n        \n        vector<int> newGroup(g);\n        for (int i = 0; i < g; i++) newGroup[i] = groups[k][ordered[i]];\n        groups[k] = newGroup;\n    }\n    \n    // Calculate total minimum queries needed\n    int totalMinQueries = 0;\n    for (int k = 0; k < M; k++) {\n        int g = groups[k].size();\n        if (g <= 1) continue;\n        else if (g <= L) totalMinQueries += 1;\n        else totalMinQueries += (g - 2) / (L - 1) + 1;\n    }\n    \n    vector<vector<pair<int,int>>> edges(M);\n    vector<vector<pair<int,int>>> all_edges_per_group(M);\n    \n    // First pass: ensure connectivity\n    for (int k = 0; k < M; k++) {\n        int g = groups[k].size();\n        if (g == 1) continue;\n        \n        if (g <= L && queries_used < Q) {\n            edges[k] = query(groups[k]);\n        } else {\n            int remainingBudget = Q - queries_used;\n            int remainingGroups = 0;\n            for (int j = k; j < M; j++) if (groups[j].size() > (size_t)L) remainingGroups++;\n            \n            int step = L - 1;\n            if (remainingBudget > totalMinQueries * 2 && remainingGroups > 0) {\n                step = max(1, (L - 1) / 2);\n            }\n            \n            // Main sliding window\n            for (int i = 0; i < g && queries_used < Q; i += step) {\n                int end = min(i + L, g);\n                if (end - i >= 2) {\n                    vector<int> subset(groups[k].begin() + i, groups[k].begin() + end);\n                    auto e = query(subset);\n                    all_edges_per_group[k].insert(all_edges_per_group[k].end(), e.begin(), e.end());\n                }\n                if (end >= g) break;\n            }\n            \n            // Second pass with offset\n            if (step > 1 && queries_used < Q && g > L) {\n                for (int i = step/2; i + 1 < g && queries_used < Q; i += step) {\n                    int end = min(i + L, g);\n                    if (end - i >= 2) {\n                        vector<int> subset(groups[k].begin() + i, groups[k].begin() + end);\n                        auto e = query(subset);\n                        all_edges_per_group[k].insert(all_edges_per_group[k].end(), e.begin(), e.end());\n                    }\n                    if (end >= g) break;\n                }\n            }\n            \n            // Build MST\n            map<int, int> city_to_local;\n            for (int i = 0; i < g; i++) city_to_local[groups[k][i]] = i;\n            \n            vector<int> parent(g);\n            iota(parent.begin(), parent.end(), 0);\n            function<int(int)> find = [&](int u) -> int {\n                return parent[u] == u ? u : parent[u] = find(parent[u]);\n            };\n            \n            auto& ae = all_edges_per_group[k];\n            sort(ae.begin(), ae.end(), [&](auto& a, auto& b) {\n                double da = estDist(x[a.first], y[a.first], x[a.second], y[a.second]);\n                double db = estDist(x[b.first], y[b.first], x[b.second], y[b.second]);\n                return da < db;\n            });\n            \n            for (auto& e : ae) {\n                int u = city_to_local[e.first];\n                int v = city_to_local[e.second];\n                if (find(u) != find(v)) {\n                    parent[find(u)] = find(v);\n                    edges[k].push_back(e);\n                }\n            }\n            \n            // Fallback\n            while ((int)edges[k].size() < g - 1) {\n                double best_dist = 1e18;\n                int best_u = -1, best_v = -1;\n                for (int i = 0; i < g; i++) {\n                    for (int j = i + 1; j < g; j++) {\n                        if (find(i) != find(j)) {\n                            double d = estDist(x[groups[k][i]], y[groups[k][i]], \n                                             x[groups[k][j]], y[groups[k][j]]);\n                            if (d < best_dist) {\n                                best_dist = d;\n                                best_u = i; best_v = j;\n                            }\n                        }\n                    }\n                }\n                if (best_u >= 0) {\n                    parent[find(best_u)] = find(best_v);\n                    edges[k].push_back({groups[k][best_u], groups[k][best_v]});\n                } else break;\n            }\n        }\n    }\n    \n    // Use remaining queries for large groups - random sampling\n    mt19937 rng(42);\n    vector<int> largeGroups;\n    for (int k = 0; k < M; k++) {\n        if ((int)groups[k].size() > L) largeGroups.push_back(k);\n    }\n    \n    while (queries_used < Q && !largeGroups.empty()) {\n        int k = largeGroups[rng() % largeGroups.size()];\n        int g = groups[k].size();\n        \n        // Sample L random cities\n        vector<int> indices(g);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), rng);\n        \n        vector<int> subset;\n        for (int i = 0; i < min(L, g); i++) {\n            subset.push_back(groups[k][indices[i]]);\n        }\n        \n        auto e = query(subset);\n        // Check if any edge improves our MST\n        for (auto& edge : e) {\n            bool found = false;\n            for (auto& existing : edges[k]) {\n                if ((existing.first == edge.first && existing.second == edge.second) ||\n                    (existing.first == edge.second && existing.second == edge.first)) {\n                    found = true;\n                    break;\n                }\n            }\n            if (!found) {\n                all_edges_per_group[k].push_back(edge);\n            }\n        }\n    }\n    \n    cout << \"!\" << endl;\n    for (int k = 0; k < M; k++) {\n        for (int c : groups[k]) cout << c << \" \";\n        cout << \"\\n\";\n        for (auto& e : edges[k]) {\n            cout << e.first << \" \" << e.second << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc046":"#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<pair<int, int>> targets(M);\n    for (int i = 0; i < M; i++) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n    \n    vector<string> actions;\n    int curR = targets[0].first, curC = targets[0].second;\n    \n    for (int i = 1; i < M; i++) {\n        int tR = targets[i].first, tC = targets[i].second;\n        \n        int moveCost = abs(tR - curR) + abs(tC - curC);\n        int bestCost = moveCost;\n        int bestStrategy = 0;\n        \n        // Edge target strategies (1-4)\n        if (tR == 0 && curR > 0) {\n            int cost = abs(tC - curC) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 1; }\n        }\n        if (tR == N - 1 && curR < N - 1) {\n            int cost = abs(tC - curC) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 2; }\n        }\n        if (tC == 0 && curC > 0) {\n            int cost = abs(tR - curR) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 3; }\n        }\n        if (tC == N - 1 && curC < N - 1) {\n            int cost = abs(tR - curR) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 4; }\n        }\n        \n        // Slide-first strategies (5-8)\n        if (curR > 0) {\n            int cost = 1 + tR + abs(tC - curC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 5; }\n        }\n        if (curR < N - 1) {\n            int cost = 1 + (N - 1 - tR) + abs(tC - curC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 6; }\n        }\n        if (curC > 0) {\n            int cost = 1 + tC + abs(tR - curR);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 7; }\n        }\n        if (curC < N - 1) {\n            int cost = 1 + (N - 1 - tC) + abs(tR - curR);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 8; }\n        }\n        \n        // Double-slide to corners (9-12)\n        if (curR > 0 && curC > 0) { // to (0,0)\n            int cost = 2 + tR + tC;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 9; }\n        }\n        if (curR > 0 && curC < N - 1) { // to (0, N-1)\n            int cost = 2 + tR + (N - 1 - tC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 10; }\n        }\n        if (curR < N - 1 && curC > 0) { // to (N-1, 0)\n            int cost = 2 + (N - 1 - tR) + tC;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 11; }\n        }\n        if (curR < N - 1 && curC < N - 1) { // to (N-1, N-1)\n            int cost = 2 + (N - 1 - tR) + (N - 1 - tC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 12; }\n        }\n        \n        switch (bestStrategy) {\n            case 0:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                break;\n            case 1: case 2: case 3: case 4:\n                if (bestStrategy <= 2) {\n                    while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                    while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                    actions.push_back(bestStrategy == 1 ? \"S U\" : \"S D\");\n                    curR = (bestStrategy == 1) ? 0 : N - 1;\n                } else {\n                    while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                    while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                    actions.push_back(bestStrategy == 3 ? \"S L\" : \"S R\");\n                    curC = (bestStrategy == 3) ? 0 : N - 1;\n                }\n                break;\n            case 5: actions.push_back(\"S U\"); curR = 0; goto moveToTarget;\n            case 6: actions.push_back(\"S D\"); curR = N - 1; goto moveToTarget;\n            case 7: actions.push_back(\"S L\"); curC = 0; goto moveToTarget;\n            case 8: actions.push_back(\"S R\"); curC = N - 1; goto moveToTarget;\n            case 9: actions.push_back(\"S U\"); curR = 0; actions.push_back(\"S L\"); curC = 0; goto moveToTarget;\n            case 10: actions.push_back(\"S U\"); curR = 0; actions.push_back(\"S R\"); curC = N - 1; goto moveToTarget;\n            case 11: actions.push_back(\"S D\"); curR = N - 1; actions.push_back(\"S L\"); curC = 0; goto moveToTarget;\n            case 12: actions.push_back(\"S D\"); curR = N - 1; actions.push_back(\"S R\"); curC = N - 1; goto moveToTarget;\n            moveToTarget:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                break;\n        }\n    }\n    \n    for (const string& action : actions) {\n        cout << action << \"\\n\";\n    }\n    \n    return 0;\n}"},"16":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int W = 10000;\nint n;\nvector<int> px, py, rr;\nint a[201], b[201], c[201], d[201];\n\nbool canExpand(int i, int dir) {\n    int na = a[i], nb = b[i], nc = c[i], nd = d[i];\n    if (dir == 0) na--; else if (dir == 1) nc++; else if (dir == 2) nb--; else nd++;\n    if (na < 0 || nc > W || nb < 0 || nd > W) return false;\n    for (int j = 0; j < n; j++) {\n        if (i != j && !(nc <= a[j] || c[j] <= na || nd <= b[j] || d[j] <= nb)) return false;\n    }\n    return true;\n}\n\nvoid doExpand(int i, int dir) {\n    if (dir == 0) a[i]--; else if (dir == 1) c[i]++; else if (dir == 2) b[i]--; else d[i]++;\n}\n\nlong long area(int i) { return (long long)(c[i] - a[i]) * (d[i] - b[i]); }\n\ndouble score(int i) {\n    long long s = area(i);\n    double ratio = (double)min((long long)rr[i], s) / max((long long)rr[i], s);\n    return 1.0 - (1.0 - ratio) * (1.0 - ratio);\n}\n\ndouble totalScore() { double s = 0; for (int i = 0; i < n; i++) s += score(i); return s; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> n;\n    px.resize(n); py.resize(n); rr.resize(n);\n    for (int i = 0; i < n; i++) {\n        cin >> px[i] >> py[i] >> rr[i];\n        a[i] = px[i]; b[i] = py[i]; c[i] = px[i]+1; d[i] = py[i]+1;\n    }\n    \n    auto start = chrono::high_resolution_clock::now();\n    auto elapsed = [&]() {\n        return chrono::duration<double>(chrono::high_resolution_clock::now() - start).count();\n    };\n    \n    // Phase 1: Quick initial expansion up to target\n    while (elapsed() < 0.8) {\n        bool changed = false;\n        vector<int> order(n);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(), [&](int i, int j) {\n            return (double)(rr[i] - area(i)) / rr[i] > (double)(rr[j] - area(j)) / rr[j];\n        });\n        for (int i : order) {\n            if (area(i) >= rr[i]) continue;\n            for (int dir = 0; dir < 4; dir++) {\n                if (area(i) >= rr[i]) break;\n                if (canExpand(i, dir)) { doExpand(i, dir); changed = true; }\n            }\n        }\n        if (!changed) break;\n    }\n    \n    // Phase 2: Fill remaining space\n    while (elapsed() < 1.2) {\n        bool changed = false;\n        vector<int> order(n);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(), [&](int i, int j) { return rr[i] - area(i) > rr[j] - area(j); });\n        for (int i : order) {\n            for (int dir = 0; dir < 4; dir++)\n                if (canExpand(i, dir)) { doExpand(i, dir); changed = true; }\n        }\n        if (!changed) break;\n    }\n    \n    // Phase 3: Quick shrink-expand\n    for (int cycle = 0; cycle < 3 && elapsed() < 1.8; cycle++) {\n        for (int iter = 0; iter < 200; iter++) {\n            bool changed = false;\n            for (int i = 0; i < n; i++) {\n                if (area(i) <= rr[i]) continue;\n                for (int dir = 0; dir < 4; dir++) {\n                    int na = a[i], nb = b[i], nc = c[i], nd = d[i];\n                    if (dir == 0) na++; else if (dir == 1) nc--; else if (dir == 2) nb++; else nd--;\n                    if (na >= nc || nb >= nd) continue;\n                    if (!(na <= px[i] && px[i] < nc && nb <= py[i] && py[i] < nd)) continue;\n                    if ((long long)(nc - na) * (nd - nb) >= rr[i]) {\n                        a[i] = na; b[i] = nb; c[i] = nc; d[i] = nd; changed = true;\n                    }\n                }\n            }\n            if (!changed) break;\n        }\n        for (int iter = 0; iter < 200; iter++) {\n            bool changed = false;\n            for (int i = 0; i < n; i++) {\n                if (area(i) >= rr[i]) continue;\n                for (int dir = 0; dir < 4; dir++) if (canExpand(i, dir)) { doExpand(i, dir); changed = true; }\n            }\n            if (!changed) break;\n        }\n    }\n    \n    // Phase 4: Extended simulated annealing\n    mt19937 rng(42);\n    uniform_real_distribution<double> prob(0.0, 1.0);\n    vector<int> sa(n), sb(n), sc(n), sd(n);\n    double bestScore = totalScore();\n    vector<int> ba(n), bb(n), bc(n), bd(n);\n    for (int i = 0; i < n; i++) { ba[i] = a[i]; bb[i] = b[i]; bc[i] = c[i]; bd[i] = d[i]; }\n    \n    double startT = 0.05, endT = 0.001;\n    \n    while (elapsed() < 4.7) {\n        double progress = (elapsed() - 1.8) / (4.7 - 1.8);\n        double T = startT * pow(endT / startT, progress);\n        \n        for (int i = 0; i < n; i++) { sa[i] = a[i]; sb[i] = b[i]; sc[i] = c[i]; sd[i] = d[i]; }\n        double oldScore = totalScore();\n        \n        // Pick rectangle to shrink - prefer oversized\n        vector<pair<long long, int>> candidates;\n        for (int i = 0; i < n; i++) {\n            long long excess = area(i) - rr[i];\n            if (excess > -rr[i]/2) candidates.push_back({-excess, i}); // negative so oversized comes first\n        }\n        if (candidates.empty()) break;\n        sort(candidates.begin(), candidates.end());\n        \n        int pick = min((int)(prob(rng) * prob(rng) * candidates.size()), (int)candidates.size() - 1);\n        int idx = candidates[pick].second;\n        int dir = rng() % 4;\n        \n        int na = a[idx], nb = b[idx], nc = c[idx], nd = d[idx];\n        if (dir == 0) na++; else if (dir == 1) nc--; else if (dir == 2) nb++; else nd--;\n        if (na >= nc || nb >= nd || !(na <= px[idx] && px[idx] < nc && nb <= py[idx] && py[idx] < nd)) continue;\n        \n        a[idx] = na; b[idx] = nb; c[idx] = nc; d[idx] = nd;\n        \n        // Expand undersized neighbors\n        for (int it = 0; it < 30; it++) {\n            bool ch = false;\n            for (int i = 0; i < n; i++) {\n                if (area(i) >= rr[i]) continue;\n                for (int d = 0; d < 4; d++) if (canExpand(i, d)) { doExpand(i, d); ch = true; }\n            }\n            if (!ch) break;\n        }\n        \n        double newScore = totalScore();\n        if (newScore > oldScore || prob(rng) < exp((newScore - oldScore) / T)) {\n            if (newScore > bestScore) {\n                bestScore = newScore;\n                for (int i = 0; i < n; i++) { ba[i] = a[i]; bb[i] = b[i]; bc[i] = c[i]; bd[i] = d[i]; }\n            }\n        } else {\n            for (int i = 0; i < n; i++) { a[i] = sa[i]; b[i] = sb[i]; c[i] = sc[i]; d[i] = sd[i]; }\n        }\n    }\n    \n    for (int i = 0; i < n; i++) { a[i] = ba[i]; b[i] = bb[i]; c[i] = bc[i]; d[i] = bd[i]; }\n    \n    for (int i = 0; i < n; i++) {\n        cout << a[i] << \" \" << b[i] << \" \" << c[i] << \" \" << d[i] << \"\\n\";\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 50;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dc[] = {'U', 'D', 'L', 'R'};\n\nint t[N][N], p[N][N];\nint si, sj;\nmt19937 rng;\n\ninline int countMoves(int x, int y, const bitset<2500>& used, int curTile) {\n    int cnt = 0;\n    for (int d = 0; d < 4; d++) {\n        int nx = x + dx[d], ny = y + dy[d];\n        if (nx >= 0 && nx < N && ny >= 0 && ny < N && !used[t[nx][ny]] && t[nx][ny] != curTile) cnt++;\n    }\n    return cnt;\n}\n\ninline int countMoves2(int x, int y, const bitset<2500>& used, int curTile) {\n    int cnt = 0;\n    for (int d = 0; d < 4; d++) {\n        int nx = x + dx[d], ny = y + dy[d];\n        if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n        int tile = t[nx][ny];\n        if (used[tile] || tile == curTile) continue;\n        cnt++;\n        for (int d2 = 0; d2 < 4; d2++) {\n            int nnx = nx + dx[d2], nny = ny + dy[d2];\n            if (nnx >= 0 && nnx < N && nny >= 0 && nny < N && \n                !used[t[nnx][nny]] && t[nnx][nny] != tile && t[nnx][nny] != curTile) cnt++;\n        }\n    }\n    return cnt;\n}\n\nstruct State {\n    int x, y, score, priority;\n    bitset<2500> usedTiles;\n    string path;\n    bool operator<(const State& o) const { return priority < o.priority; }\n};\n\nvoid chokudaiSearch(int beamWidth, int moveWeight, int timeLimit,\n                    string& bestPath, int& bestScore, chrono::steady_clock::time_point startTime,\n                    bool use2Step = false) {\n    const int MAX_DEPTH = 2600;\n    vector<priority_queue<State>> queues(MAX_DEPTH);\n    \n    State init;\n    init.x = si; init.y = sj;\n    init.score = p[si][sj];\n    init.usedTiles.set(t[si][sj]);\n    init.path = \"\";\n    int fm = use2Step ? countMoves2(si, sj, init.usedTiles, -1) : countMoves(si, sj, init.usedTiles, -1);\n    init.priority = init.score + fm * moveWeight;\n    queues[0].push(init);\n    \n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() < timeLimit) {\n        for (int depth = 0; depth < MAX_DEPTH - 1; depth++) {\n            if (queues[depth].empty()) continue;\n            \n            for (int w = 0; w < beamWidth && !queues[depth].empty(); w++) {\n                State state = queues[depth].top();\n                queues[depth].pop();\n                \n                bool canExtend = false;\n                for (int d = 0; d < 4; d++) {\n                    int nx = state.x + dx[d];\n                    int ny = state.y + dy[d];\n                    if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n                    if (state.usedTiles[t[nx][ny]]) continue;\n                    \n                    canExtend = true;\n                    State newState;\n                    newState.x = nx; newState.y = ny;\n                    newState.score = state.score + p[nx][ny];\n                    newState.usedTiles = state.usedTiles;\n                    newState.usedTiles.set(t[nx][ny]);\n                    newState.path = state.path + dc[d];\n                    \n                    fm = use2Step ? countMoves2(nx, ny, newState.usedTiles, -1) : countMoves(nx, ny, newState.usedTiles, -1);\n                    newState.priority = newState.score + fm * moveWeight;\n                    queues[depth + 1].push(newState);\n                }\n                \n                if (!canExtend && state.score > bestScore) {\n                    bestScore = state.score;\n                    bestPath = state.path;\n                }\n            }\n            \n            while ((int)queues[depth + 1].size() > beamWidth * 2) {\n                queues[depth + 1].pop();\n            }\n        }\n    }\n    \n    for (int d = 0; d < MAX_DEPTH; d++) {\n        while (!queues[d].empty()) {\n            if (queues[d].top().score > bestScore) {\n                bestScore = queues[d].top().score;\n                bestPath = queues[d].top().path;\n            }\n            queues[d].pop();\n        }\n    }\n}\n\nvoid randomGreedy(string& bestPath, int& bestScore, int moveWeight, int randPercent) {\n    int x = si, y = sj;\n    int score = p[si][sj];\n    string path = \"\";\n    bitset<2500> usedTiles;\n    usedTiles.set(t[si][sj]);\n    \n    while (true) {\n        vector<pair<int, int>> moves;\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            if (usedTiles[t[nx][ny]]) continue;\n            int fm = countMoves(nx, ny, usedTiles, t[nx][ny]);\n            moves.push_back({p[nx][ny] + fm * moveWeight, d});\n        }\n        if (moves.empty()) break;\n        sort(moves.begin(), moves.end(), greater<pair<int,int>>());\n        \n        int choice = 0;\n        if (moves.size() > 1 && (int)(rng() % 100) < randPercent) {\n            choice = rng() % min((int)moves.size(), 3);\n        }\n        \n        int d = moves[choice].second;\n        x += dx[d]; y += dy[d];\n        score += p[x][y];\n        usedTiles.set(t[x][y]);\n        path += dc[d];\n    }\n    if (score > bestScore) {\n        bestScore = score;\n        bestPath = path;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    auto startTime = chrono::steady_clock::now();\n    rng.seed(chrono::steady_clock::now().time_since_epoch().count());\n    \n    cin >> si >> sj;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) cin >> t[i][j];\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) cin >> p[i][j];\n    \n    string bestPath = \"\";\n    int bestScore = p[si][sj];\n    \n    // 7 Chokudai configs - added 2-step pure score\n    chokudaiSearch(100, 0, 270, bestPath, bestScore, startTime);       // Pure score\n    chokudaiSearch(100, 50, 540, bestPath, bestScore, startTime);      // Light move\n    chokudaiSearch(100, 100, 810, bestPath, bestScore, startTime);     // Moderate\n    chokudaiSearch(80, 0, 1020, bestPath, bestScore, startTime, true); // 2-step pure score (NEW)\n    chokudaiSearch(80, 80, 1230, bestPath, bestScore, startTime, true);// 2-step moderate\n    chokudaiSearch(100, 150, 1440, bestPath, bestScore, startTime);    // Move heavy\n    chokudaiSearch(80, 120, 1650, bestPath, bestScore, startTime, true);// 2-step heavy\n    \n    // Random greedy with remaining time\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() < 1950) {\n        int moveW = 15 + rng() % 35;\n        int randP = 25 + rng() % 25;\n        randomGreedy(bestPath, bestScore, moveW, randP);\n    }\n    \n    cout << bestPath << endl;\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\ndouble h[N][N-1], v[N-1][N];\nint h_cnt[N][N-1], v_cnt[N-1][N];\ndouble g_sum = 0;\nint g_cnt = 0;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    fill(&h[0][0], &h[0][0] + N*(N-1), 5000.0);\n    fill(&v[0][0], &v[0][0] + (N-1)*N, 5000.0);\n    fill(&h_cnt[0][0], &h_cnt[0][0] + N*(N-1), 0);\n    fill(&v_cnt[0][0], &v_cnt[0][0] + (N-1)*N, 0);\n    \n    auto getH = [&](int i, int j) -> double {\n        if (h_cnt[i][j] > 0) return h[i][j];\n        double sum = 0, wgt = 0;\n        for (int k = 0; k < N-1; k++) {\n            if (h_cnt[i][k] > 0) {\n                double w = 1.0 / (1.0 + abs(j - k));\n                sum += h[i][k] * w;\n                wgt += w;\n            }\n        }\n        if (wgt > 0) return sum / wgt;\n        if (g_cnt > 0) return g_sum / g_cnt;\n        return 5000.0;\n    };\n    \n    auto getV = [&](int i, int j) -> double {\n        if (v_cnt[i][j] > 0) return v[i][j];\n        double sum = 0, wgt = 0;\n        for (int k = 0; k < N-1; k++) {\n            if (v_cnt[k][j] > 0) {\n                double w = 1.0 / (1.0 + abs(i - k));\n                sum += v[k][j] * w;\n                wgt += w;\n            }\n        }\n        if (wgt > 0) return sum / wgt;\n        if (g_cnt > 0) return g_sum / g_cnt;\n        return 5000.0;\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 idx = [](int i, int j) { return i * N + j; };\n        vector<double> dist(N*N, 1e18);\n        vector<int> prv(N*N, -1);\n        \n        priority_queue<pair<double,int>, vector<pair<double,int>>, greater<>> pq;\n        dist[idx(si, sj)] = 0;\n        pq.push({0, idx(si, sj)});\n        \n        while (!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if (d > dist[u]) continue;\n            int i = u / N, j = u % N;\n            \n            auto relax = [&](int ni, int nj, double w) {\n                int nu = idx(ni, nj);\n                if (dist[u] + w < dist[nu]) {\n                    dist[nu] = dist[u] + w;\n                    prv[nu] = u;\n                    pq.push({dist[nu], nu});\n                }\n            };\n            \n            if (i > 0) relax(i-1, j, getV(i-1, j));\n            if (i < N-1) relax(i+1, j, getV(i, j));\n            if (j > 0) relax(i, j-1, getH(i, j-1));\n            if (j < N-1) relax(i, j+1, getH(i, j));\n        }\n        \n        string path = \"\";\n        vector<tuple<int, int, int>> edges;\n        \n        int cur = idx(ti, tj);\n        while (prv[cur] != -1) {\n            int ci = cur / N, cj = cur % N;\n            int pi = prv[cur] / N, pj = prv[cur] % N;\n            \n            if (ci < pi) { path += 'U'; edges.emplace_back(1, ci, cj); }\n            else if (ci > pi) { path += 'D'; edges.emplace_back(1, pi, pj); }\n            else if (cj < pj) { path += 'L'; edges.emplace_back(0, ci, cj); }\n            else { path += 'R'; edges.emplace_back(0, pi, pj); }\n            \n            cur = prv[cur];\n        }\n        \n        reverse(path.begin(), path.end());\n        cout << path << \"\\n\" << flush;\n        \n        int feedback;\n        cin >> feedback;\n        \n        double est = 0;\n        for (auto& [t, ei, ej] : edges) {\n            est += (t == 0) ? getH(ei, ej) : getV(ei, ej);\n        }\n        \n        double ratio = feedback / est;\n        \n        for (auto& [t, ei, ej] : edges) {\n            double implied = (t == 0) ? getH(ei, ej) * ratio : getV(ei, ej) * ratio;\n            \n            if (t == 0) {\n                int cnt = ++h_cnt[ei][ej];\n                double alpha = 3.0 / (3.0 + cnt);\n                h[ei][ej] = h[ei][ej] * (1 - alpha) + implied * alpha;\n            } else {\n                int cnt = ++v_cnt[ei][ej];\n                double alpha = 3.0 / (3.0 + cnt);\n                v[ei][ej] = v[ei][ej] * (1 - alpha) + implied * alpha;\n            }\n        }\n        \n        g_sum = 0; g_cnt = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N-1; j++) {\n                if (h_cnt[i][j] > 0) { g_sum += h[i][j]; g_cnt++; }\n            }\n        }\n        for (int i = 0; i < N-1; i++) {\n            for (int j = 0; j < N; j++) {\n                if (v_cnt[i][j] > 0) { g_sum += v[i][j]; g_cnt++; }\n            }\n        }\n    }\n    \n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;\nint m;\nvector<string> strs;\n\nbool matchAt(const char grid[N][N], int idx, int r, int c, int d) {\n    const string& s = strs[idx];\n    for(int p = 0; p < (int)s.size(); p++) {\n        int ni = d ? (r+p)%N : r, nj = d ? c : (c+p)%N;\n        if(grid[ni][nj] != s[p]) return false;\n    }\n    return true;\n}\n\ntuple<int,int,int> findMatch(const char grid[N][N], int idx) {\n    for(int r = 0; r < N; r++)\n        for(int c = 0; c < N; c++) {\n            if(matchAt(grid, idx, r, c, 0)) return {r, c, 0};\n            if(matchAt(grid, idx, r, c, 1)) return {r, c, 1};\n        }\n    return {-1, -1, -1};\n}\n\nbool posContains(int r, int c, int d, int len, int i, int j) {\n    for(int p = 0; p < len; p++) {\n        int ni = d ? (r+p)%N : r, nj = d ? c : (c+p)%N;\n        if(ni == i && nj == j) return true;\n    }\n    return false;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n; cin >> n >> m;\n    strs.resize(m);\n    for(int i = 0; i < m; i++) cin >> strs[i];\n    \n    mt19937 rng(12345);\n    char bestGrid[N][N];\n    int bestScore = 0;\n    auto start = chrono::high_resolution_clock::now();\n    \n    for(int trial = 0; ; trial++) {\n        if(chrono::duration<double>(chrono::high_resolution_clock::now() - start).count() > 2.0) break;\n        \n        char grid[N][N]; fill(&grid[0][0], &grid[N][0], '.');\n        vector<int> order(m); iota(order.begin(), order.end(), 0);\n        if(trial % 3 == 0) sort(order.begin(), order.end(), [&](int a, int b) { return strs[a].size() > strs[b].size(); });\n        else { shuffle(order.begin(), order.end(), rng); if(trial % 3 == 1) stable_sort(order.begin(), order.end(), [&](int a, int b) { return strs[a].size() > strs[b].size(); }); }\n        \n        for(int idx : order) {\n            const string& s = strs[idx];\n            vector<tuple<int,int,int>> cands; int bestOv = -1;\n            for(int r = 0; r < N; r++) for(int c = 0; c < N; c++) for(int d = 0; d < 2; d++) {\n                bool can = true; int ov = 0;\n                for(int p = 0; p < (int)s.size(); p++) {\n                    int ni = d?(r+p)%N:r, nj = d?c:(c+p)%N;\n                    if(grid[ni][nj] != '.' && grid[ni][nj] != s[p]) { can = false; break; }\n                    if(grid[ni][nj] != '.') ov++;\n                }\n                if(can && ov >= bestOv) { if(ov > bestOv) { bestOv = ov; cands.clear(); } cands.push_back({r,c,d}); }\n            }\n            if(!cands.empty()) { auto [r,c,d] = cands[rng()%cands.size()]; for(int p = 0; p < (int)s.size(); p++) { int ni = d?(r+p)%N:r, nj = d?c:(c+p)%N; grid[ni][nj] = s[p]; } }\n        }\n        for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) if(grid[i][j] == '.') grid[i][j] = 'A' + rng()%8;\n        int score = 0; for(int i = 0; i < m; i++) if(get<0>(findMatch(grid, i)) >= 0) score++;\n        if(score > bestScore) { bestScore = score; memcpy(bestGrid, grid, sizeof(grid)); }\n    }\n    \n    char grid[N][N]; memcpy(grid, bestGrid, sizeof(grid));\n    vector<tuple<int,int,int>> matchPos(m);\n    for(int i = 0; i < m; i++) matchPos[i] = findMatch(grid, i);\n    int curScore = bestScore;\n    \n    while(true) {\n        double elapsed = chrono::duration<double>(chrono::high_resolution_clock::now() - start).count();\n        if(elapsed > 2.95) break;\n        double T = 1.5 * max(0.01, 1.0 - elapsed / 3.0);\n        \n        int ci = rng()%N, cj = rng()%N;\n        char old = grid[ci][cj];\n        \n        int bestDelta = -1000; char bestChar = old;\n        vector<pair<int, tuple<int,int,int>>> bestChanges;\n        \n        for(char nc = 'A'; nc <= 'H'; nc++) {\n            if(nc == old) continue;\n            grid[ci][cj] = nc;\n            int delta = 0;\n            vector<pair<int, tuple<int,int,int>>> changes;\n            \n            for(int idx = 0; idx < m; idx++) {\n                auto [r,c,d] = matchPos[idx];\n                int len = strs[idx].size();\n                if(r >= 0 && posContains(r, c, d, len, ci, cj)) {\n                    if(!matchAt(grid, idx, r, c, d)) {\n                        auto nm = findMatch(grid, idx);\n                        changes.push_back({idx, nm});\n                        if(get<0>(nm) < 0) delta--;\n                    }\n                } else if(r < 0) {\n                    for(int p = 0; p < len; p++) { int sc = (cj-p+N)%N; if(matchAt(grid,idx,ci,sc,0)) { delta++; changes.push_back({idx,{ci,sc,0}}); goto nx; } }\n                    for(int p = 0; p < len; p++) { int sr = (ci-p+N)%N; if(matchAt(grid,idx,sr,cj,1)) { delta++; changes.push_back({idx,{sr,cj,1}}); goto nx; } }\n                    nx:;\n                }\n            }\n            if(delta > bestDelta) { bestDelta = delta; bestChar = nc; bestChanges = changes; }\n        }\n        grid[ci][cj] = old;\n        \n        if(bestDelta >= 0 || (rng()&0xFFFF) < 65536.0 * exp(bestDelta / T)) {\n            grid[ci][cj] = bestChar;\n            curScore += bestDelta;\n            for(auto& [idx, pos] : bestChanges) matchPos[idx] = pos;\n            if(curScore > bestScore) { bestScore = curScore; memcpy(bestGrid, grid, sizeof(grid)); }\n        }\n    }\n    \n    for(int i = 0; i < N; i++) cout << string(bestGrid[i], bestGrid[i]+N) << '\\n';\n}","ahc005":"#include <bits/stdc++.h>\n#include <chrono>\nusing namespace std;\nusing namespace chrono;\n\nint N, si, sj;\nvector<string> grid;\n\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nconst char dir_char[] = {'U', 'D', 'L', 'R'};\n\ninline bool is_road(int i, int j) {\n    return i >= 0 && i < N && j >= 0 && j < N && grid[i][j] != '#';\n}\n\npair<vector<vector<int>>, vector<vector<pair<int,int>>>> dijkstra(int si, int sj) {\n    vector<vector<int>> dist(N, vector<int>(N, INT_MAX));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1,-1}));\n    priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;\n    dist[si][sj] = 0; pq.push({0, si, sj});\n    while (!pq.empty()) {\n        auto [d, i, j] = pq.top(); pq.pop();\n        if (d > dist[i][j]) continue;\n        for (int k = 0; k < 4; k++) {\n            int ni = i + dx[k], nj = j + dy[k];\n            if (is_road(ni, nj)) {\n                int c = grid[ni][nj] - '0';\n                if (dist[i][j] + c < dist[ni][nj]) {\n                    dist[ni][nj] = dist[i][j] + c;\n                    parent[ni][nj] = {i, j};\n                    pq.push({dist[ni][nj], ni, nj});\n                }\n            }\n        }\n    }\n    return {dist, parent};\n}\n\nstring get_path(int i1, int j1, int i2, int j2, vector<vector<pair<int,int>>>& parent) {\n    if (i1 == i2 && j1 == j2) return \"\";\n    string path;\n    int ci = i2, cj = j2;\n    while (ci != i1 || cj != j1) {\n        auto [pi, pj] = parent[ci][cj];\n        for (int k = 0; k < 4; k++) if (pi + dx[k] == ci && pj + dy[k] == cj) { path += dir_char[k]; break; }\n        ci = pi; cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nint calc_path_time(const string& path) {\n    int time = 0, ci = si, cj = sj;\n    for (char c : path) {\n        if (c == 'U') ci--; else if (c == 'D') ci++; else if (c == 'L') cj--; else cj++;\n        time += grid[ci][cj] - '0';\n    }\n    return time;\n}\n\nstring solve(double alpha, int check_limit) {\n    vector<vector<bool>> visible(N, vector<bool>(N, false));\n    vector<vector<int>> mark_iter(N, vector<int>(N, 0));\n    int current_iter = 0;\n    int visible_count = 0, total_roads = 0;\n    for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (is_road(i, j)) total_roads++;\n    \n    auto mark_visible = [&](int i, int j) {\n        if (!visible[i][j]) { visible[i][j] = true; visible_count++; }\n        for (int jj = j - 1; jj >= 0 && is_road(i, jj); jj--) if (!visible[i][jj]) { visible[i][jj] = true; visible_count++; }\n        for (int jj = j + 1; jj < N && is_road(i, jj); jj++) if (!visible[i][jj]) { visible[i][jj] = true; visible_count++; }\n        for (int ii = i - 1; ii >= 0 && is_road(ii, j); ii--) if (!visible[ii][j]) { visible[ii][j] = true; visible_count++; }\n        for (int ii = i + 1; ii < N && is_road(ii, j); ii++) if (!visible[ii][j]) { visible[ii][j] = true; visible_count++; }\n    };\n    \n    auto count_new_visible = [&](int i, int j) {\n        int cnt = !visible[i][j];\n        for (int jj = j - 1; jj >= 0 && is_road(i, jj); jj--) cnt += !visible[i][jj];\n        for (int jj = j + 1; jj < N && is_road(i, jj); jj++) cnt += !visible[i][jj];\n        for (int ii = i - 1; ii >= 0 && is_road(ii, j); ii--) cnt += !visible[ii][j];\n        for (int ii = i + 1; ii < N && is_road(ii, j); ii++) cnt += !visible[ii][j];\n        return cnt;\n    };\n    \n    auto calc_path_visibility = [&](int si, int sj, const string& path) {\n        current_iter++;\n        int cnt = 0, ci = si, cj = sj;\n        auto add_vis = [&](int i, int j) {\n            if (!visible[i][j] && mark_iter[i][j] != current_iter) {\n                mark_iter[i][j] = current_iter;\n                cnt++;\n            }\n        };\n        for (char c : path) {\n            if (c == 'U') ci--; else if (c == 'D') ci++; else if (c == 'L') cj--; else cj++;\n            add_vis(ci, cj);\n            for (int jj = cj - 1; jj >= 0 && is_road(ci, jj); jj--) add_vis(ci, jj);\n            for (int jj = cj + 1; jj < N && is_road(ci, jj); jj++) add_vis(ci, jj);\n            for (int ii = ci - 1; ii >= 0 && is_road(ii, cj); ii--) add_vis(ii, cj);\n            for (int ii = ci + 1; ii < N && is_road(ii, cj); ii++) add_vis(ii, cj);\n        }\n        return cnt;\n    };\n    \n    auto [dist_from_start, parent_from_start] = dijkstra(si, sj);\n    int cur_i = si, cur_j = sj;\n    string result;\n    mark_visible(cur_i, cur_j);\n    \n    while (visible_count < total_roads) {\n        auto [dist, parent] = dijkstra(cur_i, cur_j);\n        vector<tuple<double, int, int>> candidates;\n        for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) {\n            if (dist[i][j] == INT_MAX || dist[i][j] == 0) continue;\n            int nv = count_new_visible(i, j);\n            if (nv == 0) continue;\n            double cost = dist[i][j] + alpha * dist_from_start[i][j];\n            candidates.push_back({-(double)nv / cost, i, j});\n        }\n        if (candidates.empty()) break;\n        sort(candidates.begin(), candidates.end());\n        \n        int best_i = -1, best_j = -1; double best_score = -1e18; string best_path;\n        int check_count = min((int)candidates.size(), check_limit);\n        for (int c = 0; c < check_count; c++) {\n            auto [_, i, j] = candidates[c];\n            string path = get_path(cur_i, cur_j, i, j, parent);\n            double nv = (check_limit > 1) ? calc_path_visibility(cur_i, cur_j, path) : count_new_visible(i, j);\n            if (nv == 0) continue;\n            double cost = dist[i][j] + alpha * dist_from_start[i][j];\n            double score = nv / cost;\n            if (score > best_score) { best_score = score; best_i = i; best_j = j; best_path = path; }\n        }\n        if (best_i == -1) break;\n        result += best_path;\n        int ti = cur_i, tj = cur_j;\n        for (char c : best_path) {\n            if (c == 'U') ti--; else if (c == 'D') ti++; else if (c == 'L') tj--; else tj++;\n            mark_visible(ti, tj);\n        }\n        cur_i = best_i; cur_j = best_j;\n    }\n    if (cur_i != si || cur_j != sj) {\n        auto [dist, parent] = dijkstra(cur_i, cur_j);\n        result += get_path(cur_i, cur_j, si, sj, parent);\n    }\n    return result;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(nullptr);\n    auto start = steady_clock::now();\n    cin >> N >> si >> sj;\n    grid.resize(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    \n    string best_result; int best_time = INT_MAX;\n    vector<double> alphas;\n    for (int i = 0; i <= 50; i++) alphas.push_back(i * 0.01);\n    vector<int> check_limits = {1, 3, 6, 10, 15, 21, 28, 36, 45};\n    \n    for (double alpha : alphas) {\n        if (duration<double>(steady_clock::now() - start).count() > 2.7) break;\n        for (int cl : check_limits) {\n            string result = solve(alpha, cl);\n            int time = calc_path_time(result);\n            if (time < best_time) { best_time = time; best_result = result; }\n        }\n    }\n    cout << best_result << endl;\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    vector<vector<int>> deps(N), rdeps(N);\n    for (int i = 0; i < R; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        deps[v].push_back(u);\n        rdeps[u].push_back(v);\n    }\n    \n    vector<int> taskStatus(N, -1);\n    vector<int> memberTask(M, -1), memberStartDay(M, 0);\n    \n    double initSkill = 40.0 / sqrt(K);\n    vector<vector<double>> skillEst(M, vector<double>(K, initSkill));\n    vector<vector<double>> skillLo(M, vector<double>(K, 0.0));\n    \n    auto estimateTime = [&](int task, int member) -> double {\n        double w = 0;\n        for (int k = 0; k < K; k++)\n            w += max(0.0, (double)d[task][k] - skillEst[member][k]);\n        return max(1.0, w);\n    };\n    \n    auto avgTime = [&](int task) -> double {\n        double sum = 0;\n        for (int j = 0; j < M; j++) sum += estimateTime(task, j);\n        return sum / M;\n    };\n    \n    vector<int> downstream(N, 0);\n    for (int i = N - 1; i >= 0; i--) {\n        downstream[i] = (int)rdeps[i].size();\n        for (int v : rdeps[i]) downstream[i] += downstream[v];\n    }\n    \n    vector<double> wdepth(N);\n    auto recalcDepth = [&]() {\n        for (int i = N - 1; i >= 0; i--) {\n            if (taskStatus[i] == 1) { wdepth[i] = 0; continue; }\n            wdepth[i] = avgTime(i);\n            double maxChild = 0;\n            for (int v : rdeps[i]) maxChild = max(maxChild, wdepth[v]);\n            wdepth[i] += maxChild;\n        }\n    };\n    recalcDepth();\n    \n    for (int day = 1; ; day++) {\n        if (day % 25 == 1) recalcDepth();\n        \n        vector<int> availTasks;\n        for (int i = 0; i < N; i++) {\n            if (taskStatus[i] != -1) continue;\n            bool ok = true;\n            for (int dep : deps[i])\n                if (taskStatus[dep] != 1) { ok = false; break; }\n            if (ok) availTasks.push_back(i);\n        }\n        \n        vector<int> freeMembers;\n        for (int j = 0; j < M; j++)\n            if (memberTask[j] == -1) freeMembers.push_back(j);\n        \n        vector<tuple<double, int, int>> candidates;\n        for (int task : availTasks) {\n            for (int member : freeMembers) {\n                double t = estimateTime(task, member);\n                double score = wdepth[task] / max(1.0, t) + 0.001 * downstream[task];\n                candidates.push_back({-score, task, member});\n            }\n        }\n        sort(candidates.begin(), candidates.end());\n        \n        vector<pair<int, int>> assignments;\n        vector<bool> usedMember(M, false), usedTask(N, false);\n        \n        for (auto& [score, task, member] : candidates) {\n            if (usedMember[member] || usedTask[task]) continue;\n            usedMember[member] = true;\n            usedTask[task] = true;\n            assignments.push_back({member + 1, task + 1});\n            taskStatus[task] = 0;\n            memberTask[member] = task;\n            memberStartDay[member] = day;\n        }\n        \n        cout << assignments.size();\n        for (auto& [a, b] : assignments) cout << \" \" << a << \" \" << b;\n        cout << \"\\n\";\n        cout.flush();\n        \n        int n; cin >> n;\n        if (n == -1) break;\n        \n        for (int i = 0; i < n; i++) {\n            int f; cin >> f; f--;\n            int task = memberTask[f];\n            int timeTaken = day - memberStartDay[f] + 1;\n            taskStatus[task] = 1;\n            memberTask[f] = -1;\n            \n            if (timeTaken == 1) {\n                for (int k = 0; k < K; k++) {\n                    skillLo[f][k] = max(skillLo[f][k], (double)d[task][k]);\n                    skillEst[f][k] = max(skillEst[f][k], (double)d[task][k]);\n                }\n            } else {\n                double wEst = (double)timeTaken;\n                double currW = 0;\n                for (int k = 0; k < K; k++)\n                    currW += max(0.0, (double)d[task][k] - skillEst[f][k]);\n                \n                if (currW > 0.5) {\n                    double factor = wEst / currW;\n                    factor = 0.65 * factor + 0.35;\n                    factor = max(0.5, min(1.6, factor));\n                    \n                    for (int k = 0; k < K; k++) {\n                        double gap = d[task][k] - skillEst[f][k];\n                        if (gap > 0) {\n                            double newSkill = d[task][k] - gap * factor;\n                            skillEst[f][k] = max(skillLo[f][k], newSkill);\n                        }\n                    }\n                } else if (wEst > 4) {\n                    double totalReq = 0;\n                    for (int k = 0; k < K; k++) totalReq += d[task][k];\n                    if (totalReq > 0.5) {\n                        for (int k = 0; k < K; k++) {\n                            double reduction = (wEst - 2) * d[task][k] / totalReq;\n                            skillEst[f][k] = max(skillLo[f][k], skillEst[f][k] - reduction);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1000, M = 50, CX = 400, CY = 400;\nint ordA[N], ordB[N], ordC[N], ordD[N];\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\ninline int dist(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\nint buildRoute(const vector<int>& sel, vector<pair<int,bool>>& ev) {\n    ev.clear();\n    ev.reserve(2 * M);\n    bool picked[N] = {}, done[N] = {};\n    int cx = CX, cy = CY, cost = 0;\n    \n    for (int i = 0; i < 2*M; i++) {\n        int best = -1, bd = 1e9;\n        bool isDel = false;\n        for (int j : sel) {\n            if (!picked[j]) {\n                int d = dist(cx, cy, ordA[j], ordB[j]);\n                if (d < bd) { bd = d; best = j; isDel = false; }\n            } else if (!done[j]) {\n                int d = dist(cx, cy, ordC[j], ordD[j]);\n                if (d < bd) { bd = d; best = j; isDel = true; }\n            }\n        }\n        cost += bd;\n        if (isDel) { cx = ordC[best]; cy = ordD[best]; done[best] = true; }\n        else { cx = ordA[best]; cy = ordB[best]; picked[best] = true; }\n        ev.push_back({best, isDel});\n    }\n    return cost + dist(cx, cy, CX, CY);\n}\n\nint calcCost(const vector<pair<int,bool>>& ev) {\n    int cx = CX, cy = CY, cost = 0;\n    for (auto& [idx, isDel] : ev) {\n        int nx = isDel ? ordC[idx] : ordA[idx];\n        int ny = isDel ? ordD[idx] : ordB[idx];\n        cost += dist(cx, cy, nx, ny);\n        cx = nx; cy = ny;\n    }\n    return cost + dist(cx, cy, CX, CY);\n}\n\nbool validSwap(vector<pair<int,bool>>& ev, int i, int j) {\n    swap(ev[i], ev[j]);\n    int pickPos[N];\n    memset(pickPos, -1, sizeof(pickPos));\n    for (int k = 0; k < (int)ev.size(); k++) {\n        if (!ev[k].second) pickPos[ev[k].first] = k;\n        else if (pickPos[ev[k].first] < 0 || pickPos[ev[k].first] > k) {\n            swap(ev[i], ev[j]);\n            return false;\n        }\n    }\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    auto st = chrono::steady_clock::now();\n    for (int i = 0; i < N; i++) cin >> ordA[i] >> ordB[i] >> ordC[i] >> ordD[i];\n    \n    auto elapsed = [&]() {\n        return chrono::duration<double>(chrono::steady_clock::now() - st).count();\n    };\n    \n    vector<pair<int,int>> byDist(N);\n    for (int i = 0; i < N; i++) {\n        byDist[i] = {dist(CX, CY, ordA[i], ordB[i]) + dist(CX, CY, ordC[i], ordD[i]), i};\n    }\n    sort(byDist.begin(), byDist.end());\n    \n    vector<int> sel(M), unsel(N-M);\n    for (int i = 0; i < M; i++) sel[i] = byDist[i].second;\n    for (int i = 0; i < N-M; i++) unsel[i] = byDist[M+i].second;\n    \n    vector<pair<int,bool>> ev, bestEv;\n    int cost = buildRoute(sel, ev);\n    int bestCost = cost;\n    vector<int> bestSel = sel;\n    bestEv = ev;\n    \n    double temp = 3000.0;\n    \n    while (elapsed() < 1.8) {\n        int si = rng() % M;\n        int ui = rng() % (N-M);\n        swap(sel[si], unsel[ui]);\n        \n        int nc = buildRoute(sel, ev);\n        int delta = nc - cost;\n        \n        if (delta < 0 || (rng() % 10000) < 10000 * exp(-delta / temp)) {\n            cost = nc;\n            if (nc < bestCost) {\n                bestCost = nc;\n                bestSel = sel;\n                bestEv = ev;\n            }\n        } else {\n            swap(sel[si], unsel[ui]);\n        }\n        temp *= 0.99995;\n    }\n    \n    // 2-opt: complete full passes\n    bool improved = true;\n    while (improved && elapsed() < 1.95) {\n        improved = false;\n        for (int i = 0; i < 2*M - 1; i++) {\n            for (int j = i + 1; j < 2*M; j++) {\n                if (elapsed() > 1.95) break;\n                if (bestEv[i].first == bestEv[j].first) continue;\n                if (validSwap(bestEv, i, j)) {\n                    int nc = calcCost(bestEv);\n                    if (nc < bestCost) {\n                        bestCost = nc;\n                        improved = true;\n                    } else {\n                        swap(bestEv[i], bestEv[j]);\n                    }\n                }\n            }\n        }\n    }\n    \n    cout << M;\n    for (int x : bestSel) cout << \" \" << (x+1);\n    cout << \"\\n\" << (2*M+2) << \" \" << CX << \" \" << CY;\n    for (auto& [idx, isDel] : bestEv) {\n        if (isDel) cout << \" \" << ordC[idx] << \" \" << ordD[idx];\n        else cout << \" \" << ordA[idx] << \" \" << ordB[idx];\n    }\n    cout << \" \" << CX << \" \" << CY << \"\\n\";\n    \n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nclass UnionFind {\n    vector<int> parent, rank_;\npublic:\n    UnionFind(int n) : parent(n), rank_(n, 0) {\n        iota(parent.begin(), parent.end(), 0);\n    }\n    int find(int x) {\n        if (parent[x] != x) parent[x] = find(parent[x]);\n        return parent[x];\n    }\n    bool unite(int x, int y) {\n        int px = find(x), py = find(y);\n        if (px == py) return false;\n        if (rank_[px] < rank_[py]) swap(px, py);\n        parent[py] = px;\n        if (rank_[px] == rank_[py]) rank_[px]++;\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 400, M = 1995;\n    \n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        cin >> x[i] >> y[i];\n    }\n    \n    vector<int> u(M), v(M), d(M);\n    for (int i = 0; i < M; i++) {\n        cin >> u[i] >> v[i];\n        double dx = x[u[i]] - x[v[i]];\n        double dy = y[u[i]] - y[v[i]];\n        d[i] = (int)round(sqrt(dx * dx + dy * dy));\n    }\n    \n    UnionFind uf(N);\n    int components = N;\n    \n    for (int i = 0; i < M; i++) {\n        int l;\n        cin >> l;\n        \n        int pu = uf.find(u[i]);\n        int pv = uf.find(v[i]);\n        \n        bool already_connected = (pu == pv);\n        double ratio = (double)l / d[i];\n        \n        bool adopt = false;\n        \n        if (!already_connected) {\n            // Always accept truly excellent deals (ratio close to minimum possible)\n            if (ratio <= 1.4) {\n                adopt = true;\n            }\n            else {\n                int useful_remaining = 0;\n                int same_pair_remaining = 0;\n                \n                for (int j = i + 1; j < M; j++) {\n                    int uj = uf.find(u[j]);\n                    int vj = uf.find(v[j]);\n                    if (uj != vj) {\n                        useful_remaining++;\n                        if ((uj == pu && vj == pv) || (uj == pv && vj == pu)) {\n                            same_pair_remaining++;\n                        }\n                    }\n                }\n                \n                int needed = components - 1;\n                \n                if (same_pair_remaining == 0) {\n                    adopt = true;\n                }\n                else if (useful_remaining < needed * 2) {\n                    adopt = true;\n                }\n                else {\n                    double k = same_pair_remaining;\n                    double expected_min = 1.0 + 2.0 / (k + 2.0);\n                    double threshold = expected_min + 0.28;\n                    \n                    if (ratio <= threshold) {\n                        adopt = true;\n                    }\n                }\n            }\n        }\n        \n        if (adopt) {\n            uf.unite(u[i], v[i]);\n            components--;\n        }\n        \n        cout << (adopt ? 1 : 0) << \"\\n\" << flush;\n    }\n    \n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nvector<array<int,3>> pets;\nvector<array<int,2>> humans;\nbool blocked[32][32];\n\nint dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};\nchar wc[] = {'u', 'd', 'l', 'r'}, mc[] = {'U', 'D', 'L', 'R'};\n\nbool pet_at(int x, int y) {\n    for (auto& p : pets) if (p[0] == x && p[1] == y) return true;\n    return false;\n}\n\nbool pet_adjacent(int x, int y) {\n    for (int d = 0; d < 4; d++) if (pet_at(x+dx[d], y+dy[d])) return true;\n    return pet_at(x, y);\n}\n\nbool can_place(int x, int y) {\n    if (x < 1 || x > 30 || y < 1 || y > 30 || blocked[x][y]) return false;\n    for (auto& h : humans) if (h[0] == x && h[1] == y) return false;\n    return !pet_adjacent(x, y);\n}\n\nbool passable(int x, int y) {\n    return x >= 1 && x <= 30 && y >= 1 && y <= 30 && !blocked[x][y];\n}\n\nint count_adjacent_blocked(int x, int y) {\n    int cnt = 0;\n    for (int d = 0; d < 4; d++) {\n        int nx = x + dx[d], ny = y + dy[d];\n        if (nx < 1 || nx > 30 || ny < 1 || ny > 30 || blocked[nx][ny]) cnt++;\n    }\n    return cnt;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N; pets.resize(N);\n    for (int i = 0; i < N; i++) cin >> pets[i][0] >> pets[i][1] >> pets[i][2];\n    cin >> M; humans.resize(M);\n    for (int i = 0; i < M; i++) cin >> humans[i][0] >> humans[i][1];\n    \n    set<pair<int,int>> target;\n    for (int i = 1; i <= 30; i++) {\n        for (int c : {6, 12, 18, 24}) {\n            target.insert({i, c});\n            target.insert({c, i});\n        }\n    }\n    \n    for (int turn = 0; turn < 300; turn++) {\n        string action(M, '.');\n        set<pair<int,int>> will_block;\n        \n        for (int i = 0; i < M; i++) {\n            int hx = humans[i][0], hy = humans[i][1];\n            \n            // Try to build a target wall, prefer ones that extend existing walls\n            int bestd = -1, best_adj = -1;\n            for (int d = 0; d < 4; d++) {\n                int nx = hx + dx[d], ny = hy + dy[d];\n                if (target.count({nx, ny}) && can_place(nx, ny) && !will_block.count({nx, ny})) {\n                    int adj = count_adjacent_blocked(nx, ny);\n                    if (adj > best_adj) {\n                        best_adj = adj;\n                        bestd = d;\n                    }\n                }\n            }\n            \n            if (bestd >= 0) {\n                action[i] = wc[bestd];\n                will_block.insert({hx + dx[bestd], hy + dy[bestd]});\n            } else {\n                // Check if we're adjacent to an unbuilt target\n                bool near_unbuilt_target = false;\n                for (int d = 0; d < 4; d++) {\n                    int nx = hx + dx[d], ny = hy + dy[d];\n                    if (nx >= 1 && nx <= 30 && ny >= 1 && ny <= 30 &&\n                        target.count({nx, ny}) && !blocked[nx][ny]) {\n                        near_unbuilt_target = true;\n                        break;\n                    }\n                }\n                \n                if (near_unbuilt_target) {\n                    action[i] = '.';\n                } else {\n                    // Move toward closest unbuilt target\n                    int minD = INT_MAX;\n                    int moveD = -1;\n                    \n                    for (auto& [tx, ty] : target) {\n                        if (blocked[tx][ty]) continue;\n                        int dist = abs(hx-tx) + abs(hy-ty);\n                        if (dist > 0 && dist < minD) {\n                            minD = dist;\n                        }\n                    }\n                    \n                    for (int d = 0; d < 4; d++) {\n                        int nx = hx + dx[d], ny = hy + dy[d];\n                        if (!passable(nx, ny) || pet_at(nx, ny) || will_block.count({nx, ny})) continue;\n                        \n                        for (auto& [tx, ty] : target) {\n                            if (blocked[tx][ty]) continue;\n                            int newDist = abs(nx-tx) + abs(ny-ty);\n                            if (newDist < minD) {\n                                minD = newDist;\n                                moveD = d;\n                            }\n                        }\n                    }\n                    if (moveD >= 0) action[i] = mc[moveD];\n                }\n            }\n        }\n        \n        cout << action << \"\\n\" << flush;\n        \n        for (int i = 0; i < M; i++) {\n            char a = action[i];\n            for (int d = 0; d < 4; d++) {\n                if (a == wc[d]) blocked[humans[i][0]+dx[d]][humans[i][1]+dy[d]] = true;\n                if (a == mc[d]) { humans[i][0] += dx[d]; humans[i][1] += dy[d]; }\n            }\n        }\n        \n        for (int i = 0; i < N; i++) {\n            string s; cin >> s;\n            for (char c : s) {\n                if (c == 'U') pets[i][0]--;\n                else if (c == 'D') pets[i][0]++;\n                else if (c == 'L') pets[i][1]--;\n                else if (c == 'R') pets[i][1]++;\n            }\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N = 20;\nint si, sj, ti, tj;\ndouble p;\nbool hwall[20][19];\nbool vwall[19][20];\n\nbool canMove(int i, int j, char dir) {\n    if (dir == 'U') return i > 0 && !vwall[i-1][j];\n    if (dir == 'D') return i < 19 && !vwall[i][j];\n    if (dir == 'L') return j > 0 && !hwall[i][j-1];\n    if (dir == 'R') return j < 19 && !hwall[i][j];\n    return false;\n}\n\npair<int,int> doMove(int i, int j, char dir) {\n    if (!canMove(i, j, dir)) return {i, j};\n    if (dir == 'U') return {i-1, j};\n    if (dir == 'D') return {i+1, j};\n    if (dir == 'L') return {i, j-1};\n    if (dir == 'R') return {i, j+1};\n    return {i, j};\n}\n\ndouble prob[20][20], newProb[20][20];\n\ndouble evaluate(const string& s) {\n    if (s.empty() || s.size() > 200) return -1;\n    memset(prob, 0, sizeof(prob));\n    prob[si][sj] = 1.0;\n    double expectedScore = 0;\n    for (int t = 1; t <= (int)s.size(); t++) {\n        char dir = s[t-1];\n        memset(newProb, 0, sizeof(newProb));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (prob[i][j] < 1e-15) continue;\n                auto [ni, nj] = doMove(i, j, dir);\n                if (ni == ti && nj == tj) {\n                    expectedScore += (1-p) * prob[i][j] * (401 - t);\n                } else {\n                    newProb[ni][nj] += (1-p) * prob[i][j];\n                }\n                newProb[i][j] += p * prob[i][j];\n            }\n        }\n        memcpy(prob, newProb, sizeof(prob));\n    }\n    return expectedScore;\n}\n\nstring bfsWithOrder(vector<char>& order) {\n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    vector<vector<pair<int,int>>> parent(N, vector<pair<int,int>>(N, {-1,-1}));\n    vector<vector<char>> fromDir(N, vector<char>(N, ' '));\n    queue<pair<int,int>> q;\n    q.push({si, sj});\n    dist[si][sj] = 0;\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        for (char d : order) {\n            auto [ni, nj] = doMove(i, j, d);\n            if (ni == i && nj == j) continue;\n            if (dist[ni][nj] == -1) {\n                dist[ni][nj] = dist[i][j] + 1;\n                parent[ni][nj] = {i, j};\n                fromDir[ni][nj] = d;\n                q.push({ni, nj});\n            }\n        }\n    }\n    string path;\n    int ci = ti, cj = tj;\n    while (ci != si || cj != sj) {\n        path += fromDir[ci][cj];\n        auto [pi, pj] = parent[ci][cj];\n        ci = pi; cj = pj;\n    }\n    reverse(path.begin(), path.end());\n    return path;\n}\n\nmt19937 rng(42);\nstring best;\ndouble bestScore = -1;\nconst char dirs[] = {'U', 'D', 'L', 'R'};\nchrono::steady_clock::time_point startTime;\n\nbool timeUp(int ms) {\n    return chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() > ms;\n}\n\nvoid updateBest(const string& s, double score) {\n    if (score > bestScore) { bestScore = score; best = s; }\n}\n\nvoid localSearch(string& cur, double& curScore, int maxMs) {\n    while (!timeUp(maxMs)) {\n        bool improved = false;\n        \n        // Remove\n        for (size_t i = 0; i < cur.size() && !improved; i++) {\n            string trial = cur.substr(0, i) + cur.substr(i + 1);\n            if (!trial.empty()) {\n                double score = evaluate(trial);\n                if (score > curScore) { cur = trial; curScore = score; updateBest(cur, curScore); improved = true; }\n            }\n        }\n        // Change\n        for (size_t i = 0; i < cur.size() && !improved; i++) {\n            for (char d : dirs) {\n                if (d == cur[i]) continue;\n                string trial = cur; trial[i] = d;\n                double score = evaluate(trial);\n                if (score > curScore) { cur = trial; curScore = score; updateBest(cur, curScore); improved = true; break; }\n            }\n        }\n        // Insert\n        if (cur.size() < 200 && !improved) {\n            for (size_t i = 0; i <= cur.size() && !improved; i++) {\n                for (char d : dirs) {\n                    string trial = cur.substr(0, i) + d + cur.substr(i);\n                    double score = evaluate(trial);\n                    if (score > curScore) { cur = trial; curScore = score; updateBest(cur, curScore); improved = true; break; }\n                }\n            }\n        }\n        // Duplicate\n        if (cur.size() < 200 && !improved) {\n            for (size_t i = 0; i < cur.size() && !improved; i++) {\n                string trial = cur.substr(0, i+1) + cur[i] + cur.substr(i+1);\n                double score = evaluate(trial);\n                if (score > curScore) { cur = trial; curScore = score; updateBest(cur, curScore); improved = true; }\n            }\n        }\n        // Remove segment\n        for (int len = 2; len <= 4 && !improved; len++) {\n            for (size_t i = 0; i + len <= cur.size() && !improved; i++) {\n                string trial = cur.substr(0, i) + cur.substr(i + len);\n                if (!trial.empty()) {\n                    double score = evaluate(trial);\n                    if (score > curScore) { cur = trial; curScore = score; updateBest(cur, curScore); improved = true; }\n                }\n            }\n        }\n        // Duplicate segment\n        if (cur.size() < 196 && !improved) {\n            for (int len = 2; len <= 4 && !improved; len++) {\n                for (size_t i = 0; i + len <= cur.size() && !improved; i++) {\n                    string trial = cur.substr(0, i + len) + cur.substr(i, len) + cur.substr(i + len);\n                    if (trial.size() <= 200) {\n                        double score = evaluate(trial);\n                        if (score > curScore) { cur = trial; curScore = score; updateBest(cur, curScore); improved = true; }\n                    }\n                }\n            }\n        }\n        \n        if (!improved) break;\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    startTime = chrono::steady_clock::now();\n    \n    cin >> si >> sj >> ti >> tj >> p;\n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < 19; j++) hwall[i][j] = (s[j] == '1');\n    }\n    for (int i = 0; i < 19; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) vwall[i][j] = (s[j] == '1');\n    }\n    \n    vector<char> order = {'U', 'D', 'L', 'R'};\n    set<string> pathSet;\n    for (int iter = 0; iter < 50; iter++) {\n        shuffle(order.begin(), order.end(), rng);\n        pathSet.insert(bfsWithOrder(order));\n    }\n    vector<string> paths(pathSet.begin(), pathSet.end());\n    sort(paths.begin(), paths.end(), [](const string& a, const string& b) { return a.size() < b.size(); });\n    \n    vector<pair<double, string>> candidates;\n    \n    for (const string& path : paths) {\n        if (timeUp(250)) break;\n        int L = path.size();\n        \n        for (int rep = 1; rep * L <= 200; rep++) {\n            string r; for (char c : path) for (int i = 0; i < rep; i++) r += c;\n            double sc = evaluate(r);\n            candidates.emplace_back(sc, r);\n            updateBest(r, sc);\n        }\n        for (int rep = 1; rep * L <= 200; rep++) {\n            string r; for (int i = 0; i < rep; i++) r += path;\n            double sc = evaluate(r);\n            candidates.emplace_back(sc, r);\n            updateBest(r, sc);\n        }\n        for (int bonus = 2; bonus <= 8; bonus += 2) {\n            for (int base = 1; base * L <= 200; base++) {\n                string r; int ci = si, cj = sj;\n                for (char c : path) {\n                    auto [ni, nj] = doMove(ci, cj, c);\n                    int reps = !canMove(ni, nj, c) ? base + bonus : base;\n                    for (int i = 0; i < reps && r.size() < 200; i++) r += c;\n                    ci = ni; cj = nj;\n                }\n                double sc = evaluate(r);\n                candidates.emplace_back(sc, r);\n                updateBest(r, sc);\n            }\n        }\n        for (int pr = 1; pr <= 8; pr++) {\n            for (int mr = 1; mr * L * pr <= 200 && mr <= 8; mr++) {\n                string r;\n                for (int i = 0; i < pr; i++) for (char c : path) for (int j = 0; j < mr; j++) r += c;\n                double sc = evaluate(r);\n                candidates.emplace_back(sc, r);\n                updateBest(r, sc);\n            }\n        }\n    }\n    \n    sort(candidates.rbegin(), candidates.rend());\n    \n    // Local search on diverse top candidates\n    set<int> tried;\n    for (int i = 0; i < min(10, (int)candidates.size()) && !timeUp(1200); i++) {\n        int len = candidates[i].second.size();\n        if (i >= 3 && tried.count(len)) continue;\n        tried.insert(len);\n        \n        string cur = candidates[i].second;\n        double curScore = candidates[i].first;\n        localSearch(cur, curScore, 1200);\n    }\n    \n    // Random restarts\n    while (!timeUp(1890)) {\n        string cur = best;\n        double curScore = bestScore;\n        \n        int ops = 1 + rng() % 2;\n        for (int i = 0; i < ops; i++) {\n            if (cur.empty()) break;\n            int t = rng() % 4;\n            size_t pos = rng() % cur.size();\n            if (t == 0 && cur.size() > 1) cur.erase(pos, 1);\n            else if (t == 1 && cur.size() < 200) cur.insert(pos, 1, dirs[rng() % 4]);\n            else if (t == 2 && !cur.empty()) cur[pos] = dirs[rng() % 4];\n            else if (t == 3 && cur.size() < 200 && !cur.empty()) cur.insert(pos, 1, cur[pos]);\n        }\n        \n        if (!cur.empty() && cur.size() <= 200) {\n            curScore = evaluate(cur);\n            if (curScore > bestScore * 0.97) {\n                localSearch(cur, curScore, 1890);\n            }\n        }\n    }\n    \n    cout << best << endl;\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nint tiles[N][N];\nint rotation[N][N];\n\nconst int di[] = {0, -1, 0, 1};\nconst int dj[] = {-1, 0, 1, 0};\n\nconst int to_arr[8][4] = {\n    {1, 0, -1, -1}, {3, -1, -1, 0}, {-1, -1, 3, 2}, {-1, 2, 1, -1},\n    {1, 0, 3, 2}, {3, 2, 1, 0}, {2, -1, 0, -1}, {-1, 3, -1, 1},\n};\n\nint state_cache[N][N];\nint visited_gen[N][N][4];\nint current_gen;\n\ninline void updateState(int i, int j) {\n    int t = tiles[i][j], r = rotation[i][j];\n    if (t < 4) state_cache[i][j] = (t + r) & 3;\n    else if (t < 6) state_cache[i][j] = 4 + ((t + r) & 1);\n    else state_cache[i][j] = 6 + ((t + r) & 1);\n}\n\ninline int traceLoop(int si, int sj, int sd) {\n    int i = si, j = sj, d = sd, length = 0;\n    do {\n        int d2 = to_arr[state_cache[i][j]][d];\n        if (d2 < 0) return 0;\n        if (++length > 3600) return 0;\n        i += di[d2]; j += dj[d2];\n        if ((unsigned)i >= N || (unsigned)j >= N) return 0;\n        d = d2 ^ 2;\n    } while (i != si || j != sj || d != sd);\n    return length;\n}\n\ninline pair<int, int> computeTopTwoLoops() {\n    ++current_gen;\n    int top1 = 0, top2 = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int st = state_cache[i][j];\n            for (int d = 0; d < 4; d++) {\n                if (to_arr[st][d] < 0 || visited_gen[i][j][d] == current_gen) continue;\n                int len = traceLoop(i, j, d);\n                if (len > 0) {\n                    if (len > top1) { top2 = top1; top1 = len; }\n                    else if (len > top2) { top2 = len; }\n                    int ci = i, cj = j, cd = d;\n                    do {\n                        visited_gen[ci][cj][cd] = current_gen;\n                        int d2 = to_arr[state_cache[ci][cj]][cd];\n                        ci += di[d2]; cj += dj[d2];\n                        cd = d2 ^ 2;\n                    } while (ci != i || cj != j || cd != d);\n                }\n            }\n        }\n    }\n    return {top1, top2};\n}\n\nint best_rotation[N][N];\nlong long best_score;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    memset(visited_gen, 0, sizeof(visited_gen));\n    current_gen = 0;\n    \n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = s[j] - '0';\n            rotation[i][j] = 0;\n            updateState(i, j);\n        }\n    }\n    \n    mt19937 rng(42);\n    auto start_time = chrono::steady_clock::now();\n    \n    auto [l1, l2] = computeTopTwoLoops();\n    best_score = (long long)l1 * l2;\n    memcpy(best_rotation, rotation, sizeof(rotation));\n    long long current_score = best_score;\n    \n    const double TIME_LIMIT = 1.95;\n    int iter = 0;\n    \n    while (true) {\n        if ((++iter & 0xFF) == 0) {\n            auto now = chrono::steady_clock::now();\n            double elapsed = chrono::duration<double>(now - start_time).count();\n            if (elapsed > TIME_LIMIT) break;\n        }\n        \n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start_time).count();\n        double T = 1000.0 * pow(0.0001, elapsed / TIME_LIMIT);\n        \n        int i = rng() % N, j = rng() % N;\n        int old_rot = rotation[i][j];\n        int new_rot = (old_rot + 1 + (rng() % 3)) & 3;\n        \n        rotation[i][j] = new_rot;\n        updateState(i, j);\n        \n        auto [nl1, nl2] = computeTopTwoLoops();\n        long long new_score = (long long)nl1 * nl2;\n        \n        if (new_score >= current_score || \n            (rng() & 0xFFFFFF) < (unsigned)(exp((double)(new_score - current_score) / T) * 0x1000000)) {\n            current_score = new_score;\n            if (new_score > best_score) {\n                best_score = new_score;\n                memcpy(best_rotation, rotation, sizeof(rotation));\n            }\n        } else {\n            rotation[i][j] = old_rot;\n            updateState(i, j);\n        }\n    }\n    \n    string result;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            result += ('0' + best_rotation[i][j]);\n    cout << result << endl;\n    \n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nint dr[] = {-1, 1, 0, 0};\nint dc[] = {0, 0, -1, 1};\nchar dc_char[] = {'U', 'D', 'L', 'R'};\nint rev[] = {1, 0, 3, 2};\n\nint hexChar(char c) {\n    return (c >= '0' && c <= '9') ? c - '0' : c - 'a' + 10;\n}\n\nint calcScore(const vector<vector<int>>& board) {\n    vector<vector<int>> adj(N * N);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (board[i][j] == 0) continue;\n            if (i + 1 < N && board[i+1][j] != 0 && (board[i][j] & 8) && (board[i+1][j] & 2)) {\n                adj[i*N+j].push_back((i+1)*N+j);\n                adj[(i+1)*N+j].push_back(i*N+j);\n            }\n            if (j + 1 < N && board[i][j+1] != 0 && (board[i][j] & 4) && (board[i][j+1] & 1)) {\n                adj[i*N+j].push_back(i*N+j+1);\n                adj[i*N+j+1].push_back(i*N+j);\n            }\n        }\n    }\n    vector<bool> vis(N * N, false);\n    int maxTree = 0;\n    for (int s = 0; s < N * N; s++) {\n        if (vis[s] || board[s/N][s%N] == 0) continue;\n        int cnt = 0, edges = 0;\n        queue<int> q; q.push(s); vis[s] = true;\n        while (!q.empty()) {\n            int u = q.front(); q.pop(); cnt++;\n            edges += adj[u].size();\n            for (int v : adj[u]) if (!vis[v]) { vis[v] = true; q.push(v); }\n        }\n        if (edges / 2 == cnt - 1) maxTree = max(maxTree, cnt);\n    }\n    return maxTree;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> T;\n    vector<vector<int>> board(N, vector<int>(N));\n    int er, ec;\n    for (int i = 0; i < N; i++) {\n        string s; cin >> s;\n        for (int j = 0; j < N; j++) {\n            board[i][j] = hexChar(s[j]);\n            if (board[i][j] == 0) { er = i; ec = j; }\n        }\n    }\n    \n    string best, cur;\n    int bestScore = calcScore(board), curScore = bestScore;\n    auto bestBoard = board;\n    int bestEr = er, bestEc = ec;\n    int lastD = -1;\n    int step = 0;\n    int stepsWithoutImprove = 0;\n    \n    mt19937 rng(42);\n    auto start = chrono::steady_clock::now();\n    \n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - start).count() < 2850) {\n        if (cur.size() >= (size_t)T || bestScore >= N * N - 1) break;\n        step++;\n        stepsWithoutImprove++;\n        \n        vector<int> valid;\n        for (int dd = 0; dd < 4; dd++) {\n            int nr = er + dr[dd], nc = ec + dc[dd];\n            if (nr >= 0 && nr < N && nc >= 0 && nc < N) valid.push_back(dd);\n        }\n        \n        if (lastD >= 0 && valid.size() > 1 && rng() % 100 < 76) {\n            valid.erase(remove(valid.begin(), valid.end(), rev[lastD]), valid.end());\n        }\n        \n        int d;\n        bool isGreedy = (step % 7 == 0 && valid.size() > 1);\n        \n        if (isGreedy) {\n            int bestD = valid[0], bestS = -1;\n            for (int dd : valid) {\n                int nr = er + dr[dd], nc = ec + dc[dd];\n                swap(board[er][ec], board[nr][nc]);\n                int s = calcScore(board);\n                swap(board[er][ec], board[nr][nc]);\n                if (s > bestS) { bestS = s; bestD = dd; }\n            }\n            d = bestD;\n        } else {\n            d = valid[rng() % valid.size()];\n        }\n        \n        int nr = er + dr[d], nc = ec + dc[d];\n        swap(board[er][ec], board[nr][nc]);\n        cur += dc_char[d];\n        int newScore = calcScore(board);\n        \n        double temp = 1.0 - (double)cur.size() / T;\n        bool accept = isGreedy || newScore > curScore || (rng() % 1000 < (int)(118 * temp));\n        \n        if (accept) {\n            er = nr; ec = nc;\n            curScore = newScore;\n            lastD = d;\n            if (curScore > bestScore || (curScore == bestScore && cur.size() < best.size())) {\n                bestScore = curScore;\n                best = cur;\n                bestBoard = board;\n                bestEr = er;\n                bestEc = ec;\n                stepsWithoutImprove = 0;\n            }\n        } else {\n            cur.pop_back();\n            swap(board[er][ec], board[nr][nc]);\n        }\n        \n        bool shouldRestart = (cur.size() > best.size() + 130 && rng() % 100 < 5) ||\n                            (stepsWithoutImprove > 350 && rng() % 100 < 12) ||\n                            (stepsWithoutImprove > 600 && rng() % 100 < 18);\n        \n        if (shouldRestart) {\n            bool needPerturb = (stepsWithoutImprove > 500);\n            \n            board = bestBoard;\n            er = bestEr;\n            ec = bestEc;\n            cur = best;\n            curScore = bestScore;\n            lastD = -1;\n            \n            // Add perturbation to escape local optimum\n            if (needPerturb && cur.size() + 20 < (size_t)T) {\n                int perturbMoves = 8 + rng() % 12;\n                for (int i = 0; i < perturbMoves; i++) {\n                    vector<int> pV;\n                    for (int dd = 0; dd < 4; dd++) {\n                        int nnr = er + dr[dd], nnc = ec + dc[dd];\n                        if (nnr >= 0 && nnr < N && nnc >= 0 && nnc < N) pV.push_back(dd);\n                    }\n                    int pd = pV[rng() % pV.size()];\n                    int pnr = er + dr[pd], pnc = ec + dc[pd];\n                    swap(board[er][ec], board[pnr][pnc]);\n                    cur += dc_char[pd];\n                    er = pnr; ec = pnc;\n                }\n                curScore = calcScore(board);\n            }\n            \n            stepsWithoutImprove = 0;\n        }\n    }\n    \n    cout << best << endl;\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nint N, K;\nvector<int> a(10);\nvector<pair<ll, ll>> berries;\nvector<array<ll, 4>> cuts;\nvector<vector<int>> sides;\n\ninline int side(ll x1, ll y1, ll x2, ll y2, ll px, ll py) {\n    __int128 cross = (__int128)(x2 - x1) * (py - y1) - (__int128)(y2 - y1) * (px - x1);\n    if (cross > 0) return 1;\n    if (cross < 0) return -1;\n    return 0;\n}\n\nint calcScore() {\n    int numCuts = cuts.size();\n    unordered_map<uint64_t, int> pieceCount;\n    pieceCount.reserve(N);\n    \n    for (int j = 0; j < N; j++) {\n        bool onLine = false;\n        uint64_t h = 0;\n        for (int i = 0; i < numCuts; i++) {\n            if (sides[i][j] == 0) { onLine = true; break; }\n            h = h * 3ULL + (uint64_t)(sides[i][j] + 1);\n        }\n        if (!onLine) pieceCount[h]++;\n    }\n    \n    vector<int> b(11, 0);\n    for (auto& [sig, cnt] : pieceCount) {\n        if (cnt >= 1 && cnt <= 10) b[cnt]++;\n    }\n    \n    int total = 0;\n    for (int d = 1; d <= 10; d++) total += min(a[d-1], b[d]);\n    return total;\n}\n\nvoid updateSides(int idx) {\n    while ((int)sides.size() <= idx) sides.push_back(vector<int>(N));\n    for (int j = 0; j < N; j++) {\n        sides[idx][j] = side(cuts[idx][0], cuts[idx][1], cuts[idx][2], cuts[idx][3],\n                            berries[j].first, berries[j].second);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> K;\n    for (int i = 0; i < 10; i++) cin >> a[i];\n    \n    berries.resize(N);\n    for (int i = 0; i < N; i++) cin >> berries[i].first >> berries[i].second;\n    \n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    \n    auto randLine = [&]() -> array<ll, 4> {\n        ll px = (ll)(rng() % 20001) - 10000;\n        ll py = (ll)(rng() % 20001) - 10000;\n        ll qx = (ll)(rng() % 20001) - 10000;\n        ll qy = (ll)(rng() % 20001) - 10000;\n        while (px == qx && py == qy) { qx = (ll)(rng() % 20001) - 10000; qy = (ll)(rng() % 20001) - 10000; }\n        return {px, py, qx, qy};\n    };\n    \n    auto perpBisector = [&](int i, int j) -> array<ll, 4> {\n        if (i == j) return randLine();\n        ll dx = berries[j].first - berries[i].first;\n        ll dy = berries[j].second - berries[i].second;\n        ll mx = berries[i].first + berries[j].first;\n        ll my = berries[i].second + berries[j].second;\n        return {mx - dy * 1000, my + dx * 1000, mx + dy * 1000, my - dx * 1000};\n    };\n    \n    auto radialLine = [&](double angle) -> array<ll, 4> {\n        ll px = (ll)(cos(angle) * 15000);\n        ll py = (ll)(sin(angle) * 15000);\n        if (px == 0 && py == 0) px = 1;\n        return {px, py, -px, -py};\n    };\n    \n    auto genLine = [&]() -> array<ll, 4> {\n        int strat = rng() % 5;\n        if (strat == 0) return randLine();\n        else if (strat <= 2) return perpBisector(rng() % N, rng() % N);\n        else if (strat == 3) return radialLine((double)(rng() % 10000) / 10000.0 * M_PI * 2);\n        else {\n            int b1 = rng() % N, b2 = rng() % N;\n            if (b1 != b2) return {berries[b1].first, berries[b1].second, berries[b2].first, berries[b2].second};\n            return randLine();\n        }\n    };\n    \n    int bestScore = 0;\n    vector<array<ll, 4>> bestCuts;\n    \n    auto start = chrono::steady_clock::now();\n    \n    for (int restart = 0; ; restart++) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration_cast<chrono::milliseconds>(now - start).count();\n        if (elapsed > 2850) break;\n        \n        cuts.clear();\n        sides.clear();\n        int numCuts = 25 + rng() % 35;\n        \n        for (int i = 0; i < numCuts; i++) {\n            cuts.push_back(genLine());\n            updateSides(i);\n        }\n        \n        int curScore = calcScore();\n        if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n        \n        for (int iter = 0; ; iter++) {\n            now = chrono::steady_clock::now();\n            elapsed = chrono::duration_cast<chrono::milliseconds>(now - start).count();\n            if (elapsed > 2850) break;\n            \n            double progress = elapsed / 2850.0;\n            double temp = 3.0 * (1.0 - progress) + 0.1;\n            int moveType = rng() % 100;\n            \n            if (moveType < 75 && !cuts.empty()) {\n                int idx = rng() % cuts.size();\n                auto oldCut = cuts[idx];\n                auto oldSide = sides[idx];\n                \n                cuts[idx] = genLine();\n                updateSides(idx);\n                \n                int newScore = calcScore();\n                if (newScore > curScore || (double)(rng() % 1000000) / 1000000.0 < exp((newScore - curScore) / temp)) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else {\n                    cuts[idx] = oldCut;\n                    sides[idx] = oldSide;\n                }\n            } else if (moveType < 90 && cuts.size() < (size_t)min(K, 80)) {\n                cuts.push_back(genLine());\n                updateSides(cuts.size() - 1);\n                \n                int newScore = calcScore();\n                if (newScore >= curScore) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else {\n                    cuts.pop_back();\n                    sides.pop_back();\n                }\n            } else if (cuts.size() > 10) {\n                int idx = rng() % cuts.size();\n                auto oldCut = cuts[idx];\n                auto oldSide = sides[idx];\n                cuts.erase(cuts.begin() + idx);\n                sides.erase(sides.begin() + idx);\n                \n                int newScore = calcScore();\n                if (newScore >= curScore) {\n                    curScore = newScore;\n                    if (curScore > bestScore) { bestScore = curScore; bestCuts = cuts; }\n                } else {\n                    cuts.insert(cuts.begin() + idx, oldCut);\n                    sides.insert(sides.begin() + idx, oldSide);\n                }\n            }\n        }\n    }\n    \n    cout << bestCuts.size() << \"\\n\";\n    for (auto& c : bestCuts) cout << c[0] << \" \" << c[1] << \" \" << c[2] << \" \" << c[3] << \"\\n\";\n    \n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, c;\nset<pair<int,int>> dots;\nset<tuple<int,int,int,int>> usedSegs;\nvector<array<int, 8>> ops;\n\nbool inGrid(int x, int y) { return x >= 0 && x < N && y >= 0 && y < N; }\nlong long wt(int x, int y) { return (long long)(x-c)*(x-c) + (long long)(y-c)*(y-c) + 1; }\n\nvoid addSeg(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g == 0) return;\n    dx /= g; dy /= g;\n    for (int i = 0; i < g; i++) {\n        int a = x1+i*dx, b = y1+i*dy, e = a+dx, f = b+dy;\n        if (a > e || (a == e && b > f)) { swap(a,e); swap(b,f); }\n        usedSegs.insert({a,b,e,f});\n    }\n}\n\nbool segUsed(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g == 0) return true;\n    dx /= g; dy /= g;\n    for (int i = 0; i < g; i++) {\n        int a = x1+i*dx, b = y1+i*dy, e = a+dx, f = b+dy;\n        if (a > e || (a == e && b > f)) { swap(a,e); swap(b,f); }\n        if (usedSegs.count({a,b,e,f})) return true;\n    }\n    return false;\n}\n\nbool dotOnSeg(int x1, int y1, int x2, int y2) {\n    int dx = x2-x1, dy = y2-y1, g = __gcd(abs(dx), abs(dy));\n    if (g <= 1) return false;\n    dx /= g; dy /= g;\n    for (int i = 1; i < g; i++)\n        if (dots.count({x1+i*dx, y1+i*dy})) return true;\n    return false;\n}\n\nbool isValidRect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    int v1x = x2-x1, v1y = y2-y1;\n    int v2x = x3-x2, v2y = y3-y2;\n    if (v1x == 0 && v1y == 0) return false;\n    if (v2x == 0 && v2y == 0) return false;\n    if (v1x*v2x + v1y*v2y != 0) return false;\n    bool axis1 = (v1x == 0 || v1y == 0);\n    bool diag1 = (abs(v1x) == abs(v1y));\n    if (!axis1 && !diag1) return false;\n    bool axis2 = (v2x == 0 || v2y == 0);\n    bool diag2 = (abs(v2x) == abs(v2y));\n    if (!axis2 && !diag2) return false;\n    if (x4 != x1 + v2x || y4 != y1 + v2y) return false;\n    return true;\n}\n\nbool tryAdd(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {\n    if (!inGrid(x1,y1) || dots.count({x1,y1})) return false;\n    if (!dots.count({x2,y2}) || !dots.count({x3,y3}) || !dots.count({x4,y4})) return false;\n    set<pair<int,int>> pts = {{x1,y1},{x2,y2},{x3,y3},{x4,y4}};\n    if (pts.size() != 4) return false;\n    if (!isValidRect(x1,y1,x2,y2,x3,y3,x4,y4)) return false;\n    if (dotOnSeg(x1,y1,x2,y2) || dotOnSeg(x2,y2,x3,y3) || \n        dotOnSeg(x3,y3,x4,y4) || dotOnSeg(x4,y4,x1,y1)) return false;\n    if (segUsed(x1,y1,x2,y2) || segUsed(x2,y2,x3,y3) || \n        segUsed(x3,y3,x4,y4) || segUsed(x4,y4,x1,y1)) return false;\n    \n    dots.insert({x1,y1});\n    addSeg(x1,y1,x2,y2); addSeg(x2,y2,x3,y3);\n    addSeg(x3,y3,x4,y4); addSeg(x4,y4,x1,y1);\n    ops.push_back({x1,y1,x2,y2,x3,y3,x4,y4});\n    return true;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M;\n    c = (N-1) / 2;\n    for (int i = 0; i < M; i++) { int x, y; cin >> x >> y; dots.insert({x, y}); }\n    \n    auto tstart = chrono::steady_clock::now();\n    mt19937 rng(42);\n    \n    int fails = 0;\n    while (chrono::duration<double>(chrono::steady_clock::now() - tstart).count() < 4.5) {\n        vector<pair<int,int>> dl(dots.begin(), dots.end());\n        shuffle(dl.begin(), dl.end(), rng);\n        int sz = min((int)dl.size(), 100);\n        \n        vector<tuple<long long, array<int,8>>> candidates;\n        \n        for (int i = 0; i < sz; i++) {\n            for (int j = 0; j < sz; j++) {\n                if (i == j) continue;\n                for (int k = 0; k < sz; k++) {\n                    if (k == i || k == j) continue;\n                    auto [ax, ay] = dl[i];\n                    auto [bx, by] = dl[j];\n                    auto [cx, cy] = dl[k];\n                    \n                    // Try: new point D, with corners D-A-B-C (A opposite to C, B opposite to D)\n                    // D = A + C - B\n                    int dx = ax + cx - bx, dy = ay + cy - by;\n                    if (inGrid(dx, dy) && !dots.count({dx, dy})) {\n                        long long w = wt(dx, dy);\n                        candidates.push_back({w, {dx, dy, ax, ay, bx, by, cx, cy}});\n                    }\n                }\n            }\n        }\n        \n        sort(candidates.begin(), candidates.end(), greater<>());\n        \n        bool found = false;\n        for (auto& [w, arr] : candidates) {\n            if (tryAdd(arr[0],arr[1],arr[2],arr[3],arr[4],arr[5],arr[6],arr[7])) {\n                found = true;\n                break;\n            }\n        }\n        \n        if (!found) {\n            if (++fails > 200) break;\n        } else {\n            fails = 0;\n        }\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto& op : ops) {\n        for (int i = 0; i < 8; i++) cout << op[i] << \" \\n\"[i==7];\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 10;\n\nstruct State {\n    int grid[N][N];\n    \n    State() { memset(grid, 0, sizeof(grid)); }\n    \n    int countEmpty() const {\n        int cnt = 0;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] == 0) cnt++;\n        return cnt;\n    }\n    \n    void place(int p, int flavor) {\n        int cnt = 0;\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                if (grid[i][j] == 0 && ++cnt == p) { grid[i][j] = flavor; return; }\n    }\n    \n    void tilt(int dir) {\n        if (dir == 0) {\n            for (int j = 0; j < N; j++) {\n                int w = 0;\n                for (int i = 0; i < N; i++) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[w++][j] = v; }\n            }\n        } else if (dir == 1) {\n            for (int j = 0; j < N; j++) {\n                int w = N - 1;\n                for (int i = N - 1; i >= 0; i--) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[w--][j] = v; }\n            }\n        } else if (dir == 2) {\n            for (int i = 0; i < N; i++) {\n                int w = 0;\n                for (int j = 0; j < N; j++) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[i][w++] = v; }\n            }\n        } else {\n            for (int i = 0; i < N; i++) {\n                int w = N - 1;\n                for (int j = N - 1; j >= 0; j--) if (grid[i][j]) { int v = grid[i][j]; grid[i][j] = 0; grid[i][w--] = v; }\n            }\n        }\n    }\n    \n    long long calcScore() const {\n        bool vis[N][N] = {};\n        long long sum = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (grid[i][j] && !vis[i][j]) {\n                    int f = grid[i][j], sz = 0;\n                    int stk[100], top = 0;\n                    stk[top++] = i * N + j;\n                    vis[i][j] = true;\n                    while (top > 0) {\n                        int pos = stk[--top];\n                        int x = pos / N, y = pos % N;\n                        sz++;\n                        if (x > 0 && !vis[x-1][y] && grid[x-1][y] == f) { vis[x-1][y] = true; stk[top++] = (x-1)*N+y; }\n                        if (x < N-1 && !vis[x+1][y] && grid[x+1][y] == f) { vis[x+1][y] = true; stk[top++] = (x+1)*N+y; }\n                        if (y > 0 && !vis[x][y-1] && grid[x][y-1] == f) { vis[x][y-1] = true; stk[top++] = x*N+y-1; }\n                        if (y < N-1 && !vis[x][y+1] && grid[x][y+1] == f) { vis[x][y+1] = true; stk[top++] = x*N+y+1; }\n                    }\n                    sum += (long long)sz * sz;\n                }\n            }\n        }\n        return sum;\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int f[101];\n    for (int t = 1; t <= 100; t++) cin >> f[t];\n    \n    State state;\n    \n    for (int t = 1; t <= 100; t++) {\n        int p; cin >> p;\n        state.place(p, f[t]);\n        \n        int remaining = 100 - t;\n        int depth = min(13, remaining);\n        int numSims;\n        if (t <= 20) numSims = 42;\n        else if (t <= 50) numSims = 38;\n        else if (t <= 75) numSims = 32;\n        else numSims = 24;\n        \n        int bestDir = 0;\n        long long bestScore = -1;\n        \n        for (int dir = 0; dir < 4; dir++) {\n            mt19937 rng(12345 + t);\n            long long totalScore = 0;\n            \n            for (int sim = 0; sim < numSims; sim++) {\n                State s = state;\n                s.tilt(dir);\n                \n                for (int step = 1; step <= depth && t + step <= 100; step++) {\n                    int empty = s.countEmpty();\n                    if (empty == 0) break;\n                    int randPos = (rng() % empty) + 1;\n                    s.place(randPos, f[t + step]);\n                    \n                    int simBest = 0;\n                    long long simBestScore = -1;\n                    for (int d = 0; d < 4; d++) {\n                        State tmp = s;\n                        tmp.tilt(d);\n                        long long sc = tmp.calcScore();\n                        if (sc > simBestScore) { simBestScore = sc; simBest = d; }\n                    }\n                    s.tilt(simBest);\n                }\n                totalScore += s.calcScore();\n            }\n            \n            if (totalScore > bestScore) {\n                bestScore = totalScore;\n                bestDir = dir;\n            }\n        }\n        \n        state.tilt(bestDir);\n        const char dirChar[] = {'F', 'B', 'L', 'R'};\n        cout << dirChar[bestDir] << '\\n' << flush;\n    }\n    \n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\ndouble eps;\n\nvector<int> get_sorted_degrees(const string& s) {\n    vector<int> deg(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 (s[idx++] == '1') {\n                deg[i]++;\n                deg[j]++;\n            }\n        }\n    }\n    sort(deg.begin(), deg.end());\n    return deg;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    cin >> M >> eps;\n    \n    double noise_factor = (eps < 0.001) ? 1.0 : 1.0 / max(0.2, 1.0 - 2.0 * eps);\n    \n    if (eps < 0.01) {\n        N = (int)ceil(sqrt(2.0 * M)) + 2;\n    } else if (eps < 0.05) {\n        N = (int)ceil(sqrt(2.5 * M)) + 4;\n    } else if (eps < 0.15) {\n        N = (int)ceil(sqrt(3.0 * M * noise_factor)) + 8;\n    } else if (eps < 0.25) {\n        N = (int)ceil(sqrt(4.0 * M * noise_factor)) + 15;\n    } else if (eps < 0.35) {\n        N = (int)ceil(sqrt(5.0 * M * noise_factor)) + 25;\n    } else {\n        N = (int)ceil(sqrt(6.0 * M * noise_factor)) + 35;\n    }\n    \n    N = max(N, (int)(2.0 * sqrt(M)));\n    N = max(N, 8);\n    N = min(N, 100);\n    \n    cout << N << \"\\n\";\n    \n    int total = N * (N - 1) / 2;\n    \n    vector<string> G(M);\n    vector<vector<double>> expected_deg(M);\n    \n    for (int i = 0; i < M; i++) {\n        string s(total, '0');\n        long long edges = (M > 1) ? ((long long)i * total / (M - 1)) : 0;\n        \n        int filled = 0;\n        for (int a = 0; a < N && filled < edges; a++) {\n            for (int b = a + 1; b < N && filled < edges; b++) {\n                int pos = a * (2 * N - a - 1) / 2 + (b - a - 1);\n                s[pos] = '1';\n                filled++;\n            }\n        }\n        \n        G[i] = s;\n        \n        vector<int> deg = get_sorted_degrees(s);\n        expected_deg[i].resize(N);\n        double transform = 1.0 - 2.0 * eps;\n        double base = (N - 1) * eps;\n        for (int j = 0; j < N; j++) {\n            expected_deg[i][j] = deg[j] * transform + base;\n        }\n        \n        cout << s << \"\\n\";\n    }\n    cout.flush();\n    \n    // Best weight formula with slight quadratic enhancement for high eps\n    double base_weight = 0.4 + min(0.4, eps);\n    double quad_factor = (eps > 0.2) ? 0.1 * (eps - 0.2) : 0.0;\n    \n    for (int q = 0; q < 100; q++) {\n        string H;\n        cin >> H;\n        \n        vector<int> deg_h = get_sorted_degrees(H);\n        \n        int best = 0;\n        double best_score = 1e18;\n        \n        for (int i = 0; i < M; i++) {\n            double score = 0;\n            for (int j = 0; j < N; j++) {\n                double diff = deg_h[j] - expected_deg[i][j];\n                double pos = (N > 1) ? (double)j / (N - 1) : 0.5;\n                double dist_from_mid = abs(pos - 0.5) * 2.0;\n                // Linear + small quadratic component for high eps\n                double weight = 1.0 + base_weight * dist_from_mid + quad_factor * dist_from_mid * dist_from_mid;\n                score += weight * diff * diff;\n            }\n            \n            if (score < best_score) {\n                best_score = score;\n                best = i;\n            }\n        }\n        \n        cout << best << \"\\n\";\n        cout.flush();\n    }\n    \n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, D, K;\nvector<array<int,3>> edges;\nvector<vector<pair<int,int>>> adj;\nvector<vector<int>> adjEdge;\nmt19937 rng(42);\nconst long long INF = 1e9;\n\nvector<long long> dijkstraMask(int src, const vector<bool>& excl) {\n    vector<long long> dist(N, INF);\n    priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> pq;\n    dist[src] = 0;\n    pq.push({0, src});\n    while (!pq.empty()) {\n        auto [d, u] = pq.top(); pq.pop();\n        if (d > dist[u]) continue;\n        for (size_t i = 0; i < adj[u].size(); i++) {\n            if (excl[adjEdge[u][i]]) continue;\n            auto [v, w] = adj[u][i];\n            if (dist[u] + w < dist[v]) {\n                dist[v] = dist[u] + w;\n                pq.push({dist[v], v});\n            }\n        }\n    }\n    return dist;\n}\n\nint numSamples;\nvector<int> samples;\nvector<vector<long long>> origDist;\nvector<int> assign_;\nvector<int> cnt;\nvector<long long> crit;\nvector<int> critOrder;\n\ndouble evalDay(int d) {\n    vector<bool> excl(M, false);\n    for (int e = 0; e < M; e++) if (assign_[e] == d) excl[e] = true;\n    double tot = 0;\n    for (int i = 0; i < numSamples; i++) {\n        auto dist = dijkstraMask(samples[i], excl);\n        for (int v = 0; v < N; v++) if (v != samples[i])\n            tot += min(dist[v], INF) - origDist[i][v];\n    }\n    return tot;\n}\n\nvoid initAssignment(int mode) {\n    vector<int> order(M); iota(order.begin(), order.end(), 0);\n    if (mode == 0) sort(order.begin(), order.end(), [&](int a, int b) { return crit[a] > crit[b]; });\n    else shuffle(order.begin(), order.end(), rng);\n    \n    assign_.assign(M, 0);\n    cnt.assign(D + 1, 0);\n    vector<set<int>> dayV(D + 1);\n    \n    for (int e : order) {\n        int u = edges[e][0], v = edges[e][1];\n        int best = 1;\n        for (int d = 1; d <= D; d++) {\n            if (cnt[d] >= K) continue;\n            int c1 = (dayV[d].count(u)?1:0) + (dayV[d].count(v)?1:0);\n            int c2 = (dayV[best].count(u)?1:0) + (dayV[best].count(v)?1:0);\n            if (cnt[best] >= K || c1 < c2 || (c1 == c2 && cnt[d] < cnt[best])) best = d;\n        }\n        assign_[e] = best; cnt[best]++;\n        dayV[best].insert(u); dayV[best].insert(v);\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    auto start = chrono::steady_clock::now();\n    \n    cin >> N >> M >> D >> K;\n    edges.resize(M); adj.resize(N); adjEdge.resize(N);\n    vector<int> deg(N, 0);\n    \n    for (int i = 0; i < M; i++) {\n        int u, v, w; cin >> u >> v >> w; u--; v--;\n        edges[i] = {u, v, w};\n        adj[u].push_back({v, w}); adj[v].push_back({u, w});\n        adjEdge[u].push_back(i); adjEdge[v].push_back(i);\n        deg[u]++; deg[v]++;\n    }\n    for (int i = 0; i < N; i++) { int x, y; cin >> x >> y; }\n    \n    vector<bool> noEdge(M, false);\n    crit.resize(M);\n    for (int e = 0; e < M; e++) {\n        noEdge[e] = true;\n        auto dist = dijkstraMask(edges[e][0], noEdge);\n        crit[e] = dist[edges[e][1]] - edges[e][2];\n        noEdge[e] = false;\n    }\n    \n    critOrder.resize(M); iota(critOrder.begin(), critOrder.end(), 0);\n    sort(critOrder.begin(), critOrder.end(), [&](int a, int b) { return crit[a] > crit[b]; });\n    \n    // Stratified sampling\n    vector<int> byDeg(N); iota(byDeg.begin(), byDeg.end(), 0);\n    sort(byDeg.begin(), byDeg.end(), [&](int a, int b) { return deg[a] > deg[b]; });\n    \n    numSamples = min(45, N);\n    samples.clear();\n    for (int i = 0; i < min(numSamples/3, N); i++) samples.push_back(byDeg[i]);\n    shuffle(byDeg.begin(), byDeg.end(), rng);\n    for (int v : byDeg) if ((int)samples.size() < numSamples && find(samples.begin(), samples.end(), v) == samples.end())\n        samples.push_back(v);\n    numSamples = samples.size();\n    \n    origDist.resize(numSamples);\n    for (int i = 0; i < numSamples; i++) origDist[i] = dijkstraMask(samples[i], noEdge);\n    \n    double globalBest = 1e18;\n    vector<int> globalBestAssign;\n    \n    vector<double> timeLimits = {1.7, 3.5, 5.2};\n    \n    for (int restart = 0; restart < 3; restart++) {\n        auto now = chrono::steady_clock::now();\n        if (chrono::duration<double>(now - start).count() > 4.8) break;\n        \n        rng.seed(42 + restart * 1000);\n        initAssignment(restart == 0 ? 0 : 1);\n        \n        vector<double> dayCost(D + 1);\n        double cur = 0;\n        for (int d = 1; d <= D; d++) { dayCost[d] = evalDay(d); cur += dayCost[d]; }\n        \n        double bestScore = cur;\n        vector<int> bestAssign = assign_;\n        double initTemp = max(1.0, cur / D / 2);\n        double temp = initTemp;\n        int noImprove = 0;\n        \n        while (true) {\n            now = chrono::steady_clock::now();\n            if (chrono::duration<double>(now - start).count() > timeLimits[restart]) break;\n            \n            if (noImprove > 400) { temp = initTemp * 0.5; noImprove = 0; }\n            \n            int worstDay = 1, bestDay = 1;\n            for (int d = 2; d <= D; d++) {\n                if (dayCost[d] > dayCost[worstDay]) worstDay = d;\n                if (dayCost[d] < dayCost[bestDay] && cnt[d] < K) bestDay = d;\n            }\n            \n            int e1, d1, d2, moveType = rng() % 10;\n            bool isSwap = false;\n            int e2 = -1;\n            \n            if (moveType < 3) {\n                e1 = rng() % M; e2 = rng() % M;\n                if (assign_[e1] == assign_[e2]) continue;\n                d1 = assign_[e1]; d2 = assign_[e2];\n                swap(assign_[e1], assign_[e2]);\n                isSwap = true;\n            } else if (moveType < 6) {\n                e1 = rng() % M; d1 = assign_[e1]; d2 = rng() % D + 1;\n                if (d1 == d2 || cnt[d2] >= K) continue;\n                assign_[e1] = d2; cnt[d1]--; cnt[d2]++;\n            } else {\n                e1 = -1;\n                for (int i = 0; i < min(M/4, M) && e1 == -1; i++)\n                    if (assign_[critOrder[i]] == worstDay) e1 = critOrder[i];\n                if (e1 == -1) for (int i = 0; i < M; i++) if (assign_[i] == worstDay) { e1 = i; break; }\n                if (e1 == -1) continue;\n                d1 = worstDay; d2 = (cnt[bestDay] < K) ? bestDay : (rng() % D + 1);\n                if (d1 == d2 || cnt[d2] >= K) continue;\n                assign_[e1] = d2; cnt[d1]--; cnt[d2]++;\n            }\n            \n            double nc1 = evalDay(d1), nc2 = evalDay(d2);\n            double delta = (nc1 + nc2) - (dayCost[d1] + dayCost[d2]);\n            \n            if (delta < 0 || (rng() % 1000000) < 1000000 * exp(-delta / temp)) {\n                dayCost[d1] = nc1; dayCost[d2] = nc2; cur += delta;\n                if (cur < bestScore) { bestScore = cur; bestAssign = assign_; noImprove = 0; }\n                else noImprove++;\n            } else {\n                if (isSwap) swap(assign_[e1], assign_[e2]);\n                else { assign_[e1] = d1; cnt[d1]++; cnt[d2]--; }\n                noImprove++;\n            }\n            temp *= 0.99999;\n            if (temp < 0.01) temp = 0.01;\n        }\n        \n        if (bestScore < globalBest) { globalBest = bestScore; globalBestAssign = bestAssign; }\n    }\n    \n    for (int i = 0; i < M; i++) cout << globalBestAssign[i] << \" \\n\"[i == M-1];\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nint D;\nstring f[2][15], r[2][15];\n\nvector<tuple<int,int,int>> normalize(vector<tuple<int,int,int>> c) {\n    if (c.empty()) return c;\n    sort(c.begin(), c.end());\n    auto [mx,my,mz] = c[0];\n    for (auto& [x,y,z] : c) { x-=mx; y-=my; z-=mz; }\n    sort(c.begin(), c.end());\n    return c;\n}\n\nvector<tuple<int,int,int>> doRotate(vector<tuple<int,int,int>> c, int r) {\n    vector<tuple<int,int,int>> res;\n    for (auto [x,y,z] : c) {\n        int nx,ny,nz;\n        switch(r) {\n            case 0: nx=x;ny=y;nz=z;break; case 1: nx=x;ny=-z;nz=y;break;\n            case 2: nx=x;ny=-y;nz=-z;break; case 3: nx=x;ny=z;nz=-y;break;\n            case 4: nx=-x;ny=y;nz=-z;break; case 5: nx=-x;ny=-z;nz=-y;break;\n            case 6: nx=-x;ny=-y;nz=z;break; case 7: nx=-x;ny=z;nz=y;break;\n            case 8: nx=y;ny=-x;nz=z;break; case 9: nx=y;ny=-z;nz=-x;break;\n            case 10: nx=y;ny=x;nz=-z;break; case 11: nx=y;ny=z;nz=x;break;\n            case 12: nx=-y;ny=x;nz=z;break; case 13: nx=-y;ny=-z;nz=x;break;\n            case 14: nx=-y;ny=-x;nz=-z;break; case 15: nx=-y;ny=z;nz=-x;break;\n            case 16: nx=z;ny=y;nz=-x;break; case 17: nx=z;ny=x;nz=y;break;\n            case 18: nx=z;ny=-y;nz=x;break; case 19: nx=z;ny=-x;nz=-y;break;\n            case 20: nx=-z;ny=y;nz=x;break; case 21: nx=-z;ny=-x;nz=y;break;\n            case 22: nx=-z;ny=-y;nz=-x;break; default: nx=-z;ny=x;nz=-y;break;\n        }\n        res.push_back({nx,ny,nz});\n    }\n    return normalize(res);\n}\n\nvector<tuple<int,int,int>> canonical(vector<tuple<int,int,int>> c) {\n    auto best = normalize(c);\n    for (int r = 1; r < 24; r++) { auto t = doRotate(c,r); if (t < best) best = t; }\n    return best;\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n    cin >> D;\n    for (int i = 0; i < 2; i++) { for (int k = 0; k < D; k++) cin >> f[i][k]; for (int k = 0; k < D; k++) cin >> r[i][k]; }\n    \n    auto idx = [&](int x,int y,int z) { return x*D*D+y*D+z; };\n    auto valid = [&](int a,int x,int y,int z) { return f[a][z][x]=='1' && r[a][z][y]=='1'; };\n    int dx[]={1,-1,0,0,0,0}, dy[]={0,0,1,-1,0,0}, dz[]={0,0,0,0,1,-1};\n    \n    mt19937 rng(12345);\n    double bestCost = 1e18;\n    vector<int> bestB[2];\n    int bestN = 0;\n    auto startTime = chrono::steady_clock::now();\n    \n    for (int iter = 0; ; iter++) {\n        if (chrono::duration<double>(chrono::steady_clock::now() - startTime).count() > 5.5) break;\n        \n        vector<int> b[2]; for (int i=0;i<2;i++) b[i].assign(D*D*D,0);\n        int n = 0; double sharedCost = 0;\n        \n        for (int x=0;x<D;x++) for (int y=0;y<D;y++) for (int z=0;z<D;z++)\n            if (valid(0,x,y,z) && valid(1,x,y,z) && b[0][idx(x,y,z)]==0) {\n                n++; int vol=0;\n                queue<tuple<int,int,int>> q; q.push({x,y,z});\n                b[0][idx(x,y,z)] = b[1][idx(x,y,z)] = n; vol++;\n                while (!q.empty()) {\n                    auto [cx,cy,cz] = q.front(); q.pop();\n                    for (int d=0;d<6;d++) {\n                        int nx=cx+dx[d],ny=cy+dy[d],nz=cz+dz[d];\n                        if (nx>=0&&nx<D&&ny>=0&&ny<D&&nz>=0&&nz<D&&valid(0,nx,ny,nz)&&valid(1,nx,ny,nz)&&b[0][idx(nx,ny,nz)]==0) {\n                            b[0][idx(nx,ny,nz)] = b[1][idx(nx,ny,nz)] = n; vol++; q.push({nx,ny,nz});\n                        }\n                    }\n                }\n                sharedCost += 1.0/vol;\n            }\n        \n        vector<tuple<int,int,int>> cells[2];\n        for (int arr=0;arr<2;arr++) {\n            set<int> needF,needR;\n            for (int z=0;z<D;z++) {\n                for (int x=0;x<D;x++) if (f[arr][z][x]=='1') { bool c=false; for (int y=0;y<D&&!c;y++) if (b[arr][idx(x,y,z)]>0) c=true; if (!c) needF.insert(z*D+x); }\n                for (int y=0;y<D;y++) if (r[arr][z][y]=='1') { bool c=false; for (int x=0;x<D&&!c;x++) if (b[arr][idx(x,y,z)]>0) c=true; if (!c) needR.insert(z*D+y); }\n            }\n            vector<tuple<int,int,int,int>> cands;\n            for (int x=0;x<D;x++) for (int y=0;y<D;y++) for (int z=0;z<D;z++)\n                if (valid(arr,x,y,z)&&b[arr][idx(x,y,z)]==0) cands.push_back({x,y,z,0});\n            if (iter>0) shuffle(cands.begin(),cands.end(),rng);\n            while (!needF.empty()||!needR.empty()) {\n                int bi=-1,bs=0;\n                for (int i=0;i<(int)cands.size();i++) {\n                    auto& [x,y,z,u] = cands[i]; if (u) continue;\n                    int sc = (needF.count(z*D+x)?1:0) + (needR.count(z*D+y)?1:0);\n                    if (sc>bs) { bs=sc; bi=i; }\n                }\n                if (bs==0) break;\n                auto& [x,y,z,u] = cands[bi]; u=1;\n                cells[arr].push_back({x,y,z});\n                needF.erase(z*D+x); needR.erase(z*D+y);\n            }\n        }\n        \n        vector<pair<vector<tuple<int,int,int>>,vector<tuple<int,int,int>>>> comps[2];\n        set<tuple<int,int,int>> cellSet[2];\n        for (int arr=0;arr<2;arr++) for (auto c:cells[arr]) cellSet[arr].insert(c);\n        for (int arr=0;arr<2;arr++) {\n            set<tuple<int,int,int>> vis;\n            for (auto st:cells[arr]) if (!vis.count(st)) {\n                vector<tuple<int,int,int>> comp;\n                queue<tuple<int,int,int>> q; q.push(st); vis.insert(st);\n                while (!q.empty()) {\n                    auto [cx,cy,cz]=q.front(); q.pop(); comp.push_back({cx,cy,cz});\n                    for (int d=0;d<6;d++) { tuple<int,int,int> nb={cx+dx[d],cy+dy[d],cz+dz[d]}; if (cellSet[arr].count(nb)&&!vis.count(nb)) { vis.insert(nb); q.push(nb); } }\n                }\n                comps[arr].push_back({comp,canonical(comp)});\n            }\n            sort(comps[arr].begin(),comps[arr].end(),[](auto& a,auto& b){ return a.first.size()>b.first.size(); });\n        }\n        \n        // Try matching from both directions\n        auto tryMatch = [&](int first) -> pair<double,vector<pair<int,int>>> {\n            vector<bool> u0(comps[0].size()),u1(comps[1].size());\n            vector<pair<int,int>> matches;\n            double mc = 0;\n            auto& primary = (first==0) ? comps[0] : comps[1];\n            auto& secondary = (first==0) ? comps[1] : comps[0];\n            auto& up = (first==0) ? u0 : u1;\n            auto& us = (first==0) ? u1 : u0;\n            for (int i=0;i<(int)primary.size();i++) if (!up[i])\n                for (int j=0;j<(int)secondary.size();j++)\n                    if (!us[j]&&primary[i].second==secondary[j].second) {\n                        mc+=1.0/primary[i].first.size();\n                        up[i]=us[j]=true;\n                        if (first==0) matches.push_back({i,j}); else matches.push_back({j,i});\n                        break;\n                    }\n            int um0=0,um1=0;\n            for (int i=0;i<(int)comps[0].size();i++) if (!u0[i]) um0+=comps[0][i].first.size();\n            for (int j=0;j<(int)comps[1].size();j++) if (!u1[j]) um1+=comps[1][j].first.size();\n            return {mc+max(um0,um1), matches};\n        };\n        \n        auto [cost0, matches0] = tryMatch(0);\n        auto [cost1, matches1] = tryMatch(1);\n        auto& matches = (cost0 <= cost1) ? matches0 : matches1;\n        double matchCost = min(cost0, cost1);\n        \n        vector<bool> u0(comps[0].size()),u1(comps[1].size());\n        for (auto [i,j] : matches) {\n            n++; sharedCost+=1.0/comps[0][i].first.size();\n            for (auto [x,y,z]:comps[0][i].first) b[0][idx(x,y,z)]=n;\n            for (auto [x,y,z]:comps[1][j].first) b[1][idx(x,y,z)]=n;\n            u0[i]=u1[j]=true;\n        }\n        \n        vector<tuple<int,int,int>> unmatch[2];\n        for (int i=0;i<(int)comps[0].size();i++) if (!u0[i]) for (auto c:comps[0][i].first) unmatch[0].push_back(c);\n        for (int j=0;j<(int)comps[1].size();j++) if (!u1[j]) for (auto c:comps[1][j].first) unmatch[1].push_back(c);\n        \n        int m0=unmatch[0].size(),m1=unmatch[1].size();\n        double cost = sharedCost + max(m0,m1);\n        \n        if (cost < bestCost) {\n            bestCost=cost; bestN=n+max(m0,m1); bestB[0]=b[0]; bestB[1]=b[1];\n            for (int i=0;i<m0;i++) { auto [x,y,z]=unmatch[0][i]; bestB[0][idx(x,y,z)]=n+1+i; }\n            for (int i=0;i<m1;i++) { auto [x,y,z]=unmatch[1][i]; bestB[1][idx(x,y,z)]=n+1+i; }\n        }\n    }\n    \n    cout << bestN << \"\\n\";\n    for (int i=0;i<2;i++) { for (int j=0;j<D*D*D;j++) { if (j) cout<<\" \"; cout<<bestB[i][j]; } cout<<\"\\n\"; }\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, K;\nvector<pair<int,int>> V, R;\nvector<tuple<int,int,long long>> E;\nvector<vector<pair<int,int>>> adj;\nvector<vector<long long>> distVV;\nvector<vector<int>> parentV;\n\ndouble getDist(int i, int k) {\n    double dx = V[i].first - R[k].first, dy = V[i].second - R[k].second;\n    return sqrt(dx*dx + dy*dy);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> K;\n    V.resize(N); R.resize(K); E.resize(M); adj.resize(N);\n    \n    for(int i = 0; i < N; i++) cin >> V[i].first >> V[i].second;\n    for(int j = 0; j < M; j++) {\n        int u, v; long long w;\n        cin >> u >> v >> w; u--; v--;\n        E[j] = {u, v, w};\n        adj[u].push_back({v, j});\n        adj[v].push_back({u, j});\n    }\n    for(int k = 0; k < K; k++) cin >> R[k].first >> R[k].second;\n    \n    // Precompute distances\n    vector<vector<double>> distVR(N, vector<double>(K));\n    for(int i = 0; i < N; i++)\n        for(int k = 0; k < K; k++)\n            distVR[i][k] = getDist(i, k);\n    \n    // All-pairs shortest paths\n    distVV.assign(N, vector<long long>(N, LLONG_MAX/2));\n    parentV.assign(N, vector<int>(N, -1));\n    \n    for(int s = 0; s < N; s++) {\n        distVV[s][s] = 0;\n        priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> pq;\n        pq.push({0, s});\n        while(!pq.empty()) {\n            auto [d, u] = pq.top(); pq.pop();\n            if(d > distVV[s][u]) continue;\n            for(auto [v, eid] : adj[u]) {\n                long long w = get<2>(E[eid]);\n                if(distVV[s][u] + w < distVV[s][v]) {\n                    distVV[s][v] = distVV[s][u] + w;\n                    parentV[s][v] = u;\n                    pq.push({distVV[s][v], v});\n                }\n            }\n        }\n    }\n    \n    auto computeP = [&](const vector<int>& asgn) {\n        vector<int> P(N, 0);\n        for(int k = 0; k < K; k++) {\n            int v = asgn[k];\n            P[v] = max(P[v], (int)ceil(distVR[v][k] - 1e-9));\n        }\n        return P;\n    };\n    \n    auto buildTree = [&](const vector<int>& P) {\n        vector<int> B(M, 0);\n        for(int i = 0; i < N; i++) if(P[i] > 0) {\n            int cur = i;\n            while(cur != 0 && parentV[0][cur] != -1) {\n                int p = parentV[0][cur];\n                for(auto& [nxt, eid] : adj[cur]) if(nxt == p) { B[eid] = 1; break; }\n                cur = p;\n            }\n        }\n        return B;\n    };\n    \n    auto getReachable = [&](const vector<int>& B) {\n        vector<int> reach; vector<bool> vis(N, false);\n        queue<int> q; q.push(0); vis[0] = true;\n        while(!q.empty()) {\n            int u = q.front(); q.pop(); reach.push_back(u);\n            for(auto& [v, eid] : adj[u]) if(B[eid] && !vis[v]) { vis[v] = true; q.push(v); }\n        }\n        return reach;\n    };\n    \n    auto calcCost = [&](const vector<int>& P, const vector<int>& B) {\n        long long cost = 0;\n        for(int i = 0; i < N; i++) cost += (long long)P[i] * P[i];\n        for(int j = 0; j < M; j++) if(B[j]) cost += get<2>(E[j]);\n        return cost;\n    };\n    \n    vector<int> bestP(N), bestB(M), bestAsgn(K);\n    long long bestCost = LLONG_MAX;\n    \n    for(double factor : {0.0, 0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0}) {\n        vector<int> asgn(K);\n        for(int k = 0; k < K; k++) {\n            int best = -1; double bestScore = 1e18;\n            for(int i = 0; i < N; i++) {\n                if(distVR[i][k] > 5000) continue;\n                double score = distVR[i][k] * distVR[i][k] + factor * distVV[0][i];\n                if(score < bestScore) { bestScore = score; best = i; }\n            }\n            asgn[k] = best;\n        }\n        \n        for(int phase = 0; phase < 3; phase++) {\n            auto P = computeP(asgn);\n            auto B = buildTree(P);\n            \n            for(int iter = 0; iter < 20; iter++) {\n                auto reach = getReachable(B);\n                bool improved = false;\n                for(int k = 0; k < K; k++) {\n                    double curD = distVR[asgn[k]][k];\n                    for(int v : reach) {\n                        if(distVR[v][k] < curD - 0.01 && distVR[v][k] <= 5000) {\n                            asgn[k] = v; curD = distVR[v][k]; improved = true;\n                        }\n                    }\n                }\n                if(!improved) break;\n                P = computeP(asgn); B = buildTree(P);\n            }\n            \n            // Outlier optimization\n            for(int iter = 0; iter < 10; iter++) {\n                auto reach = getReachable(B);\n                vector<vector<int>> vRes(N);\n                for(int k = 0; k < K; k++) vRes[asgn[k]].push_back(k);\n                \n                bool improved = false;\n                for(int v : reach) {\n                    if(vRes[v].size() <= 1) continue;\n                    int fk = -1; double maxD = 0;\n                    for(int k : vRes[v]) if(distVR[v][k] > maxD) { maxD = distVR[v][k]; fk = k; }\n                    \n                    for(int nv : reach) {\n                        if(nv == v || distVR[nv][fk] > 5000) continue;\n                        double newMaxV = 0;\n                        for(int k : vRes[v]) if(k != fk) newMaxV = max(newMaxV, distVR[v][k]);\n                        double oldMaxNV = 0;\n                        for(int k : vRes[nv]) oldMaxNV = max(oldMaxNV, distVR[nv][k]);\n                        double newMaxNV = max(oldMaxNV, distVR[nv][fk]);\n                        double delta = (newMaxV*newMaxV - maxD*maxD) + (newMaxNV*newMaxNV - oldMaxNV*oldMaxNV);\n                        if(delta < -1) { asgn[fk] = nv; improved = true; break; }\n                    }\n                }\n                if(!improved) break;\n                P = computeP(asgn); B = buildTree(P);\n            }\n        }\n        \n        auto P = computeP(asgn);\n        auto B = buildTree(P);\n        long long cost = calcCost(P, B);\n        if(cost < bestCost) { bestCost = cost; bestP = P; bestB = B; bestAsgn = asgn; }\n    }\n    \n    for(int i = 0; i < N; i++) cout << bestP[i] << \" \\n\"[i==N-1];\n    for(int j = 0; j < M; j++) cout << bestB[j] << \" \\n\"[j==M-1];\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nint b[N][N];\nvector<tuple<int, int, int, int>> ops;\n\nvoid do_swap(int x1, int y1, int x2, int y2) {\n    ops.push_back({x1, y1, x2, y2});\n    swap(b[x1][y1], b[x2][y2]);\n}\n\nvoid sift_down(int x, int y) {\n    while (x < N - 1) {\n        int min_child_y = (b[x + 1][y + 1] < b[x + 1][y]) ? (y + 1) : y;\n        if (b[x][y] > b[x + 1][min_child_y]) {\n            do_swap(x, y, x + 1, min_child_y);\n            x = x + 1;\n            y = min_child_y;\n        } else {\n            break;\n        }\n    }\n}\n\nbool has_violation(int x, int y) {\n    if (x >= N - 1) return false;\n    return b[x][y] > b[x + 1][y] || b[x][y] > b[x + 1][y + 1];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    for (int x = 0; x < N; x++) {\n        for (int y = 0; y <= x; y++) {\n            cin >> b[x][y];\n        }\n    }\n    \n    // Greedy: always process the highest-valued violation\n    while (true) {\n        int best_val = -1, best_x = -1, best_y = -1;\n        for (int x = 0; x < N - 1; x++) {\n            for (int y = 0; y <= x; y++) {\n                if (has_violation(x, y) && b[x][y] > best_val) {\n                    best_val = b[x][y];\n                    best_x = x;\n                    best_y = y;\n                }\n            }\n        }\n        if (best_val == -1) break;\n        sift_down(best_x, best_y);\n    }\n    \n    cout << ops.size() << \"\\n\";\n    for (auto& [x1, y1, x2, y2] : ops) {\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;\nint ex, ey;\nconst int dx[] = {-1, 1, 0, 0};\nconst int dy[] = {0, 0, -1, 1};\nvector<vector<int>> grid;\nvector<vector<int>> initDepth;\n\nvoid computeInitDepth() {\n    initDepth.assign(D, vector<int>(D, -1));\n    queue<pair<int,int>> q;\n    q.push({ex, ey});\n    initDepth[ex][ey] = 0;\n    \n    while (!q.empty()) {\n        auto [x, y] = q.front(); q.pop();\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx >= 0 && nx < D && ny >= 0 && ny < D && initDepth[nx][ny] == -1 && grid[nx][ny] != -2) {\n                initDepth[nx][ny] = initDepth[x][y] + 1;\n                q.push({nx, ny});\n            }\n        }\n    }\n}\n\nint countReachableEmpty() {\n    int count = 0;\n    vector<vector<bool>> vis(D, vector<bool>(D, false));\n    queue<pair<int,int>> q;\n    q.push({ex, ey});\n    vis[ex][ey] = true;\n    \n    while (!q.empty()) {\n        auto [x, y] = q.front(); q.pop();\n        if (!(x == ex && y == ey) && grid[x][y] == -1) count++;\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx >= 0 && nx < D && ny >= 0 && ny < D && !vis[nx][ny] && grid[nx][ny] == -1) {\n                vis[nx][ny] = true;\n                q.push({nx, ny});\n            }\n        }\n    }\n    return count;\n}\n\nvector<pair<int,int>> findReachableEmpty() {\n    vector<pair<int,int>> result;\n    vector<vector<bool>> vis(D, vector<bool>(D, false));\n    queue<pair<int,int>> q;\n    q.push({ex, ey});\n    vis[ex][ey] = true;\n    \n    while (!q.empty()) {\n        auto [x, y] = q.front(); q.pop();\n        if (!(x == ex && y == ey)) result.push_back({x, y});\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx >= 0 && nx < D && ny >= 0 && ny < D && !vis[nx][ny] && grid[nx][ny] == -1) {\n                vis[nx][ny] = true;\n                q.push({nx, ny});\n            }\n        }\n    }\n    return result;\n}\n\nvector<pair<int,int>> findReachableContainers() {\n    vector<pair<int,int>> result;\n    vector<vector<bool>> vis(D, vector<bool>(D, false));\n    queue<pair<int,int>> q;\n    q.push({ex, ey});\n    vis[ex][ey] = true;\n    \n    while (!q.empty()) {\n        auto [x, y] = q.front(); q.pop();\n        for (int d = 0; d < 4; d++) {\n            int nx = x + dx[d], ny = y + dy[d];\n            if (nx >= 0 && nx < D && ny >= 0 && ny < D && !vis[nx][ny] && grid[nx][ny] != -2) {\n                vis[nx][ny] = true;\n                if (grid[nx][ny] >= 0) result.push_back({nx, ny});\n                else q.push({nx, ny});\n            }\n        }\n    }\n    return result;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> D >> N;\n    ex = 0; ey = (D - 1) / 2;\n    grid.assign(D, vector<int>(D, -1));\n    \n    for (int i = 0; i < N; i++) {\n        int x, y; cin >> x >> y;\n        grid[x][y] = -2;\n    }\n    \n    computeInitDepth();\n    int total = D * D - 1 - N;\n    \n    for (int iter = 0; iter < total; iter++) {\n        int t; cin >> t;\n        \n        vector<pair<int,int>> reach = findReachableEmpty();\n        int currentCount = (int)reach.size();\n        \n        vector<pair<int, pair<int,int>>> sortedSafe;\n        for (int i = 0; i < (int)reach.size(); i++) {\n            auto [px, py] = reach[i];\n            grid[px][py] = 999;\n            int newCount = countReachableEmpty();\n            grid[px][py] = -1;\n            if (newCount == currentCount - 1) {\n                int score = initDepth[px][py] * 1000 + i;\n                sortedSafe.push_back({score, {px, py}});\n            }\n        }\n        \n        pair<int,int> best;\n        if (sortedSafe.empty()) {\n            best = reach.back();\n        } else {\n            sort(sortedSafe.begin(), sortedSafe.end());\n            \n            int idx;\n            if (sortedSafe.size() == 1 || total <= 1) {\n                idx = 0;\n            } else {\n                // Square root mapping: gives more spread for low-numbered containers\n                double normalized = (double)t / (total - 1);\n                double mapped = sqrt(normalized);\n                idx = (int)(mapped * (sortedSafe.size() - 1) + 0.5);\n                idx = max(0, min((int)sortedSafe.size() - 1, idx));\n            }\n            best = sortedSafe[idx].second;\n        }\n        \n        grid[best.first][best.second] = t;\n        cout << best.first << \" \" << best.second << endl;\n    }\n    \n    for (int iter = 0; iter < total; iter++) {\n        vector<pair<int,int>> reachable = findReachableContainers();\n        \n        pair<int,int> best = reachable[0];\n        for (auto& pos : reachable) {\n            if (grid[pos.first][pos.second] < grid[best.first][best.second]) {\n                best = pos;\n            }\n        }\n        \n        cout << best.first << \" \" << best.second << \"\\n\";\n        grid[best.first][best.second] = -1;\n    }\n    \n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint n, m;\nint dx[] = {0, 0, 1, -1};\nint dy[] = {1, -1, 0, 0};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> n >> m;\n    vector<vector<int>> orig(n, vector<int>(n));\n    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cin >> orig[i][j];\n    \n    set<int> adjToZero;\n    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++)\n        if (i == 0 || i == n-1 || j == 0 || j == n-1) adjToZero.insert(orig[i][j]);\n    \n    map<pair<int,int>, int> initEdge;\n    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) {\n        int c = orig[i][j];\n        if (i == 0 || i == n-1 || j == 0 || j == n-1) initEdge[{0,c}]++;\n        if (j+1 < n && orig[i][j+1] != c) initEdge[{min(c,orig[i][j+1]), max(c,orig[i][j+1])}]++;\n        if (i+1 < n && orig[i+1][j] != c) initEdge[{min(c,orig[i+1][j]), max(c,orig[i+1][j])}]++;\n    }\n    set<pair<int,int>> required;\n    for (auto& [p, cnt] : initEdge) if (cnt > 0) required.insert(p);\n    \n    vector<int> initCount(m+1);\n    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) initCount[orig[i][j]]++;\n    \n    auto start = chrono::steady_clock::now();\n    vector<vector<int>> best = orig;\n    int bestScore = 0;\n    \n    auto output = [&](vector<vector<int>>& g) {\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < n; j++) { cout << g[i][j]; if (j < n-1) cout << \" \"; }\n            cout << \"\\n\";\n        }\n        cout.flush();\n    };\n    output(best);\n    \n    auto solve = [&](int seed) {\n        auto grid = orig;\n        auto edgeCount = initEdge;\n        auto colorCount = initCount;\n        mt19937 rng(seed);\n        \n        auto canRemove = [&](int i, int j) -> bool {\n            int c = grid[i][j];\n            if (c == 0 || colorCount[c] <= 1) return false;\n            \n            vector<pair<int,int>> sameNeigh;\n            for (int d = 0; d < 4; d++) {\n                int ni = i + dx[d], nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = grid[ni][nj];\n                    if (nc == c) sameNeigh.push_back({ni, nj});\n                    else if (nc != 0 && !adjToZero.count(nc)) return false;\n                }\n            }\n            if (sameNeigh.empty()) return false;\n            \n            map<pair<int,int>, int> delta;\n            if (i == 0 || i == n-1 || j == 0 || j == n-1) delta[{0, c}]--;\n            for (int d = 0; d < 4; d++) {\n                int ni = i + dx[d], nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n                    int nc = grid[ni][nj];\n                    if (nc != c && nc != 0) { delta[{min(c,nc), max(c,nc)}]--; delta[{0, nc}]++; }\n                }\n            }\n            for (auto& [e, d] : delta)\n                if (required.count(e) && edgeCount[e] + d <= 0) return false;\n            \n            // Check connectivity\n            if (sameNeigh.size() >= 2) {\n                grid[i][j] = 0;\n                vector<vector<bool>> vis(n, vector<bool>(n));\n                queue<pair<int,int>> q;\n                q.push(sameNeigh[0]);\n                vis[sameNeigh[0].first][sameNeigh[0].second] = true;\n                int toFind = sameNeigh.size() - 1;\n                while (!q.empty() && toFind > 0) {\n                    auto [x, y] = q.front(); q.pop();\n                    for (int d = 0; d < 4; d++) {\n                        int nx = x + dx[d], ny = y + dy[d];\n                        if (nx >= 0 && nx < n && ny >= 0 && ny < n && !vis[nx][ny] && grid[nx][ny] == c) {\n                            vis[nx][ny] = true;\n                            q.push({nx, ny});\n                            for (size_t k = 1; k < sameNeigh.size(); k++)\n                                if (sameNeigh[k] == make_pair(nx, ny)) toFind--;\n                        }\n                    }\n                }\n                if (toFind > 0) { grid[i][j] = c; return false; }\n            } else {\n                grid[i][j] = 0;\n            }\n            \n            for (auto& [e, d] : delta) edgeCount[e] += d;\n            colorCount[c]--;\n            return true;\n        };\n        \n        // BFS from boundary\n        vector<vector<int>> dist(n, vector<int>(n, -1));\n        vector<pair<int,int>> order;\n        queue<pair<int,int>> bq;\n        for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) {\n            if (i == 0 || i == n-1 || j == 0 || j == n-1) { \n                dist[i][j] = 0; bq.push({i,j}); order.push_back({i,j});\n            }\n        }\n        while (!bq.empty()) {\n            auto [i, j] = bq.front(); bq.pop();\n            for (int d = 0; d < 4; d++) {\n                int ni = i + dx[d], nj = j + dy[d];\n                if (ni >= 0 && ni < n && nj >= 0 && nj < n && dist[ni][nj] == -1) {\n                    dist[ni][nj] = dist[i][j] + 1;\n                    bq.push({ni, nj});\n                    order.push_back({ni, nj});\n                }\n            }\n        }\n        \n        // Shuffle within same distance\n        for (int d = 0; d <= 25; d++) {\n            int start_idx = 0, end_idx = 0;\n            for (size_t i = 0; i < order.size(); i++) {\n                if (dist[order[i].first][order[i].second] == d) {\n                    if (start_idx == end_idx) start_idx = i;\n                    end_idx = i + 1;\n                }\n            }\n            if (end_idx > start_idx)\n                shuffle(order.begin() + start_idx, order.begin() + end_idx, rng);\n        }\n        \n        vector<vector<bool>> adj0(n, vector<bool>(n));\n        for (int i = 0; i < n; i++) for (int j = 0; j < n; j++)\n            adj0[i][j] = (dist[i][j] == 0);\n        \n        for (int round = 0; round < 10; round++) {\n            bool changed = false;\n            for (auto [i, j] : order) {\n                if (grid[i][j] != 0 && adj0[i][j] && canRemove(i, j)) {\n                    for (int d = 0; d < 4; d++) {\n                        int ni = i + dx[d], nj = j + dy[d];\n                        if (ni >= 0 && ni < n && nj >= 0 && nj < n) adj0[ni][nj] = true;\n                    }\n                    changed = true;\n                }\n            }\n            if (!changed) break;\n        }\n        \n        return grid;\n    };\n    \n    for (int seed = 0; seed < 800; seed++) {\n        auto elapsed = chrono::steady_clock::now() - start;\n        if (chrono::duration_cast<chrono::milliseconds>(elapsed).count() > 1900) break;\n        \n        auto grid = solve(seed);\n        int sc = 0;\n        for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (grid[i][j] == 0) sc++;\n        if (sc > bestScore) { bestScore = sc; best = grid; output(best); }\n    }\n    \n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, D, Q;\nint query_count = 0;\n\nchar query(const vector<int>& L, const vector<int>& R) {\n    cout << L.size() << \" \" << R.size();\n    for (int x : L) cout << \" \" << x;\n    for (int x : R) cout << \" \" << x;\n    cout << \"\\n\" << flush;\n    char c;\n    cin >> c;\n    query_count++;\n    return c;\n}\n\nvector<int> sorted_items;\n\nvoid merge_sort(int l, int r) {\n    if (r - l <= 1 || query_count >= Q) return;\n    int m = (l + r) / 2;\n    merge_sort(l, m);\n    merge_sort(m, r);\n    \n    vector<int> left(sorted_items.begin() + l, sorted_items.begin() + m);\n    vector<int> right(sorted_items.begin() + m, sorted_items.begin() + r);\n    \n    int i = 0, j = 0, k = l;\n    while (i < (int)left.size() && j < (int)right.size()) {\n        if (query_count >= Q) {\n            while (i < (int)left.size()) sorted_items[k++] = left[i++];\n            while (j < (int)right.size()) sorted_items[k++] = right[j++];\n            return;\n        }\n        char c = query({left[i]}, {right[j]});\n        if (c != '>') sorted_items[k++] = left[i++];\n        else sorted_items[k++] = right[j++];\n    }\n    while (i < (int)left.size()) sorted_items[k++] = left[i++];\n    while (j < (int)right.size()) sorted_items[k++] = right[j++];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> D >> Q;\n    \n    sorted_items.resize(N);\n    iota(sorted_items.begin(), sorted_items.end(), 0);\n    merge_sort(0, N);\n    \n    vector<int> rank_of(N);\n    for (int i = 0; i < N; i++) rank_of[sorted_items[i]] = i;\n    \n    vector<double> w(N);\n    for (int i = 0; i < N; i++) w[i] = i + 1;\n    \n    int remaining = Q - query_count;\n    int est_budget = remaining / 3;\n    \n    for (int j = N - 1; j >= 1 && est_budget > 0; j--) {\n        int lo = 1, hi = j;\n        while (lo < hi && est_budget > 0 && query_count < Q) {\n            int mid = (lo + hi) / 2;\n            vector<int> L, R = {sorted_items[j]};\n            for (int t = 0; t < mid; t++) L.push_back(sorted_items[t]);\n            char c = query(L, R);\n            est_budget--;\n            if (c == '>' || c == '=') hi = mid;\n            else lo = mid + 1;\n        }\n        double sum = 0;\n        for (int t = 0; t < lo; t++) sum += w[t];\n        w[j] = max(w[j], sum);\n    }\n    \n    vector<double> set_weight(D, 0);\n    vector<int> assignment(N);\n    vector<vector<int>> sets(D);\n    \n    for (int i = N - 1; i >= 0; i--) {\n        int item = sorted_items[i];\n        int best = 0;\n        for (int j = 1; j < D; j++)\n            if (set_weight[j] < set_weight[best]) best = j;\n        assignment[item] = best;\n        set_weight[best] += w[i];\n        sets[best].push_back(item);\n    }\n    \n    bool improved = true;\n    while (improved && query_count + 3 < Q) {\n        improved = false;\n        for (int a = 0; a < D && query_count + 3 < Q; a++) {\n            for (int b = a + 1; b < D && query_count + 3 < Q; b++) {\n                if (sets[a].empty() || sets[b].empty()) continue;\n                \n                char cmp = query(sets[a], sets[b]);\n                if (cmp == '=') continue;\n                \n                int heavy = (cmp == '>') ? a : b;\n                int light = (cmp == '>') ? b : a;\n                if (sets[heavy].size() <= 1) continue;\n                \n                vector<pair<int,int>> ranked;\n                for (int item : sets[heavy])\n                    ranked.push_back({rank_of[item], item});\n                sort(ranked.begin(), ranked.end());\n                \n                int tries = min((int)ranked.size() - 1, 2);\n                for (int k = 0; k < tries && query_count + 1 < Q; k++) {\n                    int move_item = ranked[k].second;\n                    int move_rank = ranked[k].first;\n                    \n                    vector<int> new_heavy, new_light = sets[light];\n                    for (int item : sets[heavy])\n                        if (item != move_item) new_heavy.push_back(item);\n                    new_light.push_back(move_item);\n                    \n                    char new_cmp = query(new_heavy, new_light);\n                    \n                    if (new_cmp == '=' || new_cmp != cmp) {\n                        sets[heavy] = new_heavy;\n                        sets[light] = new_light;\n                        assignment[move_item] = light;\n                        set_weight[heavy] -= w[move_rank];\n                        set_weight[light] += w[move_rank];\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n        }\n    }\n    \n    while (query_count < Q) query({sorted_items[0]}, {sorted_items[1]});\n    \n    for (int i = 0; i < N; i++)\n        cout << assignment[i] << \" \\n\"[i == N - 1];\n    \n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint simulate(const vector<vector<int>>& init_stacks, int n, int m, \n             vector<pair<int,int>>& ops, mt19937& rng, int noise_level, int policy, bool random_mode) {\n    \n    vector<vector<int>> stacks = init_stacks;\n    vector<int> pos(n + 1);\n    vector<int> stack_min(m, INT_MAX);\n    \n    for (int i = 0; i < m; i++) {\n        for (int b : stacks[i]) {\n            pos[b] = i;\n            stack_min[i] = min(stack_min[i], b);\n        }\n    }\n    \n    ops.clear();\n    int total_energy = 0;\n    \n    for (int v = 1; v <= n; v++) {\n        int si = pos[v];\n        auto& st = stacks[si];\n        \n        int idx = 0;\n        while (st[idx] != v) idx++;\n        \n        if (idx < (int)st.size() - 1) {\n            int cnt = (int)st.size() - idx - 1;\n            int bottom_box = st[idx + 1];\n            \n            int max_moving = 0, min_moving = n + 1;\n            for (int j = idx + 1; j < (int)st.size(); j++) {\n                max_moving = max(max_moving, st[j]);\n                min_moving = min(min_moving, st[j]);\n            }\n            \n            int best_dest = -1;\n            \n            if (random_mode && (rng() % 15) == 0) {\n                best_dest = rng() % m;\n                if (best_dest >= si) best_dest = (best_dest + 1) % m;\n                if (best_dest == si) best_dest = (si + 1) % m;\n            } else {\n                int best_score = INT_MIN;\n                \n                for (int i = 0; i < m; i++) {\n                    if (i == si) continue;\n                    \n                    int score = 0;\n                    int empty_bonus = n * 3;\n                    int safe_bonus = n * 3;\n                    int top_bonus = 50;\n                    int height_penalty = 2;\n                    int unsafe_cnt_mult = 3;\n                    int empty_extra = n - min_moving;\n                    \n                    switch (policy) {\n                        case 0: break;\n                        case 1: empty_bonus = n * 4; break;\n                        case 2: safe_bonus = n * 4; top_bonus = 80; break;\n                        case 3: height_penalty = 4; break;\n                        case 4: top_bonus = 100; break;\n                        case 5: unsafe_cnt_mult = 2; break;\n                        case 6: empty_bonus = n * 2; safe_bonus = n * 4; break;\n                        case 7: unsafe_cnt_mult = 4; height_penalty = 1; break;\n                        case 8: empty_bonus = n * 5; height_penalty = 3; break;\n                        case 9: top_bonus = 30; unsafe_cnt_mult = 4; break;\n                        case 10: empty_extra = min_moving; unsafe_cnt_mult = 2; break;\n                        case 11: height_penalty = 5; top_bonus = 40; break;\n                        case 12: safe_bonus = n * 2; unsafe_cnt_mult = 1; break;\n                        case 13: top_bonus = 150; height_penalty = 3; break;\n                        case 14: unsafe_cnt_mult = 5; empty_bonus = n * 4; break;\n                        case 15: safe_bonus = n * 5; height_penalty = 1; break;\n                        case 16: empty_bonus = n * 3; top_bonus = 70; height_penalty = 3; break;\n                        case 17: unsafe_cnt_mult = 3; empty_extra = 0; break;\n                    }\n                    \n                    if (stacks[i].empty()) {\n                        score = empty_bonus + empty_extra;\n                    } else {\n                        int min_d = stack_min[i];\n                        \n                        if (min_d > min_moving) {\n                            score = safe_bonus;\n                            if (stacks[i].back() > max_moving) {\n                                score += top_bonus;\n                            }\n                        } else {\n                            score = min_d - cnt * unsafe_cnt_mult;\n                        }\n                        \n                        score -= (int)stacks[i].size() * height_penalty;\n                    }\n                    \n                    if (noise_level > 0) {\n                        score += rng() % (noise_level + 1);\n                    }\n                    \n                    if (score > best_score) {\n                        best_score = score;\n                        best_dest = i;\n                    }\n                }\n            }\n            \n            total_energy += cnt + 1;\n            ops.push_back({bottom_box, best_dest + 1});\n            \n            for (int j = idx + 1; j < (int)st.size(); j++) {\n                int b = st[j];\n                stacks[best_dest].push_back(b);\n                pos[b] = best_dest;\n                stack_min[best_dest] = min(stack_min[best_dest], b);\n            }\n            st.resize(idx + 1);\n            stack_min[si] = st.empty() ? INT_MAX : *min_element(st.begin(), st.end());\n        }\n        \n        ops.push_back({v, 0});\n        st.pop_back();\n        if (st.empty()) stack_min[si] = INT_MAX;\n        else if (stack_min[si] == v) stack_min[si] = *min_element(st.begin(), st.end());\n    }\n    \n    return total_energy;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n, m;\n    cin >> n >> m;\n    \n    vector<vector<int>> init_stacks(m);\n    \n    for (int i = 0; i < m; i++) {\n        int h = n / m;\n        for (int j = 0; j < h; j++) {\n            int x;\n            cin >> x;\n            init_stacks[i].push_back(x);\n        }\n    }\n    \n    vector<pair<int, int>> best_ops;\n    int best_energy = INT_MAX;\n    \n    auto start_time = chrono::steady_clock::now();\n    \n    vector<int> noise_levels = {0, 2, 5, 8, 12, 16, 20, 25, 30, 38, 48, 60, 75, 95};\n    int num_policies = 18;\n    \n    for (int seed = 0; ; seed++) {\n        auto current_time = chrono::steady_clock::now();\n        auto elapsed = chrono::duration_cast<chrono::milliseconds>(current_time - start_time).count();\n        if (elapsed > 1900) break;\n        \n        int noise_level = noise_levels[seed % noise_levels.size()];\n        int policy = (seed / noise_levels.size()) % num_policies;\n        bool random_mode = (seed % 18 == 17);\n        \n        mt19937 rng(seed);\n        vector<pair<int, int>> ops;\n        int energy = simulate(init_stacks, n, m, ops, rng, noise_level, policy, random_mode);\n        \n        if (energy < best_energy) {\n            best_energy = energy;\n            best_ops = ops;\n        }\n    }\n    \n    for (auto& [a, b] : best_ops) {\n        cout << a << \" \" << b << \"\\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;\nlong long totalD;\nmt19937 rng(42);\n\nint di[] = {0, 1, 0, -1};\nint dj[] = {1, 0, -1, 0};\nchar dirChar[] = {'R', 'D', 'L', 'U'};\n\nbool canMove(int i, int j, int dir) {\n    int ni = i + di[dir], nj = j + dj[dir];\n    if (ni < 0 || ni >= N || nj < 0 || nj >= N) return false;\n    if (dir == 0) return v[i][j] == '0';\n    if (dir == 1) return h[i][j] == '0';\n    if (dir == 2) return j > 0 && v[i][j-1] == '0';\n    return i > 0 && h[i-1][j] == '0';\n}\n\nlong double fastEvaluate(const string& path) {\n    int L = path.size();\n    vector<vector<long long>> contrib(N, vector<long long>(N, 0));\n    long long contribSum = 0;\n    int ci = 0, cj = 0;\n    \n    auto move = [&](int t, char c) {\n        int dir = (c == 'R') ? 0 : (c == 'D') ? 1 : (c == 'L') ? 2 : 3;\n        ci += di[dir]; cj += dj[dir];\n        contribSum -= contrib[ci][cj];\n        contrib[ci][cj] = (long long)d[ci][cj] * t;\n        contribSum += contrib[ci][cj];\n    };\n    \n    for (int t = 1; t <= L; t++) move(t, path[t-1]);\n    \n    long double totalSum = 0;\n    for (int t = L + 1; t <= 2 * L; t++) {\n        totalSum += (long long)totalD * t - contribSum;\n        move(t, path[(t-1) % L]);\n    }\n    return totalSum / L;\n}\n\nvector<vector<int>> getVisits(const string& path) {\n    vector<vector<int>> cnt(N, vector<int>(N, 0));\n    int ci = 0, cj = 0;\n    cnt[0][0] = 1;\n    for (char c : path) {\n        int dir = (c == 'R') ? 0 : (c == 'D') ? 1 : (c == 'L') ? 2 : 3;\n        ci += di[dir]; cj += dj[dir];\n        cnt[ci][cj]++;\n    }\n    return cnt;\n}\n\nstring generatePath(int mode) {\n    vector<vector<bool>> visited(N, vector<bool>(N, false));\n    string path;\n    \n    function<void(int, int)> dfs = [&](int i, int j) {\n        visited[i][j] = true;\n        vector<pair<int, int>> children;\n        for (int dir = 0; dir < 4; dir++) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && !visited[ni][nj] && canMove(i, j, dir)) {\n                children.push_back({d[ni][nj], dir});\n            }\n        }\n        if (mode == 0) sort(children.begin(), children.end());\n        else if (mode == 1) sort(children.rbegin(), children.rend());\n        else shuffle(children.begin(), children.end(), rng);\n        \n        for (auto& [dval, dir] : children) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (!visited[ni][nj]) {\n                path += dirChar[dir];\n                dfs(ni, nj);\n                path += dirChar[(dir + 2) % 4];\n            }\n        }\n    };\n    dfs(0, 0);\n    return path;\n}\n\nvector<tuple<int,int,int,string>> allLoops;\n\nvoid precomputeLoops() {\n    vector<vector<int>> par(N, vector<int>(N, -1));\n    queue<pair<int,int>> bfs;\n    bfs.push({0, 0});\n    par[0][0] = -2;\n    \n    while (!bfs.empty()) {\n        auto [i, j] = bfs.front(); bfs.pop();\n        for (int dir = 0; dir < 4; dir++) {\n            int ni = i + di[dir], nj = j + dj[dir];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && par[ni][nj] == -1 && canMove(i, j, dir)) {\n                par[ni][nj] = (dir + 2) % 4;\n                bfs.push({ni, nj});\n            }\n        }\n    }\n    \n    for (int ti = 0; ti < N; ti++) {\n        for (int tj = 0; tj < N; tj++) {\n            if (ti == 0 && tj == 0) continue;\n            string toTarget, fromTarget;\n            int ci = ti, cj = tj;\n            while (ci != 0 || cj != 0) {\n                int pdir = par[ci][cj];\n                fromTarget += dirChar[pdir];\n                toTarget += dirChar[(pdir + 2) % 4];\n                ci += di[pdir]; cj += dj[pdir];\n            }\n            reverse(toTarget.begin(), toTarget.end());\n            allLoops.push_back({d[ti][tj], ti, tj, toTarget + fromTarget});\n        }\n    }\n    sort(allLoops.rbegin(), allLoops.rend());\n}\n\nstring bestPath;\nlong double bestScore = 1e18;\n\nlong double tryPath(const string& path) {\n    if (path.size() > 100000) return 1e18;\n    long double score = fastEvaluate(path);\n    if (score < bestScore) { bestScore = score; bestPath = path; }\n    return score;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> 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    totalD = 0;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            cin >> d[i][j];\n            totalD += d[i][j];\n        }\n    \n    precomputeLoops();\n    \n    vector<pair<long double, string>> topPaths;\n    \n    for (int mode = 0; mode < 2; mode++) {\n        string p = generatePath(mode);\n        topPaths.push_back({tryPath(p), p});\n    }\n    \n    auto startTime = chrono::steady_clock::now();\n    while (chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - startTime).count() < 1300) {\n        string p = generatePath(2);\n        topPaths.push_back({tryPath(p), p});\n    }\n    \n    sort(topPaths.begin(), topPaths.end());\n    if (topPaths.size() > 8) topPaths.resize(8);\n    \n    auto addLoopsD = [&](string bp) {\n        string cur = bp;\n        long double cs = fastEvaluate(cur);\n        for (int it = 0; it < 30; it++) {\n            bool imp = false;\n            for (auto& [dv, ti, tj, lp] : allLoops) {\n                if (cur.size() + lp.size() > 100000) continue;\n                long double sc = fastEvaluate(cur + lp);\n                if (sc < cs) {\n                    cs = sc; cur += lp; imp = true;\n                    if (sc < bestScore) { bestScore = sc; bestPath = cur; }\n                    break;\n                }\n            }\n            if (!imp) break;\n        }\n    };\n    \n    auto addLoopsV = [&](string bp) {\n        string cur = bp;\n        long double cs = fastEvaluate(cur);\n        for (int it = 0; it < 30; it++) {\n            bool imp = false;\n            auto vis = getVisits(cur);\n            vector<pair<double, int>> pri;\n            for (int i = 0; i < (int)allLoops.size(); i++) {\n                auto& [dv, ti, tj, lp] = allLoops[i];\n                pri.push_back({(double)dv / max(1, vis[ti][tj]), i});\n            }\n            sort(pri.rbegin(), pri.rend());\n            for (auto& [p, idx] : pri) {\n                auto& [dv, ti, tj, lp] = allLoops[idx];\n                if (cur.size() + lp.size() > 100000) continue;\n                long double sc = fastEvaluate(cur + lp);\n                if (sc < cs) {\n                    cs = sc; cur += lp; imp = true;\n                    if (sc < bestScore) { bestScore = sc; bestPath = cur; }\n                    break;\n                }\n            }\n            if (!imp) break;\n        }\n    };\n    \n    for (auto& [bs, bp] : topPaths) {\n        addLoopsD(bp);\n        addLoopsV(bp);\n    }\n    \n    for (int c = 0; c < min(12, (int)allLoops.size()); c++) {\n        auto& [dv, ti, tj, lp] = allLoops[c];\n        string cand = bestPath;\n        long double last = bestScore;\n        for (int r = 1; r <= 40 && cand.size() + lp.size() <= 100000; r++) {\n            cand += lp;\n            long double sc = tryPath(cand);\n            if (sc > last) break;\n            last = sc;\n        }\n    }\n    \n    cout << bestPath << endl;\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, si, sj;\nmap<char, vector<pair<int,int>>> charPos;\n\nint calcOverlap(const string& a, const string& b) {\n    int maxOv = min(a.length(), b.length());\n    for (int ov = maxOv; ov >= 1; ov--) {\n        bool match = true;\n        size_t aStart = a.length() - ov;\n        for (int k = 0; k < ov && match; k++)\n            if (a[aStart + k] != b[k]) match = false;\n        if (match) return ov;\n    }\n    return 0;\n}\n\nstring buildSuperstring(const vector<string>& strings) {\n    int n = strings.size();\n    vector<vector<int>> preOv(n, vector<int>(n, 0));\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < n; j++)\n            if (i != j) preOv[i][j] = calcOverlap(strings[i], strings[j]);\n    \n    vector<int> startWith(n), endWith(n);\n    for (int i = 0; i < n; i++) startWith[i] = endWith[i] = i;\n    \n    vector<bool> active(n, true);\n    vector<string> current = strings;\n    \n    for (int iter = 0; iter < n - 1; iter++) {\n        int bestOv = -1, bestI = -1, bestJ = -1;\n        for (int i = 0; i < n; i++) {\n            if (!active[i]) continue;\n            for (int j = 0; j < n; j++) {\n                if (!active[j] || i == j) continue;\n                int ov = preOv[endWith[i]][startWith[j]];\n                if (ov > bestOv) { bestOv = ov; bestI = i; bestJ = j; }\n            }\n        }\n        current[bestI] += current[bestJ].substr(bestOv);\n        endWith[bestI] = endWith[bestJ];\n        active[bestJ] = false;\n    }\n    for (int i = 0; i < n; i++) if (active[i]) return current[i];\n    return \"\";\n}\n\npair<int, vector<pair<int,int>>> computePath(const string& ss) {\n    int n = ss.length();\n    if (n == 0) return {0, {}};\n    vector<vector<int>> dp(n);\n    for (int pos = n - 1; pos >= 0; pos--) {\n        const auto& positions = charPos[ss[pos]];\n        dp[pos].assign(positions.size(), 0);\n        if (pos < n - 1) {\n            const auto& nextPos = charPos[ss[pos + 1]];\n            for (size_t idx = 0; idx < positions.size(); idx++) {\n                int r = positions[idx].first, c = positions[idx].second, best = INT_MAX;\n                for (size_t ni = 0; ni < nextPos.size(); ni++)\n                    best = min(best, abs(nextPos[ni].first-r)+abs(nextPos[ni].second-c)+1+dp[pos+1][ni]);\n                dp[pos][idx] = best;\n            }\n        }\n    }\n    const auto& pos0 = charPos[ss[0]];\n    int bestCost = INT_MAX;\n    for (size_t idx = 0; idx < pos0.size(); idx++)\n        bestCost = min(bestCost, abs(pos0[idx].first-si)+abs(pos0[idx].second-sj)+1+dp[0][idx]);\n    vector<pair<int,int>> path(n);\n    int curI = si, curJ = sj;\n    for (int pos = 0; pos < n; pos++) {\n        const auto& positions = charPos[ss[pos]];\n        int best = INT_MAX, bIdx = 0;\n        for (size_t idx = 0; idx < positions.size(); idx++) {\n            int total = abs(positions[idx].first-curI)+abs(positions[idx].second-curJ)+1+dp[pos][idx];\n            if (total < best) { best = total; bIdx = idx; }\n        }\n        path[pos] = positions[bIdx];\n        curI = path[pos].first; curJ = path[pos].second;\n    }\n    return {bestCost, path};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> N >> M >> si >> sj;\n    for (int i = 0; i < N; i++) {\n        string row; cin >> row;\n        for (int j = 0; j < N; j++) charPos[row[j]].push_back({i, j});\n    }\n    vector<string> t(M);\n    for (int i = 0; i < M; i++) cin >> t[i];\n    \n    mt19937 rng(12345);\n    vector<pair<int,int>> bestPath;\n    int bestCost = INT_MAX;\n    auto startTime = chrono::steady_clock::now();\n    \n    for (int iter = 0; ; iter++) {\n        if (iter > 0 && chrono::duration_cast<chrono::milliseconds>(\n            chrono::steady_clock::now() - startTime).count() > 1850) break;\n        \n        vector<string> input = t;\n        if (iter == 1) sort(input.begin(), input.end());\n        else if (iter == 2) sort(input.begin(), input.end(), greater<string>());\n        else if (iter == 3) sort(input.begin(), input.end(), [](auto& a, auto& b){ return a.back() < b.back(); });\n        else if (iter == 4) sort(input.begin(), input.end(), [](auto& a, auto& b){ return a[0] < b[0]; });\n        else if (iter > 4) shuffle(input.begin(), input.end(), rng);\n        \n        string ss = buildSuperstring(input);\n        auto [cost, path] = computePath(ss);\n        if (cost < bestCost) { bestCost = cost; bestPath = path; }\n    }\n    \n    for (auto& [i, j] : bestPath) cout << i << \" \" << j << \"\\n\";\n    return 0;\n}","ahc030":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\ndouble eps;\nvector<vector<pair<int,int>>> shapes;\nmap<pair<int,int>, int> drilled;\nset<pair<int,int>> confirmed_oil, confirmed_no_oil;\nint qcount = 0;\nint maxQ;\n\nint queryDrill(int i, int j) {\n    pair<int,int> key = make_pair(i, j);\n    if (drilled.count(key)) return drilled[key];\n    cout << \"q 1 \" << i << \" \" << j << \"\\n\" << flush;\n    qcount++;\n    int v; cin >> v;\n    drilled[key] = v;\n    if (v > 0) confirmed_oil.insert(key);\n    else confirmed_no_oil.insert(key);\n    return v;\n}\n\nint queryDivine(const vector<pair<int,int>>& cells) {\n    cout << \"q \" << cells.size();\n    for (auto& c : cells) cout << \" \" << c.first << \" \" << c.second;\n    cout << \"\\n\" << flush;\n    qcount++;\n    int v; cin >> v;\n    return v;\n}\n\nint submit(set<pair<int,int>> oil) {\n    for (auto& c : confirmed_oil) oil.insert(c);\n    cout << \"a \" << oil.size();\n    for (auto& c : oil) cout << \" \" << c.first << \" \" << c.second;\n    cout << \"\\n\" << flush;\n    qcount++;\n    int r; cin >> r;\n    return r;\n}\n\nvector<vector<set<pair<int,int>>>> placements;\n\nvoid filterPlacements() {\n    for (int m = 0; m < M; m++) {\n        vector<set<pair<int,int>>> valid;\n        for (auto& p : placements[m]) {\n            bool ok = true;\n            for (auto& c : confirmed_no_oil)\n                if (p.count(c)) { ok = false; break; }\n            if (ok) valid.push_back(p);\n        }\n        if (!valid.empty()) placements[m] = valid;\n    }\n}\n\nbool allUnique() {\n    for (int m = 0; m < M; m++)\n        if (placements[m].size() > 1) return false;\n    return true;\n}\n\nset<pair<int,int>> getAnswer() {\n    set<pair<int,int>> answer;\n    for (int m = 0; m < M; m++)\n        if (!placements[m].empty())\n            for (auto& c : placements[m][0]) answer.insert(c);\n    return answer;\n}\n\nset<pair<int,int>> getPossible() {\n    set<pair<int,int>> possible;\n    for (int m = 0; m < M; m++)\n        for (auto& p : placements[m])\n            for (auto& c : p) possible.insert(c);\n    return possible;\n}\n\npair<int,int> getBestCell(const vector<vector<double>>& prob) {\n    map<pair<int,int>, vector<int>> cellCounts;\n    \n    for (int m = 0; m < M; m++) {\n        for (auto& p : placements[m])\n            for (auto& c : p) {\n                if (cellCounts.find(c) == cellCounts.end())\n                    cellCounts[c] = vector<int>(M, 0);\n                cellCounts[c][m]++;\n            }\n    }\n    \n    // Find field with most remaining placements\n    int maxField = 0;\n    for (int m = 1; m < M; m++)\n        if (placements[m].size() > placements[maxField].size())\n            maxField = m;\n    \n    pair<int,int> best = {-1, -1};\n    double bestScore = -1e18;\n    \n    for (auto& kv : cellCounts) {\n        pair<int,int> cell = kv.first;\n        vector<int>& counts = kv.second;\n        \n        if (drilled.count(cell)) continue;\n        \n        bool valid = true;\n        for (int m = 0; m < M; m++) {\n            if ((int)placements[m].size() - counts[m] <= 0) {\n                valid = false; break;\n            }\n        }\n        if (!valid) continue;\n        \n        double p = prob[cell.first][cell.second];\n        \n        // Entropy-based scoring with log reduction\n        double entropyGain = 0;\n        double logReduction = 0;\n        for (int m = 0; m < M; m++) {\n            int sz = placements[m].size();\n            if (sz <= 1) continue;\n            double ratio = (double)counts[m] / sz;\n            entropyGain += ratio * (1 - ratio) * 4 * log((double)sz);\n            logReduction += log((double)sz) - log((double)(sz - counts[m]));\n        }\n        \n        // Bonus for splitting the most uncertain field evenly\n        double splitBonus = 0;\n        if (placements[maxField].size() > 1) {\n            int cnt = counts[maxField];\n            int sz = placements[maxField].size();\n            double ratio = (double)cnt / sz;\n            splitBonus = ratio * (1 - ratio) * 4;\n        }\n        \n        double score = (1.0 - p) * (entropyGain + logReduction * 0.5 + splitBonus * 2.0);\n        \n        if (score > bestScore) {\n            bestScore = score;\n            best = cell;\n        }\n    }\n    return best;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> eps;\n    maxQ = 2 * N * N;\n    shapes.resize(M);\n    \n    for (int m = 0; m < M; m++) {\n        int d; cin >> d;\n        shapes[m].resize(d);\n        for (int i = 0; i < d; i++)\n            cin >> shapes[m][i].first >> shapes[m][i].second;\n    }\n    \n    placements.resize(M);\n    for (int m = 0; m < M; m++) {\n        int maxI = 0, maxJ = 0;\n        for (auto& c : shapes[m]) {\n            maxI = max(maxI, c.first);\n            maxJ = max(maxJ, c.second);\n        }\n        for (int di = 0; di + maxI < N; di++)\n            for (int dj = 0; dj + maxJ < N; dj++) {\n                set<pair<int,int>> cells;\n                for (auto& c : shapes[m])\n                    cells.insert({di + c.first, dj + c.second});\n                placements[m].push_back(cells);\n            }\n    }\n    \n    // Compute structural probability\n    vector<vector<double>> structProb(N, vector<double>(N, 0.1));\n    map<pair<int,int>, int> freq;\n    int totalPlacements = 0;\n    for (int m = 0; m < M; m++) {\n        for (auto& p : placements[m]) {\n            totalPlacements++;\n            for (auto& c : p) freq[c]++;\n        }\n    }\n    for (auto& kv : freq)\n        structProb[kv.first.first][kv.first.second] = min(0.8, (double)kv.second / max(1, totalPlacements));\n    \n    vector<vector<double>> prob(N, vector<double>(N, 0.3));\n    \n    // Always do row divination\n    for (int i = 0; i < N; i++) {\n        vector<pair<int,int>> row;\n        for (int j = 0; j < N; j++) row.push_back({i, j});\n        int est = queryDivine(row);\n        double denom = max(0.6, 1.0 - 2.0 * eps);\n        double trueEst = max(0.0, (est - N * eps) / denom);\n        double divProb = min(0.9, max(0.1, trueEst / N));\n        \n        for (int j = 0; j < N; j++) {\n            if (eps <= 0.08) {\n                prob[i][j] = divProb;\n            } else {\n                double w = max(0.3, 1.0 - eps * 3);  // More structural weight as eps increases\n                prob[i][j] = w * divProb + (1-w) * structProb[i][j];\n            }\n        }\n    }\n    \n    // Column divination for low eps\n    if (eps <= 0.05) {\n        for (int j = 0; j < N; j++) {\n            vector<pair<int,int>> col;\n            for (int i = 0; i < N; i++) col.push_back({i, j});\n            int est = queryDivine(col);\n            double denom = max(0.01, 1.0 - 2.0 * eps);\n            double trueEst = max(0.0, (est - N * eps) / denom);\n            for (int i = 0; i < N; i++)\n                prob[i][j] = (prob[i][j] + min(0.9, max(0.1, trueEst / N))) / 2.0;\n        }\n    }\n    \n    while (qcount < maxQ - 5 && !allUnique()) {\n        filterPlacements();\n        auto cell = getBestCell(prob);\n        if (cell.first < 0) break;\n        queryDrill(cell.first, cell.second);\n    }\n    \n    filterPlacements();\n    set<pair<int,int>> answer = allUnique() ? getAnswer() : getPossible();\n    for (auto& c : confirmed_no_oil) answer.erase(c);\n    \n    if (!submit(answer)) {\n        while (qcount < maxQ - 2) {\n            filterPlacements();\n            if (allUnique()) break;\n            auto cell = getBestCell(prob);\n            if (cell.first < 0) {\n                auto possible = getPossible();\n                for (auto& c : possible)\n                    if (!drilled.count(c)) { cell = c; break; }\n            }\n            if (cell.first < 0) break;\n            queryDrill(cell.first, cell.second);\n        }\n        filterPlacements();\n        answer = allUnique() ? getAnswer() : getPossible();\n        for (auto& c : confirmed_no_oil) answer.erase(c);\n        if (!submit(answer)) submit(confirmed_oil);\n    }\n    \n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int W, D, N;\n    cin >> W >> D >> N;\n    \n    vector<vector<int>> a(D, vector<int>(N));\n    for (int d = 0; d < D; d++) {\n        for (int k = 0; k < N; k++) {\n            cin >> a[d][k];\n        }\n    }\n    \n    vector<int> prevH(N, 0);\n    \n    for (int d = 0; d < D; d++) {\n        vector<int> h(N);\n        int totalH = 0;\n        \n        for (int k = 0; k < N; k++) {\n            h[k] = (a[d][k] + W - 1) / W;\n            if (h[k] == 0) h[k] = 1;\n            totalH += h[k];\n        }\n        \n        if (totalH > W) {\n            while (totalH > W) {\n                int bestK = -1;\n                int maxSlack = INT_MIN;\n                for (int k = 0; k < N; k++) {\n                    if (h[k] > 1) {\n                        int slack = h[k] * W - a[d][k];\n                        if (slack > maxSlack) {\n                            maxSlack = slack;\n                            bestK = k;\n                        }\n                    }\n                }\n                if (bestK == -1) break;\n                h[bestK]--;\n                totalH--;\n            }\n        } else if (totalH < W) {\n            // Distribute extra space matching previous day where possible\n            int extra = W - totalH;\n            for (int k = 0; k < N && extra > 0; k++) {\n                if (prevH[k] > h[k]) {\n                    int add = min(extra, prevH[k] - h[k]);\n                    h[k] += add;\n                    extra -= add;\n                }\n            }\n            // Remaining extra goes to largest\n            if (extra > 0) {\n                h[N-1] += extra;\n            }\n        }\n        \n        int y = 0;\n        for (int k = 0; k < N; k++) {\n            cout << y << \" 0 \" << y + h[k] << \" \" << W << \"\\n\";\n            y += h[k];\n        }\n        \n        prevH = h;\n    }\n    \n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long P = 998244353;\nint N, M, K;\nvector<vector<long long>> a_init;\nvector<array<array<long long, 3>, 3>> stamps;\n\nvoid applyOp(vector<vector<long long>>& a, int m, int p, int q) {\n    for (int i = 0; i < 3; i++)\n        for (int j = 0; j < 3; j++)\n            a[p+i][q+j] = (a[p+i][q+j] + stamps[m][i][j]) % P;\n}\n\nlong long calcGain(const vector<vector<long long>>& a, int m, int p, int q) {\n    long long gain = 0;\n    for (int i = 0; i < 3; i++)\n        for (int j = 0; j < 3; j++)\n            gain += (a[p+i][q+j] + stamps[m][i][j]) % P - a[p+i][q+j];\n    return gain;\n}\n\nlong long calcScore(const vector<vector<long long>>& a) {\n    long long s = 0;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            s += a[i][j];\n    return s;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    cin >> N >> M >> K;\n    a_init.assign(N, vector<long long>(N));\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            cin >> a_init[i][j];\n            a_init[i][j] %= P;\n        }\n    \n    stamps.resize(M);\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    auto start = chrono::steady_clock::now();\n    auto elapsed = [&]() { return chrono::duration<double>(chrono::steady_clock::now() - start).count(); };\n    \n    vector<tuple<int,int,int>> best_ops;\n    long long best_score = calcScore(a_init);\n    \n    mt19937 rng(42);\n    \n    for (int trial = 0; elapsed() < 1.9; trial++) {\n        vector<tuple<int,int,int>> ops;\n        auto a = a_init;\n        \n        // Randomized greedy\n        for (int op = 0; op < K; op++) {\n            vector<tuple<long long, int, int, int>> cands;\n            for (int m = 0; m < M; m++)\n                for (int p = 0; p <= N-3; p++)\n                    for (int q = 0; q <= N-3; q++) {\n                        long long gain = calcGain(a, m, p, q);\n                        if (gain > 0) cands.push_back({gain, m, p, q});\n                    }\n            if (cands.empty()) break;\n            sort(cands.rbegin(), cands.rend());\n            int pick = (trial == 0) ? 0 : rng() % min((int)cands.size(), 2 + trial / 3);\n            auto [g, m, p, q] = cands[pick];\n            applyOp(a, m, p, q);\n            ops.push_back({m, p, q});\n        }\n        \n        long long score = calcScore(a);\n        \n        // Local optimization passes\n        for (int iter = 0; iter < 5 && elapsed() < 1.9; iter++) {\n            bool improved = false;\n            \n            // Try replacing each operation\n            for (int idx = 0; idx < (int)ops.size() && elapsed() < 1.9; idx++) {\n                auto orig = ops[idx];\n                auto a2 = a_init;\n                for (int k = 0; k < (int)ops.size(); k++)\n                    if (k != idx) {\n                        auto [m,p,q] = ops[k];\n                        applyOp(a2, m, p, q);\n                    }\n                \n                long long bestGain = 0;\n                int bm=-1, bp=-1, bq=-1;\n                for (int m = 0; m < M; m++)\n                    for (int p = 0; p <= N-3; p++)\n                        for (int q = 0; q <= N-3; q++) {\n                            long long gain = calcGain(a2, m, p, q);\n                            if (gain > bestGain) { bestGain = gain; bm=m; bp=p; bq=q; }\n                        }\n                \n                if (bm != -1) {\n                    auto newOp = make_tuple(bm, bp, bq);\n                    if (newOp != orig) {\n                        ops[idx] = newOp;\n                        a = a2;\n                        applyOp(a, bm, bp, bq);\n                        long long newScore = calcScore(a);\n                        if (newScore > score) {\n                            score = newScore;\n                            improved = true;\n                        }\n                    }\n                }\n            }\n            \n            // Try removing operations\n            for (int idx = (int)ops.size()-1; idx >= 0 && elapsed() < 1.9; idx--) {\n                auto a2 = a_init;\n                for (int k = 0; k < (int)ops.size(); k++)\n                    if (k != idx) {\n                        auto [m,p,q] = ops[k];\n                        applyOp(a2, m, p, q);\n                    }\n                long long newScore = calcScore(a2);\n                if (newScore >= score) {\n                    ops.erase(ops.begin() + idx);\n                    a = a2;\n                    score = newScore;\n                    improved = true;\n                }\n            }\n            \n            // Try adding more operations\n            while (ops.size() < (size_t)K && elapsed() < 1.9) {\n                long long bestGain = 0;\n                int bm=-1, bp=-1, bq=-1;\n                for (int m = 0; m < M; m++)\n                    for (int p = 0; p <= N-3; p++)\n                        for (int q = 0; q <= N-3; q++) {\n                            long long gain = calcGain(a, m, p, q);\n                            if (gain > bestGain) { bestGain = gain; bm=m; bp=p; bq=q; }\n                        }\n                if (bm == -1) break;\n                applyOp(a, bm, bp, bq);\n                ops.push_back({bm, bp, bq});\n                score += bestGain;\n                improved = true;\n            }\n            \n            if (!improved) break;\n        }\n        \n        if (score > best_score) {\n            best_score = score;\n            best_ops = ops;\n        }\n    }\n    \n    cout << best_ops.size() << \"\\n\";\n    for (auto& [m,p,q] : best_ops) cout << m << \" \" << p << \" \" << q << \"\\n\";\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 5;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int n; cin >> n;\n    int A[N][N];\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++)\n            cin >> A[i][j];\n    \n    string ans[N];\n    int grid[N][N]; memset(grid, -1, sizeof(grid));\n    int cr = 0, cc = 0, hold = -1;\n    int next_in[N] = {0};\n    set<int> dispatched;\n    \n    for (int t = 0; t < 9000; t++) {\n        for (int i = 0; i < N; i++) {\n            if (next_in[i] < N && grid[i][0] == -1) {\n                bool blocked = (cr == i && cc == 0 && hold != -1);\n                if (!blocked) grid[i][0] = A[i][next_in[i]++];\n            }\n        }\n        \n        char moves[N];\n        for (int c = 0; c < N; c++) moves[c] = '.';\n        \n        if (t == 0) {\n            for (int c = 1; c < N; c++) moves[c] = 'B';\n        }\n        \n        int min_undispatched[N];\n        for (int i = 0; i < N; i++) {\n            min_undispatched[i] = i * N;\n            while (min_undispatched[i] < (i+1)*N && dispatched.count(min_undispatched[i]))\n                min_undispatched[i]++;\n        }\n        \n        int min_on_grid[N];\n        for (int i = 0; i < N; i++) min_on_grid[i] = N * N;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                if (grid[i][j] != -1) {\n                    int cont = grid[i][j];\n                    min_on_grid[cont / N] = min(min_on_grid[cont / N], cont);\n                }\n            }\n        }\n        \n        if (hold == -1) {\n            int best_r = -1, best_c = -1, best_score = -1000000;\n            \n            for (int i = 0; i < N; i++) {\n                for (int j = 0; j < N; j++) {\n                    if (grid[i][j] != -1) {\n                        int cont = grid[i][j];\n                        int target = cont / N;\n                        int dist = abs(i - cr) + abs(j - cc);\n                        int deliver_dist = abs(i - target) + (N - 1 - j);\n                        \n                        int score = -dist * 5 - deliver_dist;\n                        \n                        if (cont == min_undispatched[target]) {\n                            score += 10000; // Must pick these\n                        } else {\n                            // Penalize by potential inversions\n                            int inversions = cont - min_undispatched[target];\n                            score -= inversions * 80;\n                            \n                            if (cont == min_on_grid[target]) {\n                                score += 200; // Small bonus for min on grid\n                            }\n                        }\n                        \n                        if (score > best_score) {\n                            best_score = score;\n                            best_r = i; best_c = j;\n                        }\n                    }\n                }\n            }\n            \n            if (best_r != -1) {\n                if (best_r == cr && best_c == cc) {\n                    moves[0] = 'P';\n                } else if (best_r > cr) moves[0] = 'D';\n                else if (best_r < cr) moves[0] = 'U';\n                else if (best_c > cc) moves[0] = 'R';\n                else moves[0] = 'L';\n            } else if (cc > 0) {\n                moves[0] = 'L';\n            }\n        } else {\n            int target = hold / N;\n            if (cr != target) {\n                if (target > cr) moves[0] = 'D';\n                else moves[0] = 'U';\n            } else if (cc < N-1) {\n                moves[0] = 'R';\n            } else {\n                moves[0] = 'Q';\n            }\n        }\n        \n        if (moves[0] == 'P') { hold = grid[cr][cc]; grid[cr][cc] = -1; }\n        else if (moves[0] == 'Q') { \n            if (cc == N-1) dispatched.insert(hold);\n            grid[cr][cc] = hold; \n            hold = -1; \n        }\n        else if (moves[0] == 'R') cc++;\n        else if (moves[0] == 'L') cc--;\n        else if (moves[0] == 'U') cr--;\n        else if (moves[0] == 'D') cr++;\n        \n        for (int i = 0; i < N; i++) grid[i][N-1] = -1;\n        for (int c = 0; c < N; c++) ans[c] += moves[c];\n        \n        bool done = true;\n        for (int i = 0; i < N; i++) if (next_in[i] < N) done = false;\n        if (hold != -1) done = false;\n        for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (grid[i][j] != -1) done = false;\n        if (done) break;\n    }\n    \n    for (int i = 0; i < N; i++) cout << ans[i] << \"\\n\";\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nmt19937 rng;\n\nstruct State {\n    vector<vector<int>> h;\n    vector<string> ops;\n    int cx, cy, load;\n    long long cost;\n    \n    State(const vector<vector<int>>& grid) : h(grid), cx(0), cy(0), load(0), cost(0) {}\n    \n    void do_load(int d) {\n        if (d <= 0) return;\n        ops.push_back(\"+\" + to_string(d));\n        load += d; h[cx][cy] -= d; cost += d;\n    }\n    \n    void do_unload(int d) {\n        if (d <= 0) return;\n        ops.push_back(\"-\" + to_string(d));\n        load -= d; h[cx][cy] += d; cost += d;\n    }\n    \n    void move_one(char dir) {\n        cost += 100 + load;\n        ops.push_back(string(1, dir));\n        if (dir == 'U') cx--; else if (dir == 'D') cx++;\n        else if (dir == 'L') cy--; else if (dir == 'R') cy++;\n    }\n    \n    void process_cell() {\n        if (h[cx][cy] > 0) do_load(h[cx][cy]);\n        if (h[cx][cy] < 0 && load > 0) do_unload(min(load, -h[cx][cy]));\n    }\n    \n    int calc_path_work(int fx, int fy, int tx, int ty, int init_load, bool vert_first) {\n        int work = 0, sim_load = init_load, x = fx, y = fy;\n        auto process = [&](int px, int py) {\n            if (h[px][py] > 0) { work += h[px][py]; sim_load += h[px][py]; }\n            else if (h[px][py] < 0 && sim_load > 0) {\n                int u = min(sim_load, -h[px][py]); work += u; sim_load -= u;\n            }\n        };\n        if (vert_first) {\n            while (x != tx) { x += (tx > x) ? 1 : -1; process(x, y); }\n            while (y != ty) { y += (ty > y) ? 1 : -1; process(x, y); }\n        } else {\n            while (y != ty) { y += (ty > y) ? 1 : -1; process(x, y); }\n            while (x != tx) { x += (tx > x) ? 1 : -1; process(x, y); }\n        }\n        return work;\n    }\n    \n    int best_path_work(int fx, int fy, int tx, int ty, int init_load) {\n        return max(calc_path_work(fx, fy, tx, ty, init_load, true),\n                   calc_path_work(fx, fy, tx, ty, init_load, false));\n    }\n    \n    void move_to(int tx, int ty) {\n        int vw = calc_path_work(cx, cy, tx, ty, load, true);\n        int hw = calc_path_work(cx, cy, tx, ty, load, false);\n        if (vw >= hw) {\n            while (cx < tx) { move_one('D'); process_cell(); }\n            while (cx > tx) { move_one('U'); process_cell(); }\n            while (cy < ty) { move_one('R'); process_cell(); }\n            while (cy > ty) { move_one('L'); process_cell(); }\n        } else {\n            while (cy < ty) { move_one('R'); process_cell(); }\n            while (cy > ty) { move_one('L'); process_cell(); }\n            while (cx < tx) { move_one('D'); process_cell(); }\n            while (cx > tx) { move_one('U'); process_cell(); }\n        }\n    }\n    \n    void solve(int pw, int ta, int dp, int rand_level = 0) {\n        while (true) {\n            if (load == 0) {\n                vector<tuple<int,int,int>> cands;\n                for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (h[i][j] > 0) {\n                    int d = abs(i-cx) + abs(j-cy);\n                    int score = best_path_work(cx,cy,i,j,0)*pw + h[i][j]*ta - d*dp;\n                    cands.push_back({score, i, j});\n                }\n                if (cands.empty()) break;\n                sort(cands.rbegin(), cands.rend());\n                int idx = 0;\n                if (rand_level > 0 && cands.size() > 1) idx = rng() % min((int)cands.size(), rand_level + 1);\n                auto [sc, si, sj] = cands[idx];\n                move_to(si, sj);\n                if (h[cx][cy] > 0) do_load(h[cx][cy]);\n            } else {\n                vector<tuple<int,int,int>> cands;\n                for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (h[i][j] < 0) {\n                    int d = abs(i-cx) + abs(j-cy);\n                    int score = best_path_work(cx,cy,i,j,load)*pw + min(-h[i][j],load)*ta - d*dp;\n                    cands.push_back({score, i, j});\n                }\n                if (cands.empty()) break;\n                sort(cands.rbegin(), cands.rend());\n                int idx = 0;\n                if (rand_level > 0 && cands.size() > 1) idx = rng() % min((int)cands.size(), rand_level + 1);\n                auto [sc, ti, tj] = cands[idx];\n                move_to(ti, tj);\n                if (h[cx][cy] < 0 && load > 0) do_unload(min(load, -h[cx][cy]));\n            }\n        }\n    }\n};\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N;\n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) cin >> h[i][j];\n    \n    State best(h);\n    best.cost = LLONG_MAX;\n    \n    // Expanded deterministic parameter grid\n    for (int pw = 1; pw <= 7; pw++)\n        for (int ta = 0; ta <= 4; ta++)\n            for (int dp = 2; dp <= 9; dp++) {\n                State s(h); s.solve(pw, ta, dp);\n                if (s.cost < best.cost) best = s;\n            }\n    \n    // Diverse base parameters for randomization\n    vector<tuple<int,int,int>> base_params = {\n        {3,1,5},{4,1,5},{2,1,5},{3,2,5},{4,2,5},{2,1,4},{5,1,6},\n        {3,1,4},{4,1,4},{2,2,5},{3,0,5},{4,0,5},{1,1,4},{6,1,7},\n        {3,1,6},{4,2,6},{5,2,5},{2,0,4},{3,3,5},{4,1,3}\n    };\n    \n    for (int seed = 0; seed < 25; seed++) {\n        rng.seed(seed);\n        for (auto [pw, ta, dp] : base_params)\n            for (int rl = 1; rl <= 5; rl++) {\n                State s(h); s.solve(pw, ta, dp, rl);\n                if (s.cost < best.cost) best = s;\n            }\n    }\n    \n    // Random parameter exploration\n    for (int seed = 100; seed < 200; seed++) {\n        rng.seed(seed);\n        int pw = 1 + rng() % 7;\n        int ta = rng() % 5;\n        int dp = 2 + rng() % 8;\n        int rl = 1 + rng() % 5;\n        State s(h); s.solve(pw, ta, dp, rl);\n        if (s.cost < best.cost) best = s;\n    }\n    \n    for (auto& op : best.ops) cout << op << \"\\n\";\n    return 0;\n}","ahc035":"#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \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, 0));\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    for (int t = 0; t < T; t++) {\n        vector<int> maxVal(M, 0);\n        for (int l = 0; l < M; l++) {\n            for (int i = 0; i < seed_count; i++) {\n                maxVal[l] = max(maxVal[l], X[i][l]);\n            }\n        }\n        \n        auto getValue = [&](int idx) {\n            int total = 0;\n            for (int l = 0; l < M; l++) total += X[idx][l];\n            return total;\n        };\n        \n        auto getMaxCount = [&](int idx) {\n            int cnt = 0;\n            for (int l = 0; l < M; l++) {\n                if (X[idx][l] == maxVal[l]) cnt++;\n            }\n            return cnt;\n        };\n        \n        auto getMaxSum = [&](int idx) {\n            int sum = 0;\n            for (int l = 0; l < M; l++) {\n                if (X[idx][l] == maxVal[l]) sum += X[idx][l];\n            }\n            return sum;\n        };\n        \n        // Selection: include maxSum to prefer seeds with important max values\n        vector<pair<double, int>> seed_scores(seed_count);\n        for (int i = 0; i < seed_count; i++) {\n            double score = getValue(i) + getMaxCount(i) * 1000.0 + getMaxSum(i) * 2.0;\n            seed_scores[i] = {score, i};\n        }\n        \n        sort(seed_scores.begin(), seed_scores.end(), greater<pair<double, int>>());\n        \n        vector<int> selected(N * N);\n        for (int i = 0; i < N * N; i++) {\n            selected[i] = seed_scores[i].second;\n        }\n        \n        // Placement: best formula from before\n        sort(selected.begin(), selected.end(), [&](int a, int b) {\n            double sa = getValue(a) + getMaxCount(a) * 400.0 + getMaxSum(a) * 2.0;\n            double sb = getValue(b) + getMaxCount(b) * 400.0 + getMaxSum(b) * 2.0;\n            if (sa != sb) return sa > sb;\n            return getValue(a) > getValue(b);\n        });\n        \n        vector<pair<int, int>> pos_order;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                pos_order.push_back({i, j});\n            }\n        }\n        \n        double cx = (N - 1) / 2.0;\n        double cy = (N - 1) / 2.0;\n        sort(pos_order.begin(), pos_order.end(), [&](auto& a, auto& b) {\n            double da = abs(a.first - cx) + abs(a.second - cy);\n            double db = abs(b.first - cx) + abs(b.second - cy);\n            if (da != db) return da < db;\n            if (a.first != b.first) return a.first < b.first;\n            return a.second < b.second;\n        });\n        \n        vector<vector<int>> A(N, vector<int>(N, -1));\n        for (int i = 0; i < N * N; i++) {\n            A[pos_order[i].first][pos_order[i].second] = selected[i];\n        }\n        \n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << A[i][j];\n                if (j < N - 1) cout << \" \";\n                else cout << \"\\n\";\n            }\n        }\n        cout.flush();\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\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M, V;\nconst int DX[] = {0, 1, 0, -1};\nconst int DY[] = {1, 0, -1, 0};\n\nint rx, ry;\nvector<int> dirs;\nvector<int> lens;\nvector<bool> holding;\nint numF;\n\npair<int,int> fingertip(int i) { \n    return {rx + DX[dirs[i]] * lens[i], ry + DY[dirs[i]] * lens[i]}; \n}\nbool valid(int x, int y) { return x >= 0 && x < N && y >= 0 && y < N; }\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> M >> V;\n    vector<string> grid(N), target(N);\n    for (int i = 0; i < N; i++) cin >> grid[i];\n    for (int i = 0; i < N; i++) cin >> target[i];\n    \n    numF = V - 1;\n    \n    // Use varied edge lengths for better coverage\n    lens.resize(numF);\n    for (int i = 0; i < numF; i++) {\n        lens[i] = min(i + 1, N - 1);\n    }\n    \n    cout << numF + 1 << \"\\n\";\n    for (int i = 0; i < numF; i++) cout << \"0 \" << lens[i] << \"\\n\";\n    \n    // Calculate centroid for better starting position\n    set<pair<int,int>> pickup, dropS;\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < N; j++) {\n            if (grid[i][j] == '1' && target[i][j] == '0') pickup.insert({i, j});\n            if (target[i][j] == '1' && grid[i][j] == '0') dropS.insert({i, j});\n        }\n    \n    int sumX = 0, sumY = 0, cnt = 0;\n    for (auto& p : pickup) { sumX += p.first; sumY += p.second; cnt++; }\n    for (auto& p : dropS) { sumX += p.first; sumY += p.second; cnt++; }\n    \n    rx = cnt > 0 ? sumX / cnt : N / 2;\n    ry = cnt > 0 ? sumY / cnt : N / 2;\n    rx = max(0, min(N - 1, rx));\n    ry = max(0, min(N - 1, ry));\n    \n    cout << rx << \" \" << ry << \"\\n\";\n    \n    dirs.assign(numF, 0);\n    holding.assign(numF, false);\n    \n    vector<string> ops;\n    \n    while (ops.size() < 95000 && (!pickup.empty() || !dropS.empty() || \n           any_of(holding.begin(), holding.end(), [](bool h){return h;}))) {\n        \n        vector<char> rot(numF, '.'), act(numF, '.');\n        bool acted = false;\n        \n        for (int i = 0; i < numF; i++) {\n            auto [fx, fy] = fingertip(i);\n            if (!valid(fx, fy)) continue;\n            if (!holding[i] && pickup.count({fx, fy})) {\n                act[i] = 'P'; pickup.erase({fx, fy}); holding[i] = true; acted = true;\n            } else if (holding[i] && dropS.count({fx, fy})) {\n                act[i] = 'P'; dropS.erase({fx, fy}); holding[i] = false; acted = true;\n            }\n        }\n        if (acted) {\n            string s = \".\";\n            for (int i = 0; i < numF; i++) s += '.';\n            s += '.';\n            for (int i = 0; i < numF; i++) s += act[i];\n            ops.push_back(s);\n            continue;\n        }\n        \n        int bestF = -1, bestDir = 0, bestCost = INT_MAX;\n        pair<int,int> bestTarget;\n        \n        for (int i = 0; i < numF; i++) {\n            auto& targets = holding[i] ? dropS : pickup;\n            if (targets.empty()) continue;\n            \n            for (auto& t : targets) {\n                for (int d = 0; d < 4; d++) {\n                    int nrx = t.first - DX[d] * lens[i];\n                    int nry = t.second - DY[d] * lens[i];\n                    if (!valid(nrx, nry)) continue;\n                    int diff = (d - dirs[i] + 4) % 4;\n                    int rotCost = min(diff, 4 - diff);\n                    int cost = abs(nrx - rx) + abs(nry - ry) + rotCost;\n                    if (cost < bestCost) {\n                        bestCost = cost; bestF = i;\n                        bestTarget = t; bestDir = d;\n                    }\n                }\n            }\n        }\n        \n        if (bestF == -1) break;\n        \n        int trx = bestTarget.first - DX[bestDir] * lens[bestF];\n        int tr_y = bestTarget.second - DY[bestDir] * lens[bestF];\n        char mv = '.';\n        \n        if (rx < trx && valid(rx + 1, ry)) { mv = 'D'; rx++; }\n        else if (rx > trx && valid(rx - 1, ry)) { mv = 'U'; rx--; }\n        else if (ry < tr_y && valid(rx, ry + 1)) { mv = 'R'; ry++; }\n        else if (ry > tr_y && valid(rx, ry - 1)) { mv = 'L'; ry--; }\n        \n        if (dirs[bestF] != bestDir) {\n            int diff = (bestDir - dirs[bestF] + 4) % 4;\n            if (diff == 1) { rot[bestF] = 'R'; dirs[bestF] = (dirs[bestF] + 1) % 4; }\n            else if (diff == 3) { rot[bestF] = 'L'; dirs[bestF] = (dirs[bestF] + 3) % 4; }\n            else { rot[bestF] = 'R'; dirs[bestF] = (dirs[bestF] + 1) % 4; }\n        }\n        \n        if (mv == '.' && rot[bestF] == '.') {\n            if (valid(rx + 1, ry)) { mv = 'D'; rx++; }\n            else if (valid(rx - 1, ry)) { mv = 'U'; rx--; }\n            else if (valid(rx, ry + 1)) { mv = 'R'; ry++; }\n            else if (valid(rx, ry - 1)) { mv = 'L'; ry--; }\n            else { rot[bestF] = 'R'; dirs[bestF] = (dirs[bestF] + 1) % 4; }\n        }\n        \n        string s; s += mv;\n        for (int i = 0; i < numF; i++) s += rot[i];\n        s += '.';\n        for (int i = 0; i < numF; i++) s += act[i];\n        ops.push_back(s);\n    }\n    \n    for (auto& op : ops) cout << op << \"\\n\";\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nint nx, ny;\nvector<int> xs, ys;\nvector<vector<int>> grid;\n\nint query(int y1, int x1, int y2, int x2) {\n    if (x1 > x2 || y1 > y2) return 0;\n    return grid[y2+1][x2+1] - grid[y1][x2+1] - grid[y2+1][x1] + grid[y1][x1];\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N; cin >> N;\n    vector<pair<int,int>> mackerel(N), sardine(N);\n    for (int i = 0; i < N; i++) cin >> mackerel[i].first >> mackerel[i].second;\n    for (int i = 0; i < N; i++) cin >> sardine[i].first >> sardine[i].second;\n    \n    for (auto& p : mackerel) { xs.push_back(p.first); ys.push_back(p.second); }\n    for (auto& p : sardine) { xs.push_back(p.first); ys.push_back(p.second); }\n    \n    sort(xs.begin(), xs.end()); xs.erase(unique(xs.begin(), xs.end()), xs.end());\n    sort(ys.begin(), ys.end()); ys.erase(unique(ys.begin(), ys.end()), ys.end());\n    \n    nx = xs.size(); ny = ys.size();\n    map<int,int> x_idx, y_idx;\n    for (int i = 0; i < nx; i++) x_idx[xs[i]] = i;\n    for (int i = 0; i < ny; i++) y_idx[ys[i]] = i;\n    \n    grid.assign(ny+1, vector<int>(nx+1, 0));\n    for (auto& p : mackerel) grid[y_idx[p.second]+1][x_idx[p.first]+1]++;\n    for (auto& p : sardine) grid[y_idx[p.second]+1][x_idx[p.first]+1]--;\n    for (int i = 1; i <= ny; i++)\n        for (int j = 1; j <= nx; j++)\n            grid[i][j] += grid[i-1][j] + grid[i][j-1] - grid[i-1][j-1];\n    \n    int best_score = 0, bx1 = 0, by1 = 0, bx2 = 0, by2 = 0;\n    int best_type = 0, best_c1 = -1, best_c2 = -1;\n    int best_cx[4], best_cy[4];\n    \n    for (int seed = 1; seed <= 8; seed++) {\n        mt19937 rng(seed * 41 + 17);\n        vector<tuple<int,int,int,int,int>> candidates;\n        int init_best = 0;\n        \n        for (int iter = 0; iter < 280000; iter++) {\n            int i1 = rng() % N, i2 = rng() % N;\n            int x1i = x_idx[mackerel[i1].first], y1i = y_idx[mackerel[i1].second];\n            int x2i = x_idx[mackerel[i2].first], y2i = y_idx[mackerel[i2].second];\n            if (x1i > x2i) swap(x1i, x2i); if (y1i > y2i) swap(y1i, y2i);\n            int score = query(y1i, x1i, y2i, x2i);\n            if (score > init_best - 150) candidates.push_back({score, x1i, y1i, x2i, y2i});\n            if (score > init_best) init_best = score;\n        }\n        \n        sort(candidates.rbegin(), candidates.rend());\n        if (candidates.size() > 30) candidates.resize(30);\n        \n        for (auto& [sc, rx1, ry1, rx2, ry2] : candidates) {\n            int cx1 = rx1, cy1 = ry1, cx2 = rx2, cy2 = ry2;\n            for (int round = 0; round < 3; round++) {\n                for (int x = 0; x <= cx2; x++) if (query(cy1, x, cy2, cx2) > query(cy1, cx1, cy2, cx2)) cx1 = x;\n                for (int x = cx1; x < nx; x++) if (query(cy1, cx1, cy2, x) > query(cy1, cx1, cy2, cx2)) cx2 = x;\n                for (int y = 0; y <= cy2; y++) if (query(y, cx1, cy2, cx2) > query(cy1, cx1, cy2, cx2)) cy1 = y;\n                for (int y = cy1; y < ny; y++) if (query(cy1, cx1, y, cx2) > query(cy1, cx1, cy2, cx2)) cy2 = y;\n            }\n            int rect_score = query(cy1, cx1, cy2, cx2);\n            if (rect_score > best_score) { best_score = rect_score; bx1 = cx1; by1 = cy1; bx2 = cx2; by2 = cy2; best_type = 0; }\n            \n            if (cx2 > cx1 + 1 && cy2 > cy1 + 1) {\n                int cut_imp[4] = {0,0,0,0}, cut_cx[4], cut_cy[4];\n                for (int iter = 0; iter < 3000; iter++) {\n                    int c = rng() % 4;\n                    int ccx = cx1 + 1 + rng() % (cx2 - cx1 - 1);\n                    int ccy = cy1 + 1 + rng() % (cy2 - cy1 - 1);\n                    int cut = 0;\n                    if (c == 0) cut = query(cy1, cx1, ccy-1, ccx-1);\n                    else if (c == 1) cut = query(cy1, ccx+1, ccy-1, cx2);\n                    else if (c == 2) cut = query(ccy+1, ccx+1, cy2, cx2);\n                    else cut = query(ccy+1, cx1, cy2, ccx-1);\n                    if (-cut > cut_imp[c]) { cut_imp[c] = -cut; cut_cx[c] = ccx; cut_cy[c] = ccy; }\n                }\n                \n                for (int c = 0; c < 4; c++)\n                    if (rect_score + cut_imp[c] > best_score) {\n                        best_score = rect_score + cut_imp[c]; bx1 = cx1; by1 = cy1; bx2 = cx2; by2 = cy2;\n                        best_type = 1; best_c1 = c;\n                        for (int i = 0; i < 4; i++) { best_cx[i] = cut_cx[i]; best_cy[i] = cut_cy[i]; }\n                    }\n                \n                if (cut_imp[0] > 0 && cut_imp[2] > 0 && cut_cx[0] < cut_cx[2] && cut_cy[0] < cut_cy[2])\n                    if (rect_score + cut_imp[0] + cut_imp[2] > best_score) {\n                        best_score = rect_score + cut_imp[0] + cut_imp[2]; bx1 = cx1; by1 = cy1; bx2 = cx2; by2 = cy2;\n                        best_type = 2; best_c1 = 0; best_c2 = 2;\n                        for (int i = 0; i < 4; i++) { best_cx[i] = cut_cx[i]; best_cy[i] = cut_cy[i]; }\n                    }\n                if (cut_imp[1] > 0 && cut_imp[3] > 0 && cut_cx[3] < cut_cx[1] && cut_cy[1] < cut_cy[3])\n                    if (rect_score + cut_imp[1] + cut_imp[3] > best_score) {\n                        best_score = rect_score + cut_imp[1] + cut_imp[3]; bx1 = cx1; by1 = cy1; bx2 = cx2; by2 = cy2;\n                        best_type = 2; best_c1 = 1; best_c2 = 3;\n                        for (int i = 0; i < 4; i++) { best_cx[i] = cut_cx[i]; best_cy[i] = cut_cy[i]; }\n                    }\n            }\n        }\n    }\n    \n    if (best_score <= 0) { cout << \"4\\n0 0\\n1 0\\n1 1\\n0 1\\n\"; return 0; }\n    int ox1 = xs[bx1], oy1 = ys[by1], ox2 = xs[bx2], oy2 = ys[by2];\n    \n    if (best_type == 0) cout << \"4\\n\" << ox1 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy2 << \"\\n\" << ox1 << \" \" << oy2 << \"\\n\";\n    else if (best_type == 1) {\n        int ocx = xs[best_cx[best_c1]], ocy = ys[best_cy[best_c1]];\n        cout << \"6\\n\";\n        if (best_c1 == 0) cout << ocx << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy2 << \"\\n\" << ox1 << \" \" << oy2 << \"\\n\" << ox1 << \" \" << ocy << \"\\n\" << ocx << \" \" << ocy << \"\\n\";\n        else if (best_c1 == 1) cout << ox1 << \" \" << oy1 << \"\\n\" << ocx << \" \" << oy1 << \"\\n\" << ocx << \" \" << ocy << \"\\n\" << ox2 << \" \" << ocy << \"\\n\" << ox2 << \" \" << oy2 << \"\\n\" << ox1 << \" \" << oy2 << \"\\n\";\n        else if (best_c1 == 2) cout << ox1 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << ocy << \"\\n\" << ocx << \" \" << ocy << \"\\n\" << ocx << \" \" << oy2 << \"\\n\" << ox1 << \" \" << oy2 << \"\\n\";\n        else cout << ox1 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy2 << \"\\n\" << ocx << \" \" << oy2 << \"\\n\" << ocx << \" \" << ocy << \"\\n\" << ox1 << \" \" << ocy << \"\\n\";\n    } else {\n        int ocx0 = xs[best_cx[best_c1]], ocy0 = ys[best_cy[best_c1]], ocx2 = xs[best_cx[best_c2]], ocy2 = ys[best_cy[best_c2]];\n        cout << \"8\\n\";\n        if (best_c1 == 0) cout << ocx0 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << oy1 << \"\\n\" << ox2 << \" \" << ocy2 << \"\\n\" << ocx2 << \" \" << ocy2 << \"\\n\" << ocx2 << \" \" << oy2 << \"\\n\" << ox1 << \" \" << oy2 << \"\\n\" << ox1 << \" \" << ocy0 << \"\\n\" << ocx0 << \" \" << ocy0 << \"\\n\";\n        else cout << ox1 << \" \" << oy1 << \"\\n\" << ocx0 << \" \" << oy1 << \"\\n\" << ocx0 << \" \" << ocy0 << \"\\n\" << ox2 << \" \" << ocy0 << \"\\n\" << ox2 << \" \" << oy2 << \"\\n\" << ocx2 << \" \" << oy2 << \"\\n\" << ocx2 << \" \" << ocy2 << \"\\n\" << ox1 << \" \" << ocy2 << \"\\n\";\n    }\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, T;\nlong long sigma;\nvector<long long> w, h;\n\nstruct PlacedRect { long long x1, y1, x2, y2; int id; };\n\npair<long long, long long> simulate(const vector<tuple<int,int,char,int>>& ops) {\n    vector<PlacedRect> placed;\n    long long W = 0, H = 0;\n    for (auto& [p, r, d, b] : ops) {\n        long long rw = w[p], rh = h[p];\n        if (r) swap(rw, rh);\n        long long x = 0, y = 0;\n        if (d == 'U') {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n            for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n        } else {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n            for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n        }\n        placed.push_back({x, y, x + rw, y + rh, p});\n        W = max(W, x + rw); H = max(H, y + rh);\n    }\n    return {W, H};\n}\n\nmt19937 rng(42);\n\nvector<tuple<int,int,char,int>> genGreedy(double wBias, int maxBase = 15) {\n    vector<tuple<int,int,char,int>> ops;\n    vector<PlacedRect> placed;\n    long long curW = 0, curH = 0;\n    \n    for (int i = 0; i < N; i++) {\n        double best = 1e18; \n        tuple<int,char,int> bc = {0,'U',-1};\n        \n        for (int r = 0; r < 2; r++) {\n            long long rw = w[i], rh = h[i]; \n            if (r) swap(rw, rh);\n            \n            for (char d : {'U','L'}) {\n                for (int b = -1; b < i; b++) {\n                    if (b >= 0 && i - b > maxBase) continue;\n                    \n                    long long x = 0, y = 0;\n                    if (d == 'U') {\n                        if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n                        for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n                    } else {\n                        if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n                        for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n                    }\n                    double sc = wBias * max(curW, x+rw) + max(curH, y+rh);\n                    if (sc < best) { best = sc; bc = {r, d, b}; }\n                }\n            }\n        }\n        \n        auto [r, d, b] = bc;\n        long long rw = w[i], rh = h[i]; if (r) swap(rw, rh);\n        long long x = 0, y = 0;\n        if (d == 'U') {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { x = pr.x2; break; }\n            for (auto& pr : placed) if (x < pr.x2 && x + rw > pr.x1) y = max(y, pr.y2);\n        } else {\n            if (b >= 0) for (auto& pr : placed) if (pr.id == b) { y = pr.y2; break; }\n            for (auto& pr : placed) if (y < pr.y2 && y + rh > pr.y1) x = max(x, pr.x2);\n        }\n        placed.push_back({x, y, x+rw, y+rh, i}); \n        curW = max(curW, x+rw); curH = max(curH, y+rh);\n        ops.push_back({i, r, d, b});\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> genShelf(double widthFactor, int rotMode) {\n    long long totalArea = 0;\n    for (int i = 0; i < N; i++) totalArea += w[i] * h[i];\n    long long targetW = max(1LL, (long long)(sqrt((double)totalArea) * widthFactor));\n    \n    vector<tuple<int,int,char,int>> ops;\n    long long curX = 0;\n    int lastInShelf = -1, shelfStart = -1;\n    \n    for (int i = 0; i < N; i++) {\n        int r = (rotMode == 0) ? 0 : (rotMode == 1) ? 1 : (h[i] > w[i] ? 1 : 0);\n        long long rw = w[i], rh = h[i]; if (r) swap(rw, rh);\n        \n        if (curX + rw > targetW && lastInShelf >= 0) {\n            ops.push_back({i, r, 'L', shelfStart});\n            shelfStart = i; curX = rw; lastInShelf = i;\n        } else {\n            if (lastInShelf < 0) {\n                ops.push_back({i, r, 'U', -1});\n                shelfStart = i;\n            } else {\n                ops.push_back({i, r, 'U', lastInShelf});\n            }\n            curX += rw; lastInShelf = i;\n        }\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> genStrip(char dir, int rotMode) {\n    vector<tuple<int,int,char,int>> ops;\n    for (int i = 0; i < N; i++) {\n        int r = (rotMode == 0) ? 0 : (rotMode == 1) ? 1 : \n                ((dir == 'U') ? (w[i] < h[i] ? 1 : 0) : (h[i] < w[i] ? 1 : 0));\n        ops.push_back({i, r, dir, -1});\n    }\n    return ops;\n}\n\nvector<tuple<int,int,char,int>> mutate(vector<tuple<int,int,char,int>> ops, int intensity) {\n    int numMut = 1 + rng() % (intensity + 1);\n    for (int m = 0; m < numMut; m++) {\n        int i = rng() % N;\n        auto& [p, r, d, b] = ops[i];\n        int choice = rng() % 3;\n        if (choice == 0) r = 1 - r;\n        else if (choice == 1) d = (d == 'U') ? 'L' : 'U';\n        else if (i > 0) b = (int)(rng() % (i + 1)) - 1;\n    }\n    return ops;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> T >> sigma;\n    w.resize(N); h.resize(N);\n    for (int i = 0; i < N; i++) cin >> w[i] >> h[i];\n    \n    auto startTime = chrono::steady_clock::now();\n    vector<pair<long long, vector<tuple<int,int,char,int>>>> candidates;\n    \n    auto addCandidate = [&](vector<tuple<int,int,char,int>> ops) {\n        auto [sw, sh] = simulate(ops);\n        candidates.push_back({sw + sh, ops});\n    };\n    \n    // Diverse greedy with different biases\n    for (double bias : {0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.5, 2.0}) {\n        addCandidate(genGreedy(bias));\n    }\n    \n    // Shelf packing with different widths\n    for (double wf : {0.6, 0.8, 1.0, 1.2, 1.5, 2.0}) {\n        for (int rm = 0; rm < 3; rm++) {\n            addCandidate(genShelf(wf, rm));\n        }\n    }\n    \n    // Strip packing\n    for (char d : {'U', 'L'}) {\n        for (int rm = 0; rm < 3; rm++) {\n            addCandidate(genStrip(d, rm));\n        }\n    }\n    \n    sort(candidates.begin(), candidates.end());\n    auto bestOps = candidates[0].second;\n    long long bestSim = candidates[0].first;\n    \n    // Hill climbing with time limit\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        if (chrono::duration_cast<chrono::milliseconds>(now - startTime).count() > 2500) break;\n        if ((int)candidates.size() >= T * 3) break;\n        \n        int srcIdx = (rng() % 100 < 70) ? 0 : rng() % min((int)candidates.size(), 10);\n        int intensity = 1 + (rng() % 3);\n        auto ops = mutate(candidates[srcIdx].second, intensity);\n        auto [sw, sh] = simulate(ops);\n        \n        if (sw + sh <= bestSim * 1.05) {\n            candidates.push_back({sw + sh, ops});\n            if (sw + sh < bestSim) { \n                bestSim = sw + sh; \n                bestOps = ops;\n            }\n        }\n    }\n    \n    sort(candidates.begin(), candidates.end());\n    \n    // Remove duplicates\n    vector<pair<long long, vector<tuple<int,int,char,int>>>> unique_cands;\n    set<vector<tuple<int,int,char,int>>> seen;\n    for (auto& c : candidates) {\n        if (seen.find(c.second) == seen.end()) {\n            seen.insert(c.second);\n            unique_cands.push_back(c);\n        }\n        if ((int)unique_cands.size() >= T) break;\n    }\n    candidates = unique_cands;\n    \n    // Fill remaining slots\n    while ((int)candidates.size() < T) {\n        auto ops = mutate(bestOps, 2);\n        auto [sw, sh] = simulate(ops);\n        candidates.push_back({sw + sh, ops});\n    }\n    \n    sort(candidates.begin(), candidates.end());\n    \n    for (int t = 0; t < T; t++) {\n        auto& ops = candidates[t].second;\n        cout << ops.size() << \"\\n\";\n        for (auto& [p, r, d, b] : ops) cout << p << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        cout.flush();\n        long long W, H; 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<int> parent_arr;\nvector<int> depth_arr;\nvector<vector<int>> children;\nvector<int> sub_h;\nvector<int> sub_sum;\nmt19937 rng(42);\n\nchrono::steady_clock::time_point start_time;\nint elapsed() {\n    return chrono::duration_cast<chrono::milliseconds>(\n        chrono::steady_clock::now() - start_time).count();\n}\n\nlong long compute_score() {\n    long long score = 0;\n    for (int i = 0; i < N; i++) {\n        score += (long long)(depth_arr[i] + 1) * A[i];\n    }\n    return score;\n}\n\nvoid rebuild_all() {\n    for (int i = 0; i < N; i++) children[i].clear();\n    for (int i = 0; i < N; i++) {\n        if (parent_arr[i] != -1) {\n            children[parent_arr[i]].push_back(i);\n        }\n    }\n    \n    fill(depth_arr.begin(), depth_arr.end(), -1);\n    queue<int> q;\n    for (int i = 0; i < N; i++) {\n        if (parent_arr[i] == -1) {\n            depth_arr[i] = 0;\n            q.push(i);\n        }\n    }\n    while (!q.empty()) {\n        int u = q.front(); q.pop();\n        for (int c : children[u]) {\n            depth_arr[c] = depth_arr[u] + 1;\n            q.push(c);\n        }\n    }\n    \n    function<pair<int,int>(int)> calc = [&](int v) -> pair<int,int> {\n        int h = 0, s = A[v];\n        for (int c : children[v]) {\n            auto [ch, cs] = calc(c);\n            h = max(h, 1 + ch);\n            s += cs;\n        }\n        sub_h[v] = h;\n        sub_sum[v] = s;\n        return {h, s};\n    };\n    for (int i = 0; i < N; i++) {\n        if (parent_arr[i] == -1) calc(i);\n    }\n}\n\nvoid dfs(int u) {\n    vector<pair<int, int>> neighbors;\n    for (int v : adj[u]) {\n        if (depth_arr[v] == -1) {\n            neighbors.push_back({-A[v], v});\n        }\n    }\n    sort(neighbors.begin(), neighbors.end());\n    \n    for (auto& [neg_beauty, v] : neighbors) {\n        if (depth_arr[v] == -1 && depth_arr[u] < H) {\n            parent_arr[v] = u;\n            depth_arr[v] = depth_arr[u] + 1;\n            dfs(v);\n        }\n    }\n}\n\nbool is_ancestor(int anc, int desc) {\n    for (int i = 0; i <= H && desc != -1; i++) {\n        if (desc == anc) return true;\n        desc = parent_arr[desc];\n    }\n    return false;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    start_time = chrono::steady_clock::now();\n    \n    cin >> N >> M >> H;\n    \n    A.resize(N);\n    for (int i = 0; i < N; i++) cin >> A[i];\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    for (int i = 0; i < N; i++) {\n        int x, y;\n        cin >> x >> y;\n    }\n    \n    parent_arr.resize(N);\n    depth_arr.resize(N);\n    children.resize(N);\n    sub_h.resize(N);\n    sub_sum.resize(N);\n    \n    vector<int> best_parent(N, -1);\n    long long best_score = 0;\n    \n    // Multiple restarts with diverse strategies\n    for (int trial = 0; trial < 800 && elapsed() < 500; trial++) {\n        fill(parent_arr.begin(), parent_arr.end(), -1);\n        fill(depth_arr.begin(), depth_arr.end(), -1);\n        \n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        \n        if (trial == 0) {\n            sort(order.begin(), order.end(), [&](int a, int b) { return A[a] < A[b]; });\n        } else if (trial == 1) {\n            sort(order.begin(), order.end(), [&](int a, int b) { return adj[a].size() < adj[b].size(); });\n        } else if (trial == 2) {\n            sort(order.begin(), order.end(), [&](int a, int b) { \n                return A[a] * (int)adj[a].size() < A[b] * (int)adj[b].size(); \n            });\n        } else if (trial == 3) {\n            sort(order.begin(), order.end(), [&](int a, int b) { \n                return (double)A[a] / adj[a].size() < (double)A[b] / adj[b].size(); \n            });\n        } else {\n            vector<int> keys(N);\n            for (int i = 0; i < N; i++) keys[i] = A[i] + (rng() % 100);\n            sort(order.begin(), order.end(), [&](int a, int b) { return keys[a] < keys[b]; });\n        }\n        \n        for (int start : order) {\n            if (depth_arr[start] != -1) continue;\n            depth_arr[start] = 0;\n            parent_arr[start] = -1;\n            dfs(start);\n        }\n        \n        long long score = compute_score();\n        if (score > best_score) {\n            best_score = score;\n            best_parent = parent_arr;\n        }\n    }\n    \n    parent_arr = best_parent;\n    rebuild_all();\n    \n    // Local search with persistence\n    vector<int> vorder(N);\n    iota(vorder.begin(), vorder.end(), 0);\n    \n    int no_improve_count = 0;\n    for (int phase = 0; phase < 1000 && elapsed() < 1850; phase++) {\n        bool improved = false;\n        \n        int strategy = phase % 6;\n        if (strategy == 0) {\n            sort(vorder.begin(), vorder.end(), [&](int a, int b) { return A[a] > A[b]; });\n        } else if (strategy == 1) {\n            sort(vorder.begin(), vorder.end(), [&](int a, int b) { return depth_arr[a] < depth_arr[b]; });\n        } else if (strategy == 2) {\n            sort(vorder.begin(), vorder.end(), [&](int a, int b) { \n                return A[a] * (H - depth_arr[a]) > A[b] * (H - depth_arr[b]); \n            });\n        } else if (strategy == 3) {\n            sort(vorder.begin(), vorder.end(), [&](int a, int b) { return sub_sum[a] > sub_sum[b]; });\n        } else if (strategy == 4) {\n            sort(vorder.begin(), vorder.end(), [&](int a, int b) { return A[a] < A[b]; }); // Low beauty first\n        } else {\n            shuffle(vorder.begin(), vorder.end(), rng);\n        }\n        \n        // Operation 1: Reparent to go deeper\n        for (int v : vorder) {\n            if (elapsed() > 1850) break;\n            \n            int cur_depth = depth_arr[v];\n            int best_new_parent = -1;\n            int best_gain = 0;\n            \n            for (int u : adj[v]) {\n                if (u == parent_arr[v]) continue;\n                if (is_ancestor(v, u)) continue;\n                \n                int new_depth = depth_arr[u] + 1;\n                if (new_depth + sub_h[v] <= H && new_depth > cur_depth) {\n                    int total_gain = (new_depth - cur_depth) * sub_sum[v];\n                    if (total_gain > best_gain) {\n                        best_gain = total_gain;\n                        best_new_parent = u;\n                    }\n                }\n            }\n            \n            if (best_new_parent != -1) {\n                parent_arr[v] = best_new_parent;\n                rebuild_all();\n                improved = true;\n            }\n        }\n        \n        // Operation 2: Attach roots\n        for (int r : vorder) {\n            if (elapsed() > 1850) break;\n            if (parent_arr[r] != -1) continue;\n            \n            int best_p = -1;\n            int best_gain = 0;\n            \n            for (int u : adj[r]) {\n                int new_depth = depth_arr[u] + 1;\n                if (new_depth + sub_h[r] <= H) {\n                    int gain = new_depth * sub_sum[r];\n                    if (gain > best_gain) {\n                        best_gain = gain;\n                        best_p = u;\n                    }\n                }\n            }\n            \n            if (best_p != -1) {\n                parent_arr[r] = best_p;\n                rebuild_all();\n                improved = true;\n            }\n        }\n        \n        long long cur_score = compute_score();\n        if (cur_score > best_score) {\n            best_score = cur_score;\n            best_parent = parent_arr;\n            no_improve_count = 0;\n        } else {\n            no_improve_count++;\n        }\n        \n        // Allow more phases even without improvement\n        if (!improved) {\n            if (no_improve_count > 12) break;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) {\n        cout << best_parent[i];\n        if (i < N - 1) cout << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nint oni_r[50], oni_c[50];\nint valid_cnt[50], valid[50][4], dist[50][4];\nint asgn[50], batch_max[80];\n\ninline int get_key(int k, int d) { return d * 20 + ((d <= 1) ? oni_c[k] : oni_r[k]); }\n\nint full_cost() {\n    memset(batch_max, 0, sizeof(batch_max));\n    for (int k = 0; k < M; k++) {\n        int key = get_key(k, asgn[k]);\n        batch_max[key] = max(batch_max[key], dist[k][asgn[k]]);\n    }\n    int t = 0; for (int i = 0; i < 80; i++) t += batch_max[i];\n    return 2 * t;\n}\n\nint try_change(int k, int new_d) {\n    int old_d = asgn[k];\n    if (old_d == new_d) return 0;\n    int old_key = get_key(k, old_d), new_key = get_key(k, new_d);\n    int old_cost = 2 * (batch_max[old_key] + batch_max[new_key]);\n    \n    int new_old_max = 0;\n    for (int i = 0; i < M; i++) if (i != k && get_key(i, asgn[i]) == old_key)\n        new_old_max = max(new_old_max, dist[i][asgn[i]]);\n    int new_new_max = max(batch_max[new_key], dist[k][new_d]);\n    \n    return 2 * (new_old_max + new_new_max) - old_cost;\n}\n\nvoid apply_change(int k, int new_d) {\n    int old_key = get_key(k, asgn[k]), new_key = get_key(k, new_d);\n    asgn[k] = new_d;\n    int new_old_max = 0;\n    for (int i = 0; i < M; i++) if (get_key(i, asgn[i]) == old_key)\n        new_old_max = max(new_old_max, dist[i][asgn[i]]);\n    batch_max[old_key] = new_old_max;\n    batch_max[new_key] = max(batch_max[new_key], dist[k][new_d]);\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n    auto start = chrono::steady_clock::now();\n    auto elapsed = [&]() { return chrono::duration<double>(chrono::steady_clock::now() - start).count(); };\n    \n    cin >> N;\n    vector<string> board(N);\n    for (int i = 0; i < N; i++) cin >> board[i];\n    \n    for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (board[i][j] == 'x') {\n        oni_r[M] = i; oni_c[M] = j; M++;\n    }\n    \n    for (int k = 0; k < M; k++) {\n        int r = oni_r[k], c = oni_c[k];\n        bool ok = true; for (int i = 0; i < r && ok; i++) if (board[i][c] == 'o') ok = false;\n        if (ok) { valid[k][valid_cnt[k]] = 0; dist[k][0] = r + 1; valid_cnt[k]++; }\n        ok = true; for (int i = r+1; i < N && ok; i++) if (board[i][c] == 'o') ok = false;\n        if (ok) { valid[k][valid_cnt[k]] = 1; dist[k][1] = N - r; valid_cnt[k]++; }\n        ok = true; for (int j = 0; j < c && ok; j++) if (board[r][j] == 'o') ok = false;\n        if (ok) { valid[k][valid_cnt[k]] = 2; dist[k][2] = c + 1; valid_cnt[k]++; }\n        ok = true; for (int j = c+1; j < N && ok; j++) if (board[r][j] == 'o') ok = false;\n        if (ok) { valid[k][valid_cnt[k]] = 3; dist[k][3] = N - c; valid_cnt[k]++; }\n    }\n    \n    mt19937 rng(42);\n    int best_asgn[50], best_cost = INT_MAX;\n    \n    auto local_search = [&]() {\n        int cur = full_cost();\n        for (int it = 0; it < 30; it++) {\n            bool imp = false;\n            for (int k = 0; k < M; k++) for (int vi = 0; vi < valid_cnt[k]; vi++) {\n                int d = valid[k][vi]; if (d == asgn[k]) continue;\n                int delta = try_change(k, d);\n                if (delta < 0) { apply_change(k, d); cur += delta; imp = true; }\n            }\n            if (!imp) break;\n        }\n        if (cur < best_cost) { best_cost = cur; memcpy(best_asgn, asgn, sizeof(asgn)); }\n    };\n    \n    // Initial: minimum individual distance\n    for (int k = 0; k < M; k++) {\n        int bd = valid[k][0];\n        for (int vi = 0; vi < valid_cnt[k]; vi++) if (dist[k][valid[k][vi]] < dist[k][bd]) bd = valid[k][vi];\n        asgn[k] = bd;\n    }\n    local_search();\n    \n    // Prefer each direction\n    for (int p = 0; p < 4; p++) {\n        for (int k = 0; k < M; k++) {\n            asgn[k] = valid[k][0];\n            for (int vi = 0; vi < valid_cnt[k]; vi++) if (valid[k][vi] == p) { asgn[k] = p; break; }\n        }\n        local_search();\n    }\n    \n    // Greedy incremental\n    vector<int> order(M); iota(order.begin(), order.end(), 0);\n    for (int t = 0; t < 30 && elapsed() < 0.3; t++) {\n        shuffle(order.begin(), order.end(), rng);\n        memset(asgn, -1, sizeof(asgn)); memset(batch_max, 0, sizeof(batch_max));\n        for (int k : order) {\n            int bd = valid[k][0], bc = INT_MAX;\n            for (int vi = 0; vi < valid_cnt[k]; vi++) {\n                int d = valid[k][vi], key = get_key(k, d);\n                int add = max(0, dist[k][d] - batch_max[key]);\n                if (add < bc) { bc = add; bd = d; }\n            }\n            asgn[k] = bd; batch_max[get_key(k, bd)] = max(batch_max[get_key(k, bd)], dist[k][bd]);\n        }\n        local_search();\n    }\n    \n    // SA with restarts\n    memcpy(asgn, best_asgn, sizeof(asgn)); full_cost();\n    int cur_cost = best_cost;\n    double temp = 10.0;\n    int no_improve = 0;\n    while (elapsed() < 1.9) {\n        int k = rng() % M;\n        if (valid_cnt[k] <= 1) continue;\n        int new_d = valid[k][rng() % valid_cnt[k]];\n        if (new_d == asgn[k]) continue;\n        int delta = try_change(k, new_d);\n        if (delta < 0 || (rng() % 10000) < 10000 * exp(-delta / temp)) {\n            apply_change(k, new_d); cur_cost += delta;\n            if (cur_cost < best_cost) { best_cost = cur_cost; memcpy(best_asgn, asgn, sizeof(asgn)); no_improve = 0; }\n            else no_improve++;\n        } else no_improve++;\n        temp *= 0.999995;\n        if (no_improve > 50000) { memcpy(asgn, best_asgn, sizeof(asgn)); full_cost(); cur_cost = best_cost; temp = 5.0; no_improve = 0; }\n    }\n    \n    map<int, int> batches;\n    for (int k = 0; k < M; k++) batches[get_key(k, best_asgn[k])] = max(batches[get_key(k, best_asgn[k])], dist[k][best_asgn[k]]);\n    \n    for (auto& [key, mx] : batches) {\n        int dir = key / 20, idx = key % 20;\n        char c1 = (dir == 0 ? 'U' : dir == 1 ? 'D' : dir == 2 ? 'L' : 'R');\n        char c2 = (dir == 0 ? 'D' : dir == 1 ? 'U' : dir == 2 ? 'R' : 'L');\n        for (int t = 0; t < mx; t++) cout << c1 << \" \" << idx << \"\\n\";\n        for (int t = 0; t < mx; t++) cout << c2 << \" \" << idx << \"\\n\";\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, L;\nvector<int> T;\n\nlong long simulate(const vector<int>& a, const vector<int>& b, vector<int>& t) {\n    fill(t.begin(), t.end(), 0);\n    int x = 0;\n    for (int week = 0; week < L; week++) {\n        t[x]++;\n        x = (t[x] & 1) ? a[x] : b[x];\n    }\n    long long error = 0;\n    for (int i = 0; i < N; i++) error += abs(t[i] - T[i]);\n    return error;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    cin >> N >> L;\n    T.resize(N);\n    for (int i = 0; i < N; i++) cin >> T[i];\n    \n    vector<int> weighted;\n    for (int i = 0; i < N; i++) {\n        int cnt = max(1, T[i] / 100);\n        for (int j = 0; j < cnt; j++) weighted.push_back(i);\n    }\n    \n    vector<int> sorted_idx(N);\n    iota(sorted_idx.begin(), sorted_idx.end(), 0);\n    sort(sorted_idx.begin(), sorted_idx.end(), [](int x, int y) { return T[x] > T[y]; });\n    \n    vector<int> best_a(N), best_b(N), t(N);\n    long long global_best = LLONG_MAX;\n    \n    auto start = chrono::steady_clock::now();\n    double sa_time_limit = 1.60;\n    \n    vector<int> seeds = {12345, 67890, 11111, 99999};\n    for (int seed : seeds) {\n        mt19937 rng(seed);\n        \n        for (int restart = 0; ; restart++) {\n            auto now = chrono::steady_clock::now();\n            double elapsed = chrono::duration<double>(now - start).count();\n            if (elapsed > sa_time_limit) break;\n            \n            vector<int> a(N), b(N);\n            \n            if (restart == 0) {\n                for (int i = 0; i < N; i++) {\n                    a[sorted_idx[i]] = sorted_idx[(i + 1) % N];\n                    b[sorted_idx[i]] = sorted_idx[(i + 1) % N];\n                }\n            } else if (restart == 1) {\n                for (int i = 0; i < N; i++) {\n                    a[sorted_idx[i]] = sorted_idx[(i + 1) % N];\n                    b[sorted_idx[i]] = sorted_idx[(i + 2) % N];\n                }\n            } else if (restart % 3 == 0 && global_best < LLONG_MAX) {\n                a = best_a; b = best_b;\n                for (int k = 0; k < N/4; k++) {\n                    int idx = rng() % N;\n                    a[idx] = weighted[rng() % weighted.size()];\n                    b[idx] = weighted[rng() % weighted.size()];\n                }\n            } else {\n                for (int i = 0; i < N; i++) {\n                    a[i] = weighted[rng() % weighted.size()];\n                    b[i] = weighted[rng() % weighted.size()];\n                }\n            }\n            \n            long long cur_error = simulate(a, b, t);\n            long long local_best = cur_error;\n            vector<int> local_a = a, local_b = b;\n            \n            double restart_budget = min(0.22, (sa_time_limit - elapsed) * 0.6);\n            double restart_start = elapsed;\n            \n            while (true) {\n                now = chrono::steady_clock::now();\n                elapsed = chrono::duration<double>(now - start).count();\n                if (elapsed > sa_time_limit || elapsed - restart_start > restart_budget) break;\n                \n                double progress = (elapsed - restart_start) / restart_budget;\n                double temp = 2500.0 * pow(0.0001, progress);\n                \n                int i = rng() % N;\n                int old_a = a[i], old_b = b[i];\n                \n                int choice = rng() % 4;\n                if (choice == 0) a[i] = weighted[rng() % weighted.size()];\n                else if (choice == 1) b[i] = weighted[rng() % weighted.size()];\n                else if (choice == 2) a[i] = rng() % N;\n                else b[i] = rng() % N;\n                \n                long long new_error = simulate(a, b, t);\n                double delta = new_error - cur_error;\n                \n                if (delta <= 0 || exp(-delta / temp) > (rng() % 1000000) / 1000000.0) {\n                    cur_error = new_error;\n                    if (new_error < local_best) {\n                        local_best = new_error;\n                        local_a = a; local_b = b;\n                    }\n                } else {\n                    a[i] = old_a; b[i] = old_b;\n                }\n            }\n            \n            if (local_best < global_best) {\n                global_best = local_best;\n                best_a = local_a; best_b = local_b;\n            }\n        }\n    }\n    \n    // Extended greedy hill climbing with single seed\n    mt19937 rng(777);\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > 1.97) break;\n        \n        int i = rng() % N;\n        int old_a = best_a[i], old_b = best_b[i];\n        \n        int choice = rng() % 5;\n        if (choice == 0) best_a[i] = weighted[rng() % weighted.size()];\n        else if (choice == 1) best_b[i] = weighted[rng() % weighted.size()];\n        else if (choice == 2) best_a[i] = rng() % N;\n        else if (choice == 3) best_b[i] = rng() % N;\n        else { best_a[i] = weighted[rng() % weighted.size()]; best_b[i] = weighted[rng() % weighted.size()]; }\n        \n        long long new_error = simulate(best_a, best_b, t);\n        if (new_error < global_best) {\n            global_best = new_error;\n        } else {\n            best_a[i] = old_a; best_b[i] = old_b;\n        }\n    }\n    \n    for (int i = 0; i < N; i++) cout << best_a[i] << \" \" << best_b[i] << \"\\n\";\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nint queries_used = 0;\nint Q_limit;\n\nvector<pair<int,int>> query(vector<int>& cities) {\n    if (queries_used >= Q_limit || cities.size() < 2) return {};\n    cout << \"? \" << cities.size();\n    for (int c : cities) cout << \" \" << c;\n    cout << endl;\n    \n    vector<pair<int,int>> edges;\n    for (size_t i = 0; i + 1 < cities.size(); i++) {\n        int a, b;\n        cin >> a >> b;\n        edges.emplace_back(a, b);\n    }\n    queries_used++;\n    return edges;\n}\n\ndouble estDist(double x1, double y1, double x2, double y2) {\n    double dx = x1 - x2, dy = y1 - y2;\n    return sqrt(dx*dx + dy*dy);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    Q_limit = Q;\n    \n    vector<int> G(M);\n    for (int i = 0; i < M; i++) cin >> G[i];\n    \n    vector<double> x(N), y(N);\n    for (int i = 0; i < N; i++) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        x[i] = (lx + rx) / 2.0;\n        y[i] = (ly + ry) / 2.0;\n    }\n    \n    // Greedy nearest-neighbor grouping\n    vector<bool> used(N, false);\n    vector<vector<int>> groups(M);\n    \n    vector<int> groupOrder(M);\n    iota(groupOrder.begin(), groupOrder.end(), 0);\n    sort(groupOrder.begin(), groupOrder.end(), [&](int a, int b) {\n        return G[a] > G[b];\n    });\n    \n    for (int gi : groupOrder) {\n        int g = G[gi];\n        double cx = 0, cy = 0;\n        int cnt = 0;\n        for (int i = 0; i < N; i++) {\n            if (!used[i]) { cx += x[i]; cy += y[i]; cnt++; }\n        }\n        if (cnt > 0) { cx /= cnt; cy /= cnt; }\n        \n        int start = -1;\n        double minD = 1e18;\n        for (int i = 0; i < N; i++) {\n            if (!used[i]) {\n                double d = estDist(x[i], y[i], cx, cy);\n                if (d < minD) { minD = d; start = i; }\n            }\n        }\n        \n        groups[gi].push_back(start);\n        used[start] = true;\n        \n        while ((int)groups[gi].size() < g) {\n            int best = -1;\n            double bestD = 1e18;\n            for (int i = 0; i < N; i++) {\n                if (used[i]) continue;\n                double minDistToGroup = 1e18;\n                for (int c : groups[gi]) {\n                    minDistToGroup = min(minDistToGroup, estDist(x[i], y[i], x[c], y[c]));\n                }\n                if (minDistToGroup < bestD) {\n                    bestD = minDistToGroup;\n                    best = i;\n                }\n            }\n            groups[gi].push_back(best);\n            used[best] = true;\n        }\n    }\n    \n    // Local TSP-like reordering within each group\n    for (int k = 0; k < M; k++) {\n        int g = groups[k].size();\n        if (g <= 2) continue;\n        \n        vector<int> ordered;\n        vector<bool> inOrder(g, false);\n        ordered.push_back(0);\n        inOrder[0] = true;\n        \n        while ((int)ordered.size() < g) {\n            int last = ordered.back();\n            int best = -1;\n            double bestD = 1e18;\n            for (int i = 0; i < g; i++) {\n                if (inOrder[i]) continue;\n                double d = estDist(x[groups[k][last]], y[groups[k][last]], \n                                   x[groups[k][i]], y[groups[k][i]]);\n                if (d < bestD) { bestD = d; best = i; }\n            }\n            ordered.push_back(best);\n            inOrder[best] = true;\n        }\n        \n        vector<int> newGroup(g);\n        for (int i = 0; i < g; i++) newGroup[i] = groups[k][ordered[i]];\n        groups[k] = newGroup;\n    }\n    \n    // Calculate total minimum queries needed\n    int totalMinQueries = 0;\n    for (int k = 0; k < M; k++) {\n        int g = groups[k].size();\n        if (g <= 1) continue;\n        else if (g <= L) totalMinQueries += 1;\n        else totalMinQueries += (g - 2) / (L - 1) + 1;\n    }\n    \n    vector<vector<pair<int,int>>> edges(M);\n    vector<vector<pair<int,int>>> all_edges_per_group(M);\n    \n    // First pass: ensure connectivity\n    for (int k = 0; k < M; k++) {\n        int g = groups[k].size();\n        if (g == 1) continue;\n        \n        if (g <= L && queries_used < Q) {\n            edges[k] = query(groups[k]);\n        } else {\n            int remainingBudget = Q - queries_used;\n            int remainingGroups = 0;\n            for (int j = k; j < M; j++) if (groups[j].size() > (size_t)L) remainingGroups++;\n            \n            int step = L - 1;\n            if (remainingBudget > totalMinQueries * 2 && remainingGroups > 0) {\n                step = max(1, (L - 1) / 2);\n            }\n            \n            // Main sliding window\n            for (int i = 0; i < g && queries_used < Q; i += step) {\n                int end = min(i + L, g);\n                if (end - i >= 2) {\n                    vector<int> subset(groups[k].begin() + i, groups[k].begin() + end);\n                    auto e = query(subset);\n                    all_edges_per_group[k].insert(all_edges_per_group[k].end(), e.begin(), e.end());\n                }\n                if (end >= g) break;\n            }\n            \n            // Second pass with offset\n            if (step > 1 && queries_used < Q && g > L) {\n                for (int i = step/2; i + 1 < g && queries_used < Q; i += step) {\n                    int end = min(i + L, g);\n                    if (end - i >= 2) {\n                        vector<int> subset(groups[k].begin() + i, groups[k].begin() + end);\n                        auto e = query(subset);\n                        all_edges_per_group[k].insert(all_edges_per_group[k].end(), e.begin(), e.end());\n                    }\n                    if (end >= g) break;\n                }\n            }\n            \n            // Build MST\n            map<int, int> city_to_local;\n            for (int i = 0; i < g; i++) city_to_local[groups[k][i]] = i;\n            \n            vector<int> parent(g);\n            iota(parent.begin(), parent.end(), 0);\n            function<int(int)> find = [&](int u) -> int {\n                return parent[u] == u ? u : parent[u] = find(parent[u]);\n            };\n            \n            auto& ae = all_edges_per_group[k];\n            sort(ae.begin(), ae.end(), [&](auto& a, auto& b) {\n                double da = estDist(x[a.first], y[a.first], x[a.second], y[a.second]);\n                double db = estDist(x[b.first], y[b.first], x[b.second], y[b.second]);\n                return da < db;\n            });\n            \n            for (auto& e : ae) {\n                int u = city_to_local[e.first];\n                int v = city_to_local[e.second];\n                if (find(u) != find(v)) {\n                    parent[find(u)] = find(v);\n                    edges[k].push_back(e);\n                }\n            }\n            \n            // Fallback\n            while ((int)edges[k].size() < g - 1) {\n                double best_dist = 1e18;\n                int best_u = -1, best_v = -1;\n                for (int i = 0; i < g; i++) {\n                    for (int j = i + 1; j < g; j++) {\n                        if (find(i) != find(j)) {\n                            double d = estDist(x[groups[k][i]], y[groups[k][i]], \n                                             x[groups[k][j]], y[groups[k][j]]);\n                            if (d < best_dist) {\n                                best_dist = d;\n                                best_u = i; best_v = j;\n                            }\n                        }\n                    }\n                }\n                if (best_u >= 0) {\n                    parent[find(best_u)] = find(best_v);\n                    edges[k].push_back({groups[k][best_u], groups[k][best_v]});\n                } else break;\n            }\n        }\n    }\n    \n    // Use remaining queries for large groups - random sampling\n    mt19937 rng(42);\n    vector<int> largeGroups;\n    for (int k = 0; k < M; k++) {\n        if ((int)groups[k].size() > L) largeGroups.push_back(k);\n    }\n    \n    while (queries_used < Q && !largeGroups.empty()) {\n        int k = largeGroups[rng() % largeGroups.size()];\n        int g = groups[k].size();\n        \n        // Sample L random cities\n        vector<int> indices(g);\n        iota(indices.begin(), indices.end(), 0);\n        shuffle(indices.begin(), indices.end(), rng);\n        \n        vector<int> subset;\n        for (int i = 0; i < min(L, g); i++) {\n            subset.push_back(groups[k][indices[i]]);\n        }\n        \n        auto e = query(subset);\n        // Check if any edge improves our MST\n        for (auto& edge : e) {\n            bool found = false;\n            for (auto& existing : edges[k]) {\n                if ((existing.first == edge.first && existing.second == edge.second) ||\n                    (existing.first == edge.second && existing.second == edge.first)) {\n                    found = true;\n                    break;\n                }\n            }\n            if (!found) {\n                all_edges_per_group[k].push_back(edge);\n            }\n        }\n    }\n    \n    cout << \"!\" << endl;\n    for (int k = 0; k < M; k++) {\n        for (int c : groups[k]) cout << c << \" \";\n        cout << \"\\n\";\n        for (auto& e : edges[k]) {\n            cout << e.first << \" \" << e.second << \"\\n\";\n        }\n    }\n    \n    return 0;\n}","ahc046":"#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<pair<int, int>> targets(M);\n    for (int i = 0; i < M; i++) {\n        cin >> targets[i].first >> targets[i].second;\n    }\n    \n    vector<string> actions;\n    int curR = targets[0].first, curC = targets[0].second;\n    \n    for (int i = 1; i < M; i++) {\n        int tR = targets[i].first, tC = targets[i].second;\n        \n        int moveCost = abs(tR - curR) + abs(tC - curC);\n        int bestCost = moveCost;\n        int bestStrategy = 0;\n        \n        // Edge target strategies (1-4)\n        if (tR == 0 && curR > 0) {\n            int cost = abs(tC - curC) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 1; }\n        }\n        if (tR == N - 1 && curR < N - 1) {\n            int cost = abs(tC - curC) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 2; }\n        }\n        if (tC == 0 && curC > 0) {\n            int cost = abs(tR - curR) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 3; }\n        }\n        if (tC == N - 1 && curC < N - 1) {\n            int cost = abs(tR - curR) + 1;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 4; }\n        }\n        \n        // Slide-first strategies (5-8)\n        if (curR > 0) {\n            int cost = 1 + tR + abs(tC - curC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 5; }\n        }\n        if (curR < N - 1) {\n            int cost = 1 + (N - 1 - tR) + abs(tC - curC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 6; }\n        }\n        if (curC > 0) {\n            int cost = 1 + tC + abs(tR - curR);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 7; }\n        }\n        if (curC < N - 1) {\n            int cost = 1 + (N - 1 - tC) + abs(tR - curR);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 8; }\n        }\n        \n        // Double-slide to corners (9-12)\n        if (curR > 0 && curC > 0) { // to (0,0)\n            int cost = 2 + tR + tC;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 9; }\n        }\n        if (curR > 0 && curC < N - 1) { // to (0, N-1)\n            int cost = 2 + tR + (N - 1 - tC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 10; }\n        }\n        if (curR < N - 1 && curC > 0) { // to (N-1, 0)\n            int cost = 2 + (N - 1 - tR) + tC;\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 11; }\n        }\n        if (curR < N - 1 && curC < N - 1) { // to (N-1, N-1)\n            int cost = 2 + (N - 1 - tR) + (N - 1 - tC);\n            if (cost < bestCost) { bestCost = cost; bestStrategy = 12; }\n        }\n        \n        switch (bestStrategy) {\n            case 0:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                break;\n            case 1: case 2: case 3: case 4:\n                if (bestStrategy <= 2) {\n                    while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                    while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                    actions.push_back(bestStrategy == 1 ? \"S U\" : \"S D\");\n                    curR = (bestStrategy == 1) ? 0 : N - 1;\n                } else {\n                    while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                    while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                    actions.push_back(bestStrategy == 3 ? \"S L\" : \"S R\");\n                    curC = (bestStrategy == 3) ? 0 : N - 1;\n                }\n                break;\n            case 5: actions.push_back(\"S U\"); curR = 0; goto moveToTarget;\n            case 6: actions.push_back(\"S D\"); curR = N - 1; goto moveToTarget;\n            case 7: actions.push_back(\"S L\"); curC = 0; goto moveToTarget;\n            case 8: actions.push_back(\"S R\"); curC = N - 1; goto moveToTarget;\n            case 9: actions.push_back(\"S U\"); curR = 0; actions.push_back(\"S L\"); curC = 0; goto moveToTarget;\n            case 10: actions.push_back(\"S U\"); curR = 0; actions.push_back(\"S R\"); curC = N - 1; goto moveToTarget;\n            case 11: actions.push_back(\"S D\"); curR = N - 1; actions.push_back(\"S L\"); curC = 0; goto moveToTarget;\n            case 12: actions.push_back(\"S D\"); curR = N - 1; actions.push_back(\"S R\"); curC = N - 1; goto moveToTarget;\n            moveToTarget:\n                while (curR < tR) { actions.push_back(\"M D\"); curR++; }\n                while (curR > tR) { actions.push_back(\"M U\"); curR--; }\n                while (curC < tC) { actions.push_back(\"M R\"); curC++; }\n                while (curC > tC) { actions.push_back(\"M L\"); curC--; }\n                break;\n        }\n    }\n    \n    for (const string& action : actions) {\n        cout << action << \"\\n\";\n    }\n    \n    return 0;\n}"}}}