{"model_name":"gpt-oss-120b","codes":{"1":{"ahc001":"#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    if (!(cin >> n)) return 0;\n    vector<long long> x(n), y(n), r(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> x[i] >> y[i] >> r[i];\n    }\n\n    // Output the unit square that contains the required half\u2011integer point.\n    for (int i = 0; i < n; ++i) {\n        // a_i = x_i, b_i = y_i, c_i = x_i+1, d_i = y_i+1\n        cout << x[i] << ' ' << y[i] << ' ' << (x[i] + 1) << ' ' << (y[i] + 1) << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj;\n    if (!(cin >> si >> sj)) return 0;  // no input\n    \n    // read tile ids (unused)\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j) {\n            int t; cin >> t;\n        }\n    \n    // read point values (unused)\n    for (int i = 0; i < 50; ++i)\n        for (int j = 0; j < 50; ++j) {\n            int p; cin >> p;\n        }\n    \n    // output an empty path\n    cout << \"\\n\";\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int Q = 1000;\n    for (int q = 0; q < Q; ++q) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) break;  // safety\n        string path;\n        if (ti > si) path.append(ti - si, 'D');\n        else if (ti < si) path.append(si - ti, 'U');\n        if (tj > sj) path.append(tj - sj, 'R');\n        else if (tj < sj) path.append(sj - tj, 'L');\n\n        cout << path << '\\n' << flush;   // flush after each answer\n        long long dummy;                 // the noisy length from the judge\n        cin >> dummy;                    // read and ignore\n    }\n    return 0;\n}","ahc004":"#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    if (!(cin >> N >> M)) return 0;\n    string s;\n    for (int i = 0; i < M; ++i) cin >> s;   // discard\n\n    // random generator for letters A..H\n    std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> dist(0, 7);   // 0..7 -> A..H\n\n    for (int i = 0; i < N; ++i) {\n        string row;\n        row.reserve(N);\n        for (int j = 0; j < N; ++j) {\n            char c = 'A' + dist(rng);\n            row.push_back(c);\n        }\n        cout << row << \"\\n\";\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, si, sj;\n    if (!(cin >> N >> si >> sj)) return 0;\n    string line;\n    for (int i = 0; i < N; ++i) {\n        cin >> line;               // read and ignore the map line\n    }\n    // Output an empty route (just a newline)\n    cout << \"\\n\";\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K, R;\n    if (!(cin >> N >> M >> K >> R)) return 0;\n\n    // read required skill vectors (they are not used)\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) cin >> d[i][j];\n\n    // build dependency graph\n    vector<vector<int>> out(N);\n    vector<int> indeg(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u; --v;\n        out[u].push_back(v);\n        ++indeg[v];\n    }\n\n    // state of tasks\n    vector<int> task_state(N, -1);          // -1 not started, 0 started, 1 finished\n    // which task a member is currently doing (-1 = idle)\n    vector<int> member_task(M, -1);\n\n    // queue of ready tasks\n    deque<int> ready;\n    for (int i = 0; i < N; ++i)\n        if (indeg[i] == 0) ready.push_back(i);\n\n    // -------------------------------------------------------------\n    // main daily loop\n    while (true) {\n        // ------- assign tasks that start today --------------------\n        vector<pair<int,int>> assign;   // (member, task)\n        for (int j = 0; j < M; ++j) {\n            if (member_task[j] == -1 && !ready.empty()) {\n                int t = ready.front(); ready.pop_front();\n                member_task[j] = t;\n                task_state[t] = 0;\n                assign.emplace_back(j, t);\n            }\n        }\n\n        // output\n        cout << assign.size();\n        for (auto [mem, tas] : assign) {\n            cout << ' ' << (mem + 1) << ' ' << (tas + 1);\n        }\n        cout << '\\n' << flush;\n\n        // ------- read judge answer (who finished today) ----------\n        string line;\n        if (!getline(cin, line)) break;       // should not happen\n        while (line.size() && (line.back() == '\\r' || line.back() == '\\n')) line.pop_back();\n        if (line.empty()) {                    // sometimes the previous >> leaves a newline\n            if (!getline(cin, line)) break;\n            while (line.size() && (line.back() == '\\r' || line.back() == '\\n')) line.pop_back();\n        }\n\n        if (line == \"-1\") break;               // all done or day limit exceeded\n\n        // parse the line\n        stringstream ss(line);\n        int cnt;\n        ss >> cnt;\n        vector<int> finished_members;\n        for (int i = 0; i < cnt; ++i) {\n            int f; ss >> f;\n            finished_members.push_back(f - 1); // to 0\u2011based\n        }\n\n        // process completions\n        for (int mem : finished_members) {\n            int t = member_task[mem];\n            if (t == -1) continue;            // should not happen\n            member_task[mem] = -1;\n            task_state[t] = 1;                 // finished\n            for (int nxt : out[t]) {\n                if (--indeg[nxt] == 0 && task_state[nxt] == -1) {\n                    ready.push_back(nxt);\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    struct Order { int a,b,c,d; };\n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; ++i) {\n        cin >> orders[i].a >> orders[i].b >> orders[i].c >> orders[i].d;\n    }\n\n    const int M = 50;                     // number of orders to take\n    vector<int> chosen;\n    chosen.reserve(M);\n    for (int i = 0; i < M; ++i) chosen.push_back(i + 1); // indices 1..50\n\n    // Build the route\n    vector<pair<int,int>> route;\n    route.emplace_back(400, 400);         // start at office\n    for (int idx : chosen) {\n        const Order &o = orders[idx-1];\n        route.emplace_back(o.a, o.b);     // restaurant\n        route.emplace_back(o.c, o.d);     // destination\n    }\n    route.emplace_back(400, 400);         // return to office\n\n    // Output\n    cout << M;\n    for (int idx : chosen) cout << ' ' << idx;\n    cout << '\\n';\n\n    cout << route.size();\n    for (auto [x,y] : route) cout << ' ' << x << ' ' << y;\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 400;\n    const int M = 1995;\n    // read vertex coordinates (unused later)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        if(!(cin >> x >> y)) return 0;\n    }\n    // read edges\n    vector<int> u(M), v(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> u[i] >> v[i];\n    }\n    \n    DSU dsu(N);\n    for (int i = 0; i < M; ++i) {\n        long long li;\n        cin >> li;                 // true length, not needed for decision\n        if (dsu.find(u[i]) != dsu.find(v[i])) {\n            cout << \"1\\n\";\n            dsu.unite(u[i], v[i]);\n        } else {\n            cout << \"0\\n\";\n        }\n        cout.flush();             // mandatory after each answer\n    }\n    return 0;\n}","ahc008":"#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    if (!(cin >> N)) return 0;\n    struct Pet { int x, y, t; };\n    vector<Pet> pets(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> pets[i].x >> pets[i].y >> pets[i].t;\n    }\n    int M;\n    cin >> M;\n    vector<pair<int,int>> humans(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> humans[i].first >> humans[i].second;\n    }\n\n    const string action(M, '.');           // M dots\n\n    for (int turn = 0; turn < 300; ++turn) {\n        cout << action << \"\\n\";\n        cout.flush();                      // required after each turn\n\n        // read pet moves (N strings)\n        for (int i = 0; i < N; ++i) {\n            string mv;\n            cin >> mv;                      // we simply discard it\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Prev {\n    int pi, pj;\n    char move;   // move taken from predecessor to this cell\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int si, sj, ti, tj;\n    double p;\n    if(!(cin >> si >> sj >> ti >> tj >> p)) return 0;\n\n    const int N = 20;\n    vector<string> h(N);          // 20 strings of length 19\n    for (int i = 0; i < N; ++i) cin >> h[i];\n    vector<string> v(N - 1);      // 19 strings of length 20\n    for (int i = 0; i < N - 1; ++i) cin >> v[i];\n\n    // BFS\n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    vector<vector<Prev>> pre(N, vector<Prev>(N, {-1,-1,'?'}));\n    queue<pair<int,int>> q;\n    dist[si][sj] = 0;\n    q.emplace(si, sj);\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char dch[4] = {'U','D','L','R'};\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        if (i == ti && j == tj) break;\n        // Up\n        if (i > 0 && v[i-1][j] == '0' && dist[i-1][j] == -1) {\n            dist[i-1][j] = dist[i][j] + 1;\n            pre[i-1][j] = {i, j, 'U'};\n            q.emplace(i-1, j);\n        }\n        // Down\n        if (i + 1 < N && v[i][j] == '0' && dist[i+1][j] == -1) {\n            dist[i+1][j] = dist[i][j] + 1;\n            pre[i+1][j] = {i, j, 'D'};\n            q.emplace(i+1, j);\n        }\n        // Left\n        if (j > 0 && h[i][j-1] == '0' && dist[i][j-1] == -1) {\n            dist[i][j-1] = dist[i][j] + 1;\n            pre[i][j-1] = {i, j, 'L'};\n            q.emplace(i, j-1);\n        }\n        // Right\n        if (j + 1 < N && h[i][j] == '0' && dist[i][j+1] == -1) {\n            dist[i][j+1] = dist[i][j] + 1;\n            pre[i][j+1] = {i, j, 'R'};\n            q.emplace(i, j+1);\n        }\n    }\n\n    // Reconstruct path\n    string ans;\n    int ci = ti, cj = tj;\n    while (!(ci == si && cj == sj)) {\n        Prev pr = pre[ci][cj];\n        ans.push_back(pr.move);\n        ci = pr.pi;\n        cj = pr.pj;\n    }\n    reverse(ans.begin(), ans.end());\n\n    // Safety: if for any reason path is empty (should not happen), output a dummy move\n    if (ans.empty()) ans = \"U\";\n\n    cout << ans << \"\\n\";\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    // Read 30 lines of input (the tile types)\n    string line;\n    for (int i = 0; i < 30; ++i) {\n        if (!(cin >> line)) return 0; // safety\n    }\n    // Output 900 zeros (no rotation for any tile)\n    cout << string(30 * 30, '0') << '\\n';\n    return 0;\n}","ahc011":"#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    long long T;\n    if (!(cin >> N >> T)) return 0;\n    string row;\n    for (int i = 0; i < N; ++i) {\n        cin >> row;               // each row of length N\n    }\n    // Output an empty sequence of moves.\n    cout << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    long long N;\n    int K;\n    if (!(cin >> N >> K)) return 0;\n    // read a_1 .. a_10\n    for (int i = 0; i < 10; ++i) {\n        long long a;\n        cin >> a;\n    }\n    // read strawberries positions\n    for (long long i = 0; i < N; ++i) {\n        long long x, y;\n        cin >> x >> y;\n    }\n    // output zero cuts\n    cout << 0 << \"\\n\";\n    return 0;\n}","ahc014":"#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    if (!(cin >> N >> M)) return 0;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y; // just consume the input\n    }\n    cout << 0 << \"\\n\";   // no operations\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // 1. read the 100 flavours (ignored)\n    for (int i = 0; i < 100; ++i) {\n        int f;\n        if (!(cin >> f)) return 0; // safety\n    }\n\n    // 2. for each of the 100 steps read p_t and output a direction\n    for (int t = 0; t < 100; ++t) {\n        int p;\n        cin >> p;                 // position of the newly placed candy\n        cout << 'L' << '\\n';      // tilt left (any direction is acceptable)\n        cout.flush();            // not strictly necessary in offline mode\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n\n    const int N = 20;                         // fixed vertex count\n    const int L = N * (N - 1) / 2;            // length of each graph string\n\n    cout << N << \"\\n\";\n    for (int k = 0; k < M; ++k) {\n        string s(k, '1');                     // k ones\n        s.append(L - k, '0');                 // remaining zeros\n        cout << s << \"\\n\";\n    }\n    cout.flush();\n\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;                             // length L\n        int cnt = 0;\n        for (char c : H) if (c == '1') ++cnt;\n\n        int t = min(cnt, M - 1);               // nearest index (0 \u2026 M\u20111)\n        cout << t << \"\\n\";\n        cout.flush();\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n\n    // read and ignore edges\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n    }\n\n    // read and ignore coordinates\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    vector<int> day(M);\n    for (int i = 0; i < M; ++i) {\n        day[i] = (i % D) + 1;          // 1\u2011based day number\n    }\n\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << day[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int D;\n    if (!(cin >> D)) return 0;\n\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) cin >> f[i][z];\n        for (int z = 0; z < D; ++z) cin >> r[i][z];\n    }\n\n    const long long SZ = 1LL * D * D * D;\n    vector<int> out1(SZ, 0), out2(SZ, 0);\n    long long curId = 0;\n\n    auto idx = [&](int x, int y, int z) -> long long {\n        return 1LL * x * D * D + 1LL * y * D + z;\n    };\n\n    // object 1\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                if (f[0][z][x] == '1' && r[0][z][y] == '1') {\n                    ++curId;\n                    out1[idx(x, y, z)] = (int)curId;\n                }\n            }\n        }\n    }\n    // object 2\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                if (f[1][z][x] == '1' && r[1][z][y] == '1') {\n                    ++curId;\n                    out2[idx(x, y, z)] = (int)curId;\n                }\n            }\n        }\n    }\n\n    cout << curId << \"\\n\";\n    for (size_t i = 0; i < out1.size(); ++i) {\n        if (i) cout << ' ';\n        cout << out1[i];\n    }\n    cout << \"\\n\";\n    for (size_t i = 0; i < out2.size(); ++i) {\n        if (i) cout << ' ';\n        cout << out2[i];\n    }\n    cout << \"\\n\";\n    return 0;\n}","ahc020":"#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, K;\n    if(!(cin >> N >> M >> K)) return 0;\n    \n    // read vertex coordinates\n    for (int i = 0; i < N; ++i) {\n        long long x, y;\n        cin >> x >> y;\n    }\n    \n    // read edges (ignore their content, we will turn all on)\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        long long w;\n        cin >> u >> v >> w;\n    }\n    \n    // read residents (ignore)\n    for (int i = 0; i < K; ++i) {\n        long long a, b;\n        cin >> a >> b;\n    }\n    \n    // output P_i = 5000 for all vertices\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << 5000;\n    }\n    cout << \"\\n\";\n    \n    // output B_j = 1 for all edges\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << 1;\n    }\n    cout << \"\\n\";\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    // The pyramid has N = 30, total balls = 465.\n    // Read and discard all numbers.\n    const int N = 30;\n    const int total = N * (N + 1) / 2; // 465\n    for (int i = 0; i < total; ++i) {\n        int x;\n        if (!(cin >> x)) return 0; // safety\n    }\n    \n    // No operation is performed.\n    cout << 0 << \"\\n\";\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int i, j;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int D = 9;\n    int N;\n    if(!(cin >> D >> N)) return 0;          // D is always 9 in all tests\n    vector<vector<int>> blocked(D, vector<int>(D, 0));\n    // entrance\n    const int ei = 0, ej = (D - 1) / 2;\n    blocked[ei][ej] = 1;                    // cannot be used for storage\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        blocked[ri][rj] = 1;\n    }\n\n    auto inside = [&](int x, int y) {\n        return 0 <= x && x < D && 0 <= y && y < D;\n    };\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n\n    // give each cell an id\n    auto id = [&](int i, int j) { return i * D + j; };\n    const int V = D * D;\n    vector<int> dist(V, -1);\n    vector<int> parent(V, -1);\n    vector<vector<int>> adj(V);\n    // BFS from entrance to compute distances and adjacency\n    queue<int> q;\n    int start = id(ei, ej);\n    dist[start] = 0;\n    q.push(start);\n    while (!q.empty()) {\n        int v = q.front(); q.pop();\n        int ci = v / D, cj = v % D;\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = ci + di[dir], nj = cj + dj[dir];\n            if (!inside(ni, nj)) continue;\n            if (blocked[ni][nj]) continue;\n            int nv = id(ni, nj);\n            adj[v].push_back(nv);\n            adj[nv].push_back(v);\n            if (dist[nv] == -1) {\n                dist[nv] = dist[v] + 1;\n                parent[nv] = v;\n                q.push(nv);\n            }\n        }\n    }\n\n    // list of all usable cells (not blocked, not entrance)\n    vector<int> cells;\n    for (int i = 0; i < D; ++i)\n        for (int j = 0; j < D; ++j)\n            if (!blocked[i][j] && !(i == ei && j == ej))\n                cells.push_back(id(i, j));\n\n    const int M = (int)cells.size();      // number of containers\n\n    // degree = number of neighbours that are still empty (initially all free neighbours)\n    vector<int> deg(V, 0);\n    for (int v : cells) {\n        int cnt = 0;\n        for (int nb : adj[v]) {\n            int ni = nb / D, nj = nb % D;\n            if (!blocked[ni][nj]) ++cnt;\n        }\n        deg[v] = cnt;\n    }\n\n    // leaf set: empty cells with deg == 1 (and not entrance)\n    unordered_set<int> leafSet;\n    for (int v : cells) {\n        if (deg[v] == 1) leafSet.insert(v);\n    }\n\n    // container number stored in each cell, -1 = empty\n    vector<int> container(V, -1);\n    // ----- storing phase -----\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;               // container number received now\n\n        // pick any leaf (the set is tiny, just take the first)\n        int chosen = *leafSet.begin();\n        leafSet.erase(chosen);\n\n        // output coordinates\n        cout << (chosen / D) << ' ' << (chosen % D) << '\\n';\n        cout.flush();\n\n        container[chosen] = t;          // remember what is placed here\n\n        // update neighbours: this cell becomes occupied -> disappear from empty graph\n        for (int nb : adj[chosen]) {\n            if (blocked[nb / D][nb % D]) continue;          // obstacle\n            if (container[nb] != -1) continue;              // already occupied\n            // nb is still empty\n            deg[nb]--;\n            if (deg[nb] == 1) leafSet.insert(nb);\n        }\n    }\n\n    // ----- taking\u2011out phase -----\n    // bucket cells by distance\n    int maxDist = 0;\n    for (int v : cells) maxDist = max(maxDist, dist[v]);\n    vector<vector<int>> bucket(maxDist + 1);\n    for (int v : cells) {\n        int d = dist[v];\n        bucket[d].push_back(v);\n    }\n    // output in increasing distance, inside each bucket sorted by container number\n    for (int d = 1; d <= maxDist; ++d) {\n        auto &vec = bucket[d];\n        sort(vec.begin(), vec.end(),\n             [&](int a, int b) { return container[a] < container[b]; });\n        for (int v : vec) {\n            cout << (v / D) << ' ' << (v % D) << '\\n';\n        }\n    }\n    cout.flush();\n    return 0;\n}","ahc024":"#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    if (!(cin >> n >> m)) return 0;\n    vector<vector<int>> a(n, vector<int>(n));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (j) cout << ' ';\n            cout << a[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n    vector<long long> w(N);\n    for (int i = 0; i < N; ++i) cin >> w[i];   // offline version gives the weights\n    \n    // indices sorted by decreasing weight\n    vector<int> ids(N);\n    iota(ids.begin(), ids.end(), 0);\n    sort(ids.begin(), ids.end(), [&](int a, int b){ return w[a] > w[b]; });\n    \n    vector<long long> tot(D, 0);\n    vector<int> ans(N, -1);\n    \n    for (int id : ids) {\n        // find bin with minimal total weight\n        int best = 0;\n        for (int b = 1; b < D; ++b) {\n            if (tot[b] < tot[best]) best = b;\n        }\n        ans[id] = best;\n        tot[best] += w[id];\n    }\n    \n    // output division\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << ans[i];\n    }\n    cout << '\\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    int n, m;\n    if (!(cin >> n >> m)) return 0;\n    const int per = n / m;                // = 20\n    vector<vector<int>> st(m);            // bottom -> top\n    for (int i = 0; i < m; ++i) {\n        st[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x; cin >> x;\n            st[i].push_back(x);\n        }\n    }\n\n    vector<pair<int,int>> ops;\n    ops.reserve(5000);\n\n    for (int target = 1; target <= n; ++target) {\n        while (true) {\n            // locate stack and position of target\n            int s = -1, pos = -1;\n            for (int i = 0; i < m; ++i) {\n                for (int j = 0; j < (int)st[i].size(); ++j) {\n                    if (st[i][j] == target) {\n                        s = i; pos = j;\n                        break;\n                    }\n                }\n                if (s != -1) break;\n            }\n            // target must exist\n            int topIdx = (int)st[s].size() - 1;\n            if (pos == topIdx) {                 // already on top\n                ops.emplace_back(target, 0);     // pop\n                st[s].pop_back();\n                break;                           // go to next target\n            } else {\n                // move the current top box away\n                int u = st[s].back();\n                int t = (s + 1) % m;\n                if (t == s) t = (t + 1) % m;     // just in case\n                ops.emplace_back(u, t + 1);      // type 1\n                st[s].pop_back();\n                st[t].push_back(u);\n            }\n        }\n    }\n\n    // output\n    for (auto [v, i] : ops) {\n        cout << v << ' ' << i << '\\n';\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n\n    vector<string> h(N - 1);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    vector<string> v(N);\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    // d is read but not used\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            long long tmp;\n            cin >> tmp;\n        }\n    }\n\n    const int di[4] = {0, 1, 0, -1};\n    const int dj[4] = {1, 0, -1, 0};\n    const char moveChar[4] = {'R', 'D', 'L', 'U'};\n    const char backChar[4] = {'L', 'U', 'R', 'D'};\n\n    vector<vector<char>> visited(N, vector<char>(N, 0));\n    string answer;\n\n    function<void(int,int)> dfs = [&](int i, int j) {\n        visited[i][j] = 1;\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + di[dir];\n            int nj = j + dj[dir];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (visited[ni][nj]) continue;\n            // check wall\n            bool blocked = false;\n            if (dir == 0) { // right\n                blocked = (v[i][j] == '1');\n            } else if (dir == 2) { // left\n                blocked = (v[i][j-1] == '1');\n            } else if (dir == 1) { // down\n                blocked = (h[i][j] == '1');\n            } else { // up\n                blocked = (h[i-1][j] == '1');\n            }\n            if (blocked) continue;\n\n            answer.push_back(moveChar[dir]);\n            dfs(ni, nj);\n            answer.push_back(backChar[dir]);\n        }\n    };\n\n    dfs(0, 0);\n    cout << answer << '\\n';\n    return 0;\n}","ahc028":"#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    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    // store first occurrence of each letter\n    pair<int,int> pos[26];\n    for (int k = 0; k < 26; ++k) pos[k] = {-1,-1};\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int idx = board[i][j] - 'A';\n            if (pos[idx].first == -1) pos[idx] = {i, j};\n        }\n    }\n\n    vector<string> words(M);\n    for (int k = 0; k < M; ++k) cin >> words[k];\n\n    // generate answer\n    vector<pair<int,int>> answer;\n    answer.reserve(5 * M + 10);\n    int cur_i = si, cur_j = sj;          // current finger position (unused later)\n\n    for (const string& w : words) {\n        for (char ch : w) {\n            auto [ti, tj] = pos[ch - 'A'];   // a cell containing ch\n            answer.emplace_back(ti, tj);\n            cur_i = ti; cur_j = tj;\n        }\n    }\n\n    // output\n    for (auto [i, j] : answer) {\n        cout << i << ' ' << j << '\\n';\n    }\n    return 0;\n}","ahc030":"#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    double eps;\n    if (!(cin >> N >> M >> eps)) return 0;\n\n    // ---- read shapes (ignored later) ----\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        for (int t = 0; t < d; ++t) {\n            int a, b;\n            cin >> a >> b;\n        }\n    }\n\n    // ---- read positions of each field (unused) ----\n    for (int k = 0; k < M; ++k) {\n        int di, dj;\n        cin >> di >> dj;\n        (void)di; (void)dj;\n    }\n\n    // ---- read the whole v matrix ----\n    vector<vector<int>> v(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> v[i][j];\n\n    // ---- discard the remaining numbers (up to 2*N^2) ----\n    // The exact amount is not needed; just read until EOF.\n    double dummy;\n    while (cin >> dummy) { /* discard */ }\n\n    // ---- collect cells with v > 0 ----\n    vector<pair<int,int>> ans;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (v[i][j] > 0) ans.emplace_back(i, j);\n\n    // ---- output in the required format ----\n    cout << \"a \" << ans.size();\n    for (auto [i, j] : ans) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << \"\\n\";\n    cout.flush();\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    if (!(cin >> W >> D >> N)) return 0;\n    // read and ignore the desired areas\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            long long a;\n            cin >> a;\n            (void)a;\n        }\n    }\n\n    // output the simple vertical strips\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            int i0 = k;\n            int j0 = 0;\n            int i1 = k + 1;\n            int j1 = W;\n            cout << i0 << ' ' << j0 << ' ' << i1 << ' ' << j1 << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const long long MOD = 998244353LL;\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;\n\n    // read board a_{i,j}\n    vector<vector<long long>> a(N, vector<long long>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> a[i][j];\n\n    // read stamps s_{m,i,j}\n    vector<array<array<long long,3>,3>> s(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 >> s[m][i][j];\n\n    // No operation is performed\n    cout << 0 << '\\n';\n    return 0;\n}","ahc033":"#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    if (!(cin >> N)) return 0;\n    // read and ignore the matrix A\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            int x; cin >> x;\n            (void)x;\n        }\n    // output one '.' for each crane\n    for (int i = 0; i < N; ++i) {\n        cout << \".\\n\";\n    }\n    return 0;\n}","ahc034":"#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    if (!(cin >> N)) return 0;\n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> h[i][j];\n    auto orig = h;                     // keep original heights\n    \n    int cur_i = 0, cur_j = 0;           // current truck position\n    long long load = 0;                // amount of soil on the truck\n    \n    auto move_to = [&](int ni, int nj) {\n        while (cur_i < ni) { cout << \"D\\n\"; ++cur_i; }\n        while (cur_i > ni) { cout << \"U\\n\"; --cur_i; }\n        while (cur_j < nj) { cout << \"R\\n\"; ++cur_j; }\n        while (cur_j > nj) { cout << \"L\\n\"; --cur_j; }\n    };\n    \n    // -----------------------------------------------------------------\n    // First tour: collect soil from positive cells\n    for (int i = 0; i < N; ++i) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; ++j) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    cout << \"+\" << h[i][j] << \"\\n\";\n                    load += h[i][j];\n                    h[i][j] = 0;\n                }\n            }\n        } else {\n            for (int j = N - 1; j >= 0; --j) {\n                move_to(i, j);\n                if (h[i][j] > 0) {\n                    cout << \"+\" << h[i][j] << \"\\n\";\n                    load += h[i][j];\n                    h[i][j] = 0;\n                }\n            }\n        }\n    }\n    \n    // -----------------------------------------------------------------\n    // Second tour: give soil to negative cells\n    for (int i = 0; i < N; ++i) {\n        if (i % 2 == 0) {\n            for (int j = 0; j < N; ++j) {\n                move_to(i, j);\n                if (orig[i][j] < 0) {\n                    int d = -orig[i][j];\n                    cout << \"-\" << d << \"\\n\";\n                    load -= d;\n                }\n            }\n        } else {\n            for (int j = N - 1; j >= 0; --j) {\n                move_to(i, j);\n                if (orig[i][j] < 0) {\n                    int d = -orig[i][j];\n                    cout << \"-\" << d << \"\\n\";\n                    load -= d;\n                }\n            }\n        }\n    }\n    \n    // (load must be zero now)\n    return 0;\n}","ahc035":"#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, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    const int seedCnt = 2 * N * (N - 1);\n\n    // read initial seed vectors (ignore)\n    for (int i = 0; i < seedCnt; ++i) {\n        for (int j = 0; j < M; ++j) {\n            int x; cin >> x;\n        }\n    }\n\n    for (int turn = 0; turn < T; ++turn) {\n        // output a fixed placement: seeds 0..N*N-1 in row\u2011major order\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (j) cout << ' ';\n                cout << i * N + j;\n            }\n            cout << '\\n';\n        }\n        cout.flush();                 // required after each turn\n\n        // read the newly generated seeds (ignore)\n        for (int i = 0; i < seedCnt; ++i) {\n            for (int j = 0; j < M; ++j) {\n                int x; cin >> x;\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#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, V;\n    if (!(cin >> N >> M >> V)) return 0;\n    string line;\n    // read initial grid\n    for (int i = 0; i < N; ++i) cin >> line;\n    // read target grid\n    for (int i = 0; i < N; ++i) cin >> line;\n\n    // ----- construct a trivial robot arm -----\n    // V' = 1 (only the root)\n    cout << 1 << \"\\n\";\n    // no parent/length lines because there are no other vertices\n    // root position (any cell inside the grid, choose (0,0))\n    cout << 0 << \" \" << 0 << \"\\n\";\n\n    // No turns are printed (empty sequence)\n    // program ends here\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\n// combine x and y into a 64\u2011bit key; 2^17 = 131072 > 1e5\nstatic inline uint64_t key(int x, int y) {\n    return (static_cast<uint64_t>(x) << 17) | static_cast<uint64_t>(y);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    const int total = 2 * N;\n    vector<pair<int,int>> pts(total);\n    unordered_set<uint64_t> S;\n    S.reserve(total * 2);\n    for (int i = 0; i < total; ++i) {\n        int x, y;\n        cin >> x >> y;\n        pts[i] = {x, y};\n        S.insert(key(x, y));\n    }\n\n    // search a 1x1 empty cell\n    int xs = -1, ys = -1;\n    const int MAXC = 100000;\n    for (int x = 0; x < MAXC && xs==-1; x += 2) {\n        for (int y = 0; y < MAXC && xs==-1; y += 2) {\n            bool ok = true;\n            // fast test: check hash set for the 4 possible points\n            // but a fish could be inside without being on a corner,\n            // so we must scan all points (still cheap).\n            for (const auto &p : pts) {\n                if (p.first >= x && p.first <= x+1 &&\n                    p.second >= y && p.second <= y+1) {\n                    ok = false; break;\n                }\n            }\n            if (ok) {\n                xs = x; ys = y;\n            }\n        }\n    }\n\n    // fallback (should never happen) : use whole bounding box\n    if (xs == -1) {\n        xs = 0; ys = 0;\n    }\n\n    // output rectangle (clockwise)\n    cout << 4 << \"\\n\";\n    cout << xs << ' ' << ys << \"\\n\";\n    cout << xs+1 << ' ' << ys << \"\\n\";\n    cout << xs+1 << ' ' << ys+1 << \"\\n\";\n    cout << xs << ' ' << ys+1 << \"\\n\";\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, T;\n    long long sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n    // read the observed widths and heights, but we do not need them\n    for (int i = 0; i < N; ++i) {\n        long long w, h;\n        cin >> w >> h;\n    }\n\n    for (int turn = 0; turn < T; ++turn) {\n        // place no rectangle\n        cout << 0 << '\\n';\n        cout.flush();                     // required flush\n\n        // read the judge's response (measured box size)\n        long long Wp, Hp;\n        cin >> Wp >> Hp;\n        // values are ignored\n        (void)Wp; (void)Hp;\n    }\n    return 0;\n}","ahc041":"#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, H;\n    if (!(cin >> N >> M >> H)) return 0;\n\n    // read beauty values\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n\n    // read edges (ignore)\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n    }\n\n    // read coordinates (ignore)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // output -1 for every vertex (each vertex is its own root)\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << -1;\n    }\n    cout << '\\n';\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 20;\n    vector<string> g(N);\n    for (int i = 0; i < N; ++i) cin >> g[i];\n\n    struct Op { char d; int p; };\n    vector<Op> ans;\n\n    // collect all Oni positions\n    vector<pair<int,int>> oni;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (g[i][j] == 'x') oni.emplace_back(i, j);\n\n    for (auto [i, j] : oni) {\n        // check freedom in four directions\n        bool freeU = true, freeD = true, freeL = true, freeR = true;\n        for (int ii = 0; ii < i; ++ii) if (g[ii][j] == 'o') freeU = false;\n        for (int ii = i+1; ii < N; ++ii) if (g[ii][j] == 'o') freeD = false;\n        for (int jj = 0; jj < j; ++jj) if (g[i][jj] == 'o') freeL = false;\n        for (int jj = j+1; jj < N; ++jj) if (g[i][jj] == 'o') freeR = false;\n\n        // distances to the corresponding edge\n        int du = i + 1;\n        int dd = N - i;\n        int dl = j + 1;\n        int dr = N - j;\n\n        // choose the free direction with minimal distance\n        int bestDist = INT_MAX;\n        char dir = '?';\n        if (freeU && du < bestDist) { bestDist = du; dir = 'U'; }\n        if (freeD && dd < bestDist) { bestDist = dd; dir = 'D'; }\n        if (freeL && dl < bestDist) { bestDist = dl; dir = 'L'; }\n        if (freeR && dr < bestDist) { bestDist = dr; dir = 'R'; }\n\n        // apply the two opposite shifts\n        if (dir == 'U') {\n            for (int k = 0; k < du; ++k) ans.push_back({'U', j});\n            for (int k = 0; k < du; ++k) ans.push_back({'D', j});\n        } else if (dir == 'D') {\n            for (int k = 0; k < dd; ++k) ans.push_back({'D', j});\n            for (int k = 0; k < dd; ++k) ans.push_back({'U', j});\n        } else if (dir == 'L') {\n            for (int k = 0; k < dl; ++k) ans.push_back({'L', i});\n            for (int k = 0; k < dl; ++k) ans.push_back({'R', i});\n        } else if (dir == 'R') {\n            for (int k = 0; k < dr; ++k) ans.push_back({'R', i});\n            for (int k = 0; k < dr; ++k) ans.push_back({'L', i});\n        }\n        // after this Oni is considered removed; we do not modify g\n    }\n\n    for (auto [c, p] : ans) {\n        cout << c << ' ' << p << '\\n';\n    }\n    return 0;\n}","ahc044":"#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    long long L;\n    if (!(cin >> N >> L)) return 0;\n    vector<long long> T(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];   // not used\n    \n    for (int i = 0; i < N; ++i) {\n        int nxt = (i + 1) % N;\n        cout << nxt << ' ' << nxt << \"\\n\";\n    }\n    return 0;\n}","ahc045":"#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, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    // read rectangle data, but we do not need it\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        (void)lx; (void)rx; (void)ly; (void)ry;\n    }\n\n    cout << \"!\\n\";\n\n    int cur = 0;                     // next unused city id\n    for (int k = 0; k < M; ++k) {\n        int sz = G[k];\n        vector<int> group;\n        group.reserve(sz);\n        for (int i = 0; i < sz; ++i) {\n            group.push_back(cur++);\n        }\n\n        // output the list of cities of this group\n        for (int i = 0; i < sz; ++i) {\n            if (i) cout << ' ';\n            cout << group[i];\n        }\n        cout << '\\n';\n\n        // output a trivial spanning tree (a path)\n        for (int i = 1; i < sz; ++i) {\n            cout << group[i-1] << ' ' << group[i] << '\\n';\n        }\n        // for sz == 1 nothing is printed, which is correct\n    }\n    return 0;\n}","ahc046":"#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    if (!(cin >> N >> M)) return 0;\n    vector<pair<int,int>> p(M);\n    for (int i = 0; i < M; ++i) cin >> p[i].first >> p[i].second;\n\n    int cur_i = p[0].first;\n    int cur_j = p[0].second;\n\n    // store output lines to print at the end (optional)\n    vector<string> out;\n\n    for (int t = 1; t < M; ++t) {\n        int ti = p[t].first;\n        int tj = p[t].second;\n\n        // vertical moves\n        while (cur_i < ti) {\n            out.emplace_back(\"M D\");\n            ++cur_i;\n        }\n        while (cur_i > ti) {\n            out.emplace_back(\"M U\");\n            --cur_i;\n        }\n        // horizontal moves\n        while (cur_j < tj) {\n            out.emplace_back(\"M R\");\n            ++cur_j;\n        }\n        while (cur_j > tj) {\n            out.emplace_back(\"M L\");\n            --cur_j;\n        }\n    }\n\n    for (const auto& s : out) cout << s << '\\n';\n    return 0;\n}"},"2":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int idx;\n    int x, y;\n    long long r;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n;\n    if (!(cin >> n)) return 0;\n    vector<Company> comp(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> comp[i].x >> comp[i].y >> comp[i].r;\n        comp[i].idx = i;\n    }\n\n    // 1) sort by x to ensure each point falls into its own vertical strip\n    sort(comp.begin(), comp.end(),\n         [](const Company& a, const Company& b) { return a.x < b.x; });\n\n    const int H = 10000;                     // board height\n    vector<int> width(n);                    // width of each strip (in original order)\n    vector<long long> base(n);\n    vector<int> rem(n);\n\n    // 2) initial width = floor(r_i / H), remainder = r_i % H\n    long long sumW = 0;\n    for (int i = 0; i < n; ++i) {\n        base[i] = comp[i].r / H;\n        rem[i]  = int(comp[i].r % H);\n        int w = int(base[i]);                // may be zero\n        if (w == 0) w = 1;                   // each rectangle must have positive area\n        width[comp[i].idx] = w;\n        sumW += w;\n    }\n\n    // 3) Adjust widths so that total width = 10000 and every width >= 1\n    const int TOTAL_W = 10000;\n    if (sumW > TOTAL_W) {\n        // need to shrink some strips (prefer those with smallest remainder)\n        // collect candidates that can be reduced (width > 1)\n        vector<int> order;\n        for (int i = 0; i < n; ++i) if (width[comp[i].idx] > 1) order.push_back(i);\n        // sort by increasing remainder (those less \"deserving\" of extra width first)\n        sort(order.begin(), order.end(),\n             [&](int a, int b) { return rem[a] < rem[b]; });\n        size_t p = 0;\n        while (sumW > TOTAL_W && p < order.size()) {\n            int id = comp[order[p]].idx;\n            width[id]--;\n            sumW--;\n            ++p;\n        }\n        // If still too large (very unlikely), keep decreasing from the end\n        for (int i = n - 1; sumW > TOTAL_W && i >= 0; --i) {\n            int id = comp[i].idx;\n            if (width[id] > 1) {\n                width[id]--;\n                --sumW;\n            }\n        }\n    } else if (sumW < TOTAL_W) {\n        // need to expand some strips (prefer those with largest remainder)\n        vector<int> order;\n        for (int i = 0; i < n; ++i) order.push_back(i);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) { return rem[a] > rem[b]; });\n        size_t p = 0;\n        while (sumW < TOTAL_W && p < order.size()) {\n            int id = comp[order[p]].idx;\n            width[id]++;\n            ++sumW;\n            ++p;\n        }\n        // If still lacking width, just distribute arbitrarily\n        for (int i = 0; sumW < TOTAL_W && i < n; ++i) {\n            int id = comp[i].idx;\n            width[id]++;\n            ++sumW;\n        }\n    }\n\n    // 4) Build the rectangles (vertical strips)\n    vector<array<int,4>> ans(n);\n    int curL = 0;\n    for (const auto& c : comp) {\n        int w = width[c.idx];\n        ans[c.idx] = {curL, 0, curL + w, H};\n        curL += w;\n    }\n\n    // 5) Output in the original order\n    for (int i = 0; i < n; ++i) {\n        auto &r = ans[i];\n        cout << r[0] << ' ' << r[1] << ' ' << r[2] << ' ' << r[3] << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 50;\n    int si, sj;\n    if (!(cin >> si >> sj)) return 0;\n\n    // read tile ids\n    int tile[N][N];\n    int maxId = -1;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            cin >> tile[i][j];\n            maxId = max(maxId, tile[i][j]);\n        }\n\n    // read point values\n    int p[N][N];\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> p[i][j];\n\n    vector<char> ans;\n    vector<char> dir = {'U', 'D', 'L', 'R'};\n    int di[4] = {-1, 1, 0, 0};\n    int dj[4] = {0, 0, -1, 1};\n\n    vector<char> used(maxId + 1, 0);\n    int curi = si, curj = sj;\n    used[tile[curi][curj]] = 1;               // start tile is already used\n\n    while (true) {\n        int bestVal = -1;\n        int bestDir = -1;\n        int bestNi = -1, bestNj = -1;\n\n        for (int d = 0; d < 4; ++d) {\n            int ni = curi + di[d];\n            int nj = curj + dj[d];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            int tid = tile[ni][nj];\n            if (used[tid]) continue;          // cannot reuse a tile\n            if (p[ni][nj] > bestVal) {\n                bestVal = p[ni][nj];\n                bestDir = d;\n                bestNi = ni;\n                bestNj = nj;\n            }\n        }\n\n        if (bestDir == -1) break;              // no move possible\n\n        // perform the move\n        ans.push_back(dir[bestDir]);\n        curi = bestNi;\n        curj = bestNj;\n        used[tile[curi][curj]] = 1;\n    }\n\n    // output the path (may be empty)\n    for (char c : ans) cout << c;\n    cout << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Edge {\n    int to;        // neighbour vertex id\n    int id;        // unique edge id (0 \u2026 1739)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int H = 30, W = 30;               // grid size\n    const int V = H * W;                    // number of vertices\n    const int E = (H * (W - 1)) + ((H - 1) * W); // total undirected edges\n\n    // build adjacency list and give each undirected edge a unique id\n    vector<vector<Edge>> g(V);\n    int edge_id = 0;\n    auto idx = [&](int i, int j) { return i * W + j; };\n\n    // horizontal edges\n    for (int i = 0; i < H; ++i) {\n        for (int j = 0; j < W - 1; ++j) {\n            int a = idx(i, j);\n            int b = idx(i, j + 1);\n            g[a].push_back({b, edge_id});\n            g[b].push_back({a, edge_id});\n            ++edge_id;\n        }\n    }\n    // vertical edges\n    for (int i = 0; i < H - 1; ++i) {\n        for (int j = 0; j < W; ++j) {\n            int a = idx(i, j);\n            int b = idx(i + 1, j);\n            g[a].push_back({b, edge_id});\n            g[b].push_back({a, edge_id});\n            ++edge_id;\n        }\n    }\n    // sanity\n    assert(edge_id == E);\n\n    // statistics for learning\n    vector<long double> total(E, 0.0L);\n    vector<int> cnt(E, 0);\n    vector<long double> weight(E, 1.0L);   // initial guess\n\n    const int Q = 1000;\n    for (int q = 0; q < Q; ++q) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) break;\n        int s = idx(si, sj);\n        int t = idx(ti, tj);\n\n        // ---------- Dijkstra ----------\n        const long double INF = 1e100L;\n        vector<long double> dist(V, INF);\n        vector<int> prev_v(V, -1);\n        vector<char> prev_dir(V, 0); // direction taken to reach this vertex from prev_v\n\n        using State = pair<long double, int>; // (dist, vertex)\n        priority_queue<State, vector<State>, greater<State>> pq;\n        dist[s] = 0;\n        pq.emplace(0.0L, s);\n\n        while (!pq.empty()) {\n            auto [d, v] = pq.top(); pq.pop();\n            if (d != dist[v]) continue;\n            if (v == t) break;\n            for (const auto &e : g[v]) {\n                long double w = weight[e.id];\n                if (dist[e.to] > d + w) {\n                    dist[e.to] = d + w;\n                    prev_v[e.to] = v;\n                    // decide direction character from v -> e.to\n                    int vi = v / W, vj = v % W;\n                    int ti2 = e.to / W, tj2 = e.to % W;\n                    char dir = '?';\n                    if (ti2 == vi - 1) dir = 'U';\n                    else if (ti2 == vi + 1) dir = 'D';\n                    else if (tj2 == vj - 1) dir = 'L';\n                    else if (tj2 == vj + 1) dir = 'R';\n                    prev_dir[e.to] = dir;\n                    pq.emplace(dist[e.to], e.to);\n                }\n            }\n        }\n\n        // ---------- reconstruct path ----------\n        string path_rev;\n        vector<int> used_edges; // edge ids on the path\n        int cur = t;\n        while (cur != s) {\n            int p = prev_v[cur];\n            char dir = prev_dir[cur];\n            path_rev.push_back(dir);\n            // find the edge id between p and cur\n            int edge_used = -1;\n            for (const auto &e : g[p]) if (e.to == cur) { edge_used = e.id; break; }\n            used_edges.push_back(edge_used);\n            cur = p;\n        }\n        reverse(path_rev.begin(), path_rev.end());\n        reverse(used_edges.begin(), used_edges.end());\n\n        // ---------- output ----------\n        cout << path_rev << '\\n' << flush;\n\n        // ---------- read judge reply ----------\n        long long reported;\n        cin >> reported;         // this is round(true_len * e_k)\n\n        // ---------- update statistics ----------\n        for (int id : used_edges) {\n            total[id] += reported;\n            ++cnt[id];\n            weight[id] = total[id] / cnt[id];   // simple average\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Placement {\n    bool horiz;   // true = horizontal, false = vertical\n    int line;     // row (if horiz) or column (if vertical)\n    int start;    // starting column (if horiz) or row (if vertical)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<string> S(M);\n    for (int i = 0; i < M; ++i) cin >> S[i];\n    \n    // board initially all '.'\n    vector<string> board(N, string(N, '.'));\n    \n    // order strings by decreasing length (longer first)\n    vector<int> idx(M);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(),\n         [&](int a, int b){ return S[a].size() > S[b].size(); });\n    \n    // greedy placement\n    for (int id : idx) {\n        const string& s = S[id];\n        int L = (int)s.size();\n        Placement bestPl{};\n        int bestGain = -1;\n        bool found = false;\n        \n        for (int orient = 0; orient < 2; ++orient) { // 0 = horiz, 1 = vert\n            bool horiz = (orient == 0);\n            for (int line = 0; line < N; ++line) {\n                for (int start = 0; start < N; ++start) {\n                    bool ok = true;\n                    int gain = 0;\n                    for (int p = 0; p < L; ++p) {\n                        int i = horiz ? line : (start + p) % N;\n                        int j = horiz ? (start + p) % N : line;\n                        char cur = board[i][j];\n                        if (cur != '.' && cur != s[p]) {\n                            ok = false;\n                            break;\n                        }\n                        if (cur == '.') ++gain;\n                    }\n                    if (ok && gain > bestGain) {\n                        bestGain = gain;\n                        bestPl = {horiz, line, start};\n                        found = true;\n                    }\n                }\n            }\n        }\n        if (!found) continue; // cannot place this string\n        \n        // write the string\n        const Placement &pl = bestPl;\n        for (int p = 0; p < L; ++p) {\n            int i = pl.horiz ? pl.line : (pl.start + p) % N;\n            int j = pl.horiz ? (pl.start + p) % N : pl.line;\n            board[i][j] = s[p];\n        }\n    }\n    \n    // replace remaining '.' with random letters (optional, just to avoid many dots)\n    std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> dist(0, 7);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == '.') board[i][j] = char('A' + dist(rng));\n        }\n    }\n    \n    // output\n    for (int i = 0; i < N; ++i) {\n        cout << board[i] << '\\n';\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int i, j;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, si, sj;\n    if (!(cin >> N >> si >> sj)) return 0;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) cin >> grid[i];\n\n    // Directions: U,D,L,R\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char dirc[4] = {'U','D','L','R'};\n    const char rev[4]  = {'D','U','R','L'};   // opposite move\n\n    // Map (i,j) -> index\n    vector<vector<int>> idx(N, vector<int>(N, -1));\n    vector<Cell> cells;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (grid[i][j] != '#') {\n                idx[i][j] = (int)cells.size();\n                cells.push_back({i, j});\n            }\n\n    int V = cells.size();\n    if (V == 0) { cout << \"\\n\"; return 0; }\n\n    // Build adjacency list\n    vector<vector<int>> adj(V);\n    for (int v = 0; v < V; ++v) {\n        int i = cells[v].i, j = cells[v].j;\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + di[d], nj = j + dj[d];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (grid[ni][nj] == '#') continue;\n            int u = idx[ni][nj];\n            adj[v].push_back(u);\n        }\n    }\n\n    // BFS to get spanning tree\n    int start = idx[si][sj];\n    vector<int> parent(V, -1);\n    vector<vector<int>> children(V);\n    queue<int> q;\n    q.push(start);\n    parent[start] = start;\n    while (!q.empty()) {\n        int v = q.front(); q.pop();\n        for (int to : adj[v]) {\n            if (parent[to] == -1) {\n                parent[to] = v;\n                children[v].push_back(to);\n                q.push(to);\n            }\n        }\n    }\n\n    // DFS walk (preorder) producing moves\n    string answer;\n    function<void(int)> dfs = [&](int v) {\n        int ci = cells[v].i, cj = cells[v].j;\n        for (int child : children[v]) {\n            int ni = cells[child].i, nj = cells[child].j;\n            // Determine direction from v to child (they are adjacent)\n            int d = -1;\n            for (int k = 0; k < 4; ++k) {\n                if (ci + di[k] == ni && cj + dj[k] == nj) { d = k; break; }\n            }\n            // go to child\n            answer.push_back(dirc[d]);\n            dfs(child);\n            // return to parent\n            answer.push_back(rev[d]);\n        }\n    };\n\n    dfs(start);\n    // At this point we are back at start, route is closed.\n    cout << answer << \"\\n\";\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K, R;\n    if (!(cin >> N >> M >> K >> R)) return 0;\n\n    // required skill vectors \u2013 not used by the algorithm\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) cin >> d[i][j];\n\n    // build DAG\n    vector<vector<int>> out(N);\n    vector<int> indeg(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;  cin >> u >> v;\n        --u; --v;\n        out[u].push_back(v);\n        ++indeg[v];\n    }\n\n    // task states\n    vector<int> task_state(N, -1);          // -1 not started, 0 started, 1 finished\n    deque<int> ready;\n    for (int i = 0; i < N; ++i) if (indeg[i] == 0) ready.push_back(i);\n\n    // member data\n    vector<int> member_task(M, -1);                 // current task ( -1 = idle )\n    vector<int> start_day(M, -1);                  // day when current task started\n    vector<double> avg_days(M, 1e9);                // estimated average duration\n    vector<int> cnt_done(M, 0);                    // number of completed tasks\n\n    int day = 0;\n    while (true) {\n        ++day;\n\n        // ----------- assignment phase ----------\n        vector<int> idle;\n        for (int j = 0; j < M; ++j) if (member_task[j] == -1) idle.push_back(j);\n        sort(idle.begin(), idle.end(),\n             [&](int a, int b){ return avg_days[a] < avg_days[b]; });\n\n        vector<pair<int,int>> assign;   // (member, task)\n        size_t p = 0;\n        while (p < idle.size() && !ready.empty()) {\n            int j = idle[p];\n            int t = ready.front(); ready.pop_front();\n            member_task[j] = t;\n            start_day[j] = day;\n            task_state[t] = 0;\n            assign.emplace_back(j, t);\n            ++p;\n        }\n\n        // output\n        cout << assign.size();\n        for (auto [mem, tas] : assign) {\n            cout << ' ' << mem + 1 << ' ' << tas + 1;\n        }\n        cout << '\\n';\n        cout.flush();\n\n        // ----------- read judge reply ----------\n        string line;\n        if (!getline(cin, line)) break;\n        while (line.size() && (line.back() == '\\r' || line.back() == '\\n')) line.pop_back();\n        if (line.empty()) {                     // consume possible empty line after previous >>\n            if (!getline(cin, line)) break;\n            while (line.size() && (line.back() == '\\r' || line.back() == '\\n')) line.pop_back();\n        }\n\n        if (line == \"-1\") break;                // finished / day limit\n\n        stringstream ss(line);\n        int cnt;\n        ss >> cnt;\n        vector<int> fin_members(cnt);\n        for (int i = 0; i < cnt; ++i) {\n            ss >> fin_members[i];\n            --fin_members[i];                   // to 0\u2011based\n        }\n\n        // process each finishing member\n        for (int j : fin_members) {\n            int t = member_task[j];\n            if (t == -1) continue;              // safety\n            int dur = day - start_day[j] + 1;    // inclusive\n            // update average duration\n            avg_days[j] = (avg_days[j] * cnt_done[j] + dur) / double(cnt_done[j] + 1);\n            ++cnt_done[j];\n\n            member_task[j] = -1;                // becomes idle\n            task_state[t] = 1;                  // finished\n\n            for (int nxt : out[t]) {\n                if (--indeg[nxt] == 0 && task_state[nxt] == -1) {\n                    ready.push_back(nxt);\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Order {\n    int a, b, c, d;\n};\n\ninline int manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// total distance of the route that visits the orders in the given order\nlong long totalDistance(const vector<int>& ord,\n                        const vector<Order>& orders,\n                        const pair<int,int>& office) {\n    long long tot = 0;\n    int curx = office.first, cury = office.second;\n    for (int idx : ord) {\n        const Order& o = orders[idx];\n        tot += manhattan(curx, cury, o.a, o.b);\n        curx = o.a; cury = o.b;\n        tot += manhattan(curx, cury, o.c, o.d);\n        curx = o.c; cury = o.d;\n    }\n    tot += manhattan(curx, cury, office.first, office.second);\n    return tot;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const pair<int,int> office = {400, 400};\n\n    vector<Order> orders(1000);\n    for (auto &o : orders) {\n        cin >> o.a >> o.b >> o.c >> o.d;\n    }\n\n    // ----- 1. choose 50 cheapest orders (round\u2011trip cost) -----\n    vector<long long> roundCost(1000);\n    for (int i = 0; i < 1000; ++i) {\n        const auto& o = orders[i];\n        roundCost[i] = (long long)manhattan(office.first, office.second, o.a, o.b)\n                     + (long long)manhattan(o.a, o.b, o.c, o.d)\n                     + (long long)manhattan(o.c, o.d, office.first, office.second);\n    }\n\n    vector<int> idx(1000);\n    iota(idx.begin(), idx.end(), 0);\n    nth_element(idx.begin(), idx.begin() + 50, idx.end(),\n                [&](int i, int j){ return roundCost[i] < roundCost[j]; });\n    idx.resize(50);                     // now contains 50 cheapest indices\n\n    // ----- 2. initial ordering (by distance of pickup from office) -----\n    sort(idx.begin(), idx.end(),\n         [&](int i, int j){\n             const auto& oi = orders[i];\n             const auto& oj = orders[j];\n             int di = manhattan(office.first, office.second, oi.a, oi.b);\n             int dj = manhattan(office.first, office.second, oj.a, oj.b);\n             return di < dj;\n         });\n\n    // ----- 3. simple local search: random swaps of whole pairs -----\n    long long bestScore = totalDistance(idx, orders, office);\n    std::mt19937 rng((unsigned)chrono::high_resolution_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> distPos(0, 49);\n\n    const int ITER = 2000;\n    for (int it = 0; it < ITER; ++it) {\n        int p = distPos(rng);\n        int q = distPos(rng);\n        if (p == q) continue;\n        if (p > q) swap(p, q);\n        swap(idx[p], idx[q]);\n        long long cur = totalDistance(idx, orders, office);\n        if (cur < bestScore) {\n            bestScore = cur;               // keep swap\n        } else {\n            swap(idx[p], idx[q]);           // revert\n        }\n    }\n\n    // ----- 4. output -----\n    cout << 50;\n    for (int id : idx) cout << ' ' << (id + 1);   // convert to 1\u2011based\n    cout << '\\n';\n\n    // build the full route\n    vector<pair<int,int>> route;\n    route.emplace_back(office);               // start\n    for (int id : idx) {\n        const Order& o = orders[id];\n        route.emplace_back(o.a, o.b);         // pickup\n        route.emplace_back(o.c, o.d);         // delivery\n    }\n    route.emplace_back(office);               // return\n\n    cout << route.size();\n    for (auto [x, y] : route) cout << ' ' << x << ' ' << y;\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 400;\n    const int M = 1995;\n    // read vertex coordinates (unused later)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        if(!(cin >> x >> y)) return 0;\n    }\n    // read edges\n    vector<int> u(M), v(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> u[i] >> v[i];\n    }\n    \n    DSU dsu(N);\n    for (int i = 0; i < M; ++i) {\n        long long li;\n        cin >> li;                 // true length, not needed for decision\n        if (dsu.find(u[i]) != dsu.find(v[i])) {\n            cout << \"1\\n\";\n            dsu.unite(u[i], v[i]);\n        } else {\n            cout << \"0\\n\";\n        }\n        cout.flush();             // mandatory after each answer\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos { int x, y; };\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<Pos> petPos(N);\n    vector<int> petType(N);\n    for (int i = 0; i < N; ++i) cin >> petPos[i].x >> petPos[i].y >> petType[i];\n\n    int M;\n    cin >> M;\n    vector<Pos> humanPos(M);\n    for (int i = 0; i < M; ++i) cin >> humanPos[i].x >> humanPos[i].y;\n\n    const int H = 30, W = 30;\n    // 0 = free, 1 = wall\n    vector<vector<int>> wall(H + 2, vector<int>(W + 2, 0));\n    // borders are treated as walls (impassable)\n    for (int i = 0; i <= H + 1; ++i) {\n        wall[i][0] = wall[i][W + 1] = 1;\n    }\n    for (int j = 0; j <= W + 1; ++j) {\n        wall[0][j] = wall[H + 1][j] = 1;\n    }\n\n    // helper to check inside board\n    auto inside = [&](int x, int y) {\n        return 1 <= x && x <= H && 1 <= y && y <= W;\n    };\n\n    // directions: U,D,L,R with corresponding delta\n    const string dirs = \"UDLR\";\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n\n    // for fast pet lookup on the grid\n    vector<vector<int>> petCnt(H + 2, vector<int>(W + 2, 0));\n    for (auto &p : petPos) petCnt[p.x][p.y]++;\n\n    for (int turn = 0; turn < 300; ++turn) {\n        string actions(M, '.');\n\n        // decide actions for each human\n        for (int i = 0; i < M; ++i) {\n            int hx = humanPos[i].x;\n            int hy = humanPos[i].y;\n            bool placed = false;\n            for (int d = 0; d < 4; ++d) {\n                int nx = hx + dx[d];\n                int ny = hy + dy[d];\n                if (!inside(nx, ny)) continue;\n                if (wall[nx][ny]) continue;            // already wall\n                if (petCnt[nx][ny] > 0) continue;      // pet stands there now\n                // check that none of the four neighbours of (nx,ny) contain a pet\n                bool adjPet = false;\n                for (int k = 0; k < 4; ++k) {\n                    int ax = nx + dx[k];\n                    int ay = ny + dy[k];\n                    if (!inside(ax, ay)) continue;\n                    if (petCnt[ax][ay] > 0) { adjPet = true; break; }\n                }\n                if (adjPet) continue;\n                // also cannot wall a cell that currently holds a human\n                bool otherHuman = false;\n                for (int j = 0; j < M; ++j) {\n                    if (j == i) continue;\n                    if (humanPos[j].x == nx && humanPos[j].y == ny) {\n                        otherHuman = true; break;\n                    }\n                }\n                if (otherHuman) continue;\n\n                // all checks passed \u2192 build wall\n                actions[i] = tolower(dirs[d]); // u/d/l/r\n                wall[nx][ny] = 1;\n                placed = true;\n                break;\n            }\n            // if no safe neighbour, action stays '.'\n            (void)placed;\n        }\n\n        // output actions\n        cout << actions << \"\\n\";\n        cout.flush();\n\n        // read pet movement strings and update positions\n        for (int i = 0; i < N; ++i) {\n            string moveStr;\n            cin >> moveStr;\n            // erase old count\n            petCnt[petPos[i].x][petPos[i].y]--;\n            // apply each step\n            for (char c : moveStr) {\n                if (c == '.') continue;\n                int md = -1;\n                if (c == 'U') md = 0;\n                else if (c == 'D') md = 1;\n                else if (c == 'L') md = 2;\n                else if (c == 'R') md = 3;\n                if (md != -1) {\n                    petPos[i].x += dx[md];\n                    petPos[i].y += dy[md];\n                }\n            }\n            // add new count\n            petCnt[petPos[i].x][petPos[i].y]++;\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Prev {\n    int pi, pj;\n    char mv;                 // move taken from predecessor to this cell\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj, ti, tj;\n    double p;\n    if (!(cin >> si >> sj >> ti >> tj >> p)) return 0;\n\n    const int N = 20;\n    vector<string> h(N);          // 20 strings, length 19\n    for (int i = 0; i < N; ++i) cin >> h[i];\n    vector<string> v(N - 1);      // 19 strings, length 20\n    for (int i = 0; i < N - 1; ++i) cin >> v[i];\n\n    // ---------- BFS ----------\n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    vector<vector<Prev>> pre(N, vector<Prev>(N, {-1, -1, '?'}));\n    queue<pair<int,int>> q;\n    dist[si][sj] = 0;\n    q.emplace(si, sj);\n\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        if (i == ti && j == tj) break;\n\n        // Up\n        if (i > 0 && v[i-1][j] == '0' && dist[i-1][j] == -1) {\n            dist[i-1][j] = dist[i][j] + 1;\n            pre[i-1][j] = {i, j, 'U'};\n            q.emplace(i-1, j);\n        }\n        // Down\n        if (i + 1 < N && v[i][j] == '0' && dist[i+1][j] == -1) {\n            dist[i+1][j] = dist[i][j] + 1;\n            pre[i+1][j] = {i, j, 'D'};\n            q.emplace(i+1, j);\n        }\n        // Left\n        if (j > 0 && h[i][j-1] == '0' && dist[i][j-1] == -1) {\n            dist[i][j-1] = dist[i][j] + 1;\n            pre[i][j-1] = {i, j, 'L'};\n            q.emplace(i, j-1);\n        }\n        // Right\n        if (j + 1 < N && h[i][j] == '0' && dist[i][j+1] == -1) {\n            dist[i][j+1] = dist[i][j] + 1;\n            pre[i][j+1] = {i, j, 'R'};\n            q.emplace(i, j+1);\n        }\n    }\n\n    // ---------- reconstruct shortest path ----------\n    string path;\n    int ci = ti, cj = tj;\n    while (!(ci == si && cj == sj)) {\n        Prev pr = pre[ci][cj];\n        path.push_back(pr.mv);\n        ci = pr.pi;\n        cj = pr.pj;\n    }\n    reverse(path.begin(), path.end());\n\n    if (path.empty()) {               // should never happen (start != target)\n        cout << \"U\\n\";\n        return 0;\n    }\n\n    // ---------- repeat to increase robustness ----------\n    const int MAXLEN = 200;\n    int repeat = MAXLEN / static_cast<int>(path.size());\n    string answer;\n    answer.reserve(repeat * path.size());\n\n    for (int i = 0; i < repeat; ++i) answer += path;\n\n    // optional: fill the remaining characters (not required)\n    int remaining = MAXLEN - static_cast<int>(answer.size());\n    if (remaining > 0) answer.append(path.substr(0, remaining));\n\n    cout << answer << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nconst int DIR = 4;\nconst int di[DIR] = {0, -1, 0, 1};\nconst int dj[DIR] = {-1, 0, 1, 0};\n\nint to0[8][DIR] = {\n    { 1, 0, -1, -1},\n    { 3,-1, -1,  0},\n    {-1,-1,  3,  2},\n    {-1, 2,  1, -1},\n    { 1, 0,  3,  2},\n    { 3, 2,  1,  0},\n    { 2,-1,  0, -1},\n    {-1, 3, -1,  1},\n};\n\nint to_rot[8][4][DIR];   // [type][rotation][enter_dir] -> leave_dir or -1\n\nvoid build_rot() {\n    for (int t = 0; t < 8; ++t)\n        for (int r = 0; r < 4; ++r)\n            for (int d = 0; d < DIR; ++d) {\n                int d0 = (d - r + 4) % 4;           // direction in original orientation\n                int nd = to0[t][d0];\n                if (nd == -1) {\n                    to_rot[t][r][d] = -1;\n                } else {\n                    to_rot[t][r][d] = (nd + r) % 4; // rotate back\n                }\n            }\n}\n\n/* ------------------------------------------------------------------ */\n/*   compute score for given rotation matrix                           */\n/* ------------------------------------------------------------------ */\nint compute_score(const vector<string>& tile, const int rot[N][N]) {\n    static bool seen[N][N][DIR];\n    memset(seen, 0, sizeof(seen));\n    vector<int> loops;\n\n    for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) for (int d = 0; d < DIR; ++d) {\n        if (seen[i][j][d]) continue;\n        int t = tile[i][j] - '0';\n        int r = rot[i][j];\n        int ndir = to_rot[t][r][d];\n        if (ndir == -1) continue;               // no edge in this direction\n\n        // start walking\n        int ci = i, cj = j, cd = d;\n        int len = 0;\n        bool broken = false;\n        while (true) {\n            int tcur = tile[ci][cj] - '0';\n            int rcur = rot[ci][cj];\n            int nd = to_rot[tcur][rcur][cd];\n            if (nd == -1) { broken = true; break; }\n            int ni = ci + di[nd];\n            int nj = cj + dj[nd];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) { broken = true; break; }\n            int ndir_next = (nd + 2) % 4;   // direction we will enter next cell\n            seen[ci][cj][cd] = true;\n            ++len;\n            ci = ni; cj = nj; cd = ndir_next;\n            if (ci == i && cj == j && cd == d) break; // closed loop\n        }\n        if (!broken && len > 0) loops.push_back(len);\n    }\n\n    if (loops.size() < 2) return 0;\n    nth_element(loops.begin(), loops.begin(), loops.end(), greater<int>());\n    int L1 = loops[0];\n    nth_element(loops.begin()+1, loops.begin()+1, loops.end(), greater<int>());\n    int L2 = loops[1];\n    return L1 * L2;\n}\n\n/* ------------------------------------------------------------------ */\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    build_rot();\n\n    vector<string> tile(N);\n    for (int i = 0; i < N; ++i) cin >> tile[i];\n\n    // random initial rotations\n    static int rot[N][N];\n    std::mt19937 rng((uint64_t)chrono::high_resolution_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist4(0,3);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            rot[i][j] = dist4(rng);\n\n    int best_score = compute_score(tile, rot);\n    int cur_score = best_score;\n\n    const double TIME_LIMIT = 1.80;   // seconds\n    auto start_time = chrono::steady_clock::now();\n\n    // annealing parameters\n    double temp0 = 2000.0, temp1 = 20.0;\n    int iter = 0;\n    while (true) {\n        ++iter;\n        double elapsed = chrono::duration<double>(chrono::steady_clock::now() - start_time).count();\n        if (elapsed > TIME_LIMIT) break;\n        double temp = temp0 + (temp1 - temp0) * (elapsed / TIME_LIMIT);\n\n        int i = uniform_int_distribution<int>(0, N-1)(rng);\n        int j = uniform_int_distribution<int>(0, N-1)(rng);\n        int old_r = rot[i][j];\n        int new_r = dist4(rng);\n        if (new_r == old_r) continue;\n        rot[i][j] = new_r;\n        int new_score = compute_score(tile, rot);\n        bool accept = false;\n        if (new_score >= cur_score) accept = true;\n        else {\n            double prob = exp((new_score - cur_score) / temp);\n            if (uniform_real_distribution<double>(0.0,1.0)(rng) < prob) accept = true;\n        }\n        if (accept) {\n            cur_score = new_score;\n            if (cur_score > best_score) {\n                best_score = cur_score;\n                // we could store best rotation matrix, but we keep current one\n            }\n        } else {\n            rot[i][j] = old_r;   // revert\n        }\n    }\n\n    // output\n    string out;\n    out.reserve(N*N);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            out.push_back(char('0' + rot[i][j]));\n    cout << out << '\\n';\n    return 0;\n}","ahc011":"#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    long long T;\n    if (!(cin >> N >> T)) return 0;\n    string row;\n    for (int i = 0; i < N; ++i) {\n        cin >> row;               // each row of length N\n    }\n    // Output an empty sequence of moves.\n    cout << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    long long N;\n    int K;\n    if (!(cin >> N >> K)) return 0;\n    // read a_1 .. a_10\n    for (int i = 0; i < 10; ++i) {\n        long long a;\n        cin >> a;\n    }\n    // read strawberries positions\n    for (long long i = 0; i < N; ++i) {\n        long long x, y;\n        cin >> x >> y;\n    }\n    // output zero cuts\n    cout << 0 << \"\\n\";\n    return 0;\n}","ahc014":"#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    if (!(cin >> N >> M)) return 0;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y; // just consume the input\n    }\n    cout << 0 << \"\\n\";   // no operations\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 10;                 // board dimension\nusing Board = array<array<int, N>, N>;\n\nstruct Pos { int r, c; };\n\n/// apply tilt direction:\n/// 0 = Forward (toward smaller row), 1 = Backward (larger row),\n/// 2 = Left (smaller col), 3 = Right (larger col)\nBoard tilt(const Board &src, int dir) {\n    Board dst = src;\n    if (dir == 0) {                     // Forward: compress upwards\n        for (int c = 0; c < N; ++c) {\n            int write = 0;\n            for (int r = 0; r < N; ++r) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[write][c] = v;\n                ++write;\n            }\n        }\n    } else if (dir == 1) {              // Backward: compress downwards\n        for (int c = 0; c < N; ++c) {\n            int write = N - 1;\n            for (int r = N - 1; r >= 0; --r) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[write][c] = v;\n                --write;\n            }\n        }\n    } else if (dir == 2) {              // Left: compress leftwards\n        for (int r = 0; r < N; ++r) {\n            int write = 0;\n            for (int c = 0; c < N; ++c) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[r][write] = v;\n                ++write;\n            }\n        }\n    } else {                            // Right: compress rightwards\n        for (int r = 0; r < N; ++r) {\n            int write = N - 1;\n            for (int c = N - 1; c >= 0; --c) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[r][write] = v;\n                --write;\n            }\n        }\n    }\n    return dst;\n}\n\n/// compute \u03a3 size\u00b2 over all connected components (4\u2011neighbour) per flavour\nlong long boardScore(const Board &b) {\n    static const int dr[4] = {-1, 1, 0, 0};\n    static const int dc[4] = {0, 0, -1, 1};\n\n    bool vis[N][N] = {};\n    long long total = 0;\n    for (int r = 0; r < N; ++r) for (int c = 0; c < N; ++c) {\n        if (b[r][c] == 0 || vis[r][c]) continue;\n        int flavour = b[r][c];\n        int sz = 0;\n        queue<Pos> q;\n        q.push({r, c});\n        vis[r][c] = true;\n        while (!q.empty()) {\n            Pos cur = q.front(); q.pop();\n            ++sz;\n            for (int d = 0; d < 4; ++d) {\n                int nr = cur.r + dr[d];\n                int nc = cur.c + dc[d];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                if (!vis[nr][nc] && b[nr][nc] == flavour) {\n                    vis[nr][nc] = true;\n                    q.push({nr, nc});\n                }\n            }\n        }\n        total += 1LL * sz * sz;\n    }\n    return total;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // 1. read flavours (unused for the heuristic)\n    vector<int> flavour(100);\n    for (int i = 0; i < 100; ++i) cin >> flavour[i];\n\n    Board board{};\n    // initially all zeros\n\n    const char dirChar[4] = {'F', 'B', 'L', 'R'};\n\n    for (int step = 0; step < 100; ++step) {\n        int p;            // 1\u2011based index of the empty cell\n        cin >> p;\n\n        // ---- place the new candy ---------------------------------\n        vector<Pos> empties;\n        empties.reserve(100);\n        for (int r = 0; r < N; ++r)\n            for (int c = 0; c < N; ++c)\n                if (board[r][c] == 0) empties.push_back({r, c});\n\n        Pos where = empties[p - 1];\n        board[where.r][where.c] = flavour[step];   // insert the candy\n\n        // ---- choose best tilt ------------------------------------\n        long long bestScore = -1;\n        int bestDir = 0;   // default to Forward\n        for (int d = 0; d < 4; ++d) {\n            Board nb = tilt(board, d);\n            long long sc = boardScore(nb);\n            if (sc > bestScore) {\n                bestScore = sc;\n                bestDir = d;\n            }\n        }\n\n        // output the chosen direction\n        cout << dirChar[bestDir] << '\\n';\n        cout.flush();\n\n        // apply the chosen tilt to the real board state for the next step\n        board = tilt(board, bestDir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n\n    const int N = 20;                         // fixed vertex count\n    const int L = N * (N - 1) / 2;            // length of each graph string\n\n    cout << N << \"\\n\";\n    for (int k = 0; k < M; ++k) {\n        string s(k, '1');                     // k ones\n        s.append(L - k, '0');                 // remaining zeros\n        cout << s << \"\\n\";\n    }\n    cout.flush();\n\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;                             // length L\n        int cnt = 0;\n        for (char c : H) if (c == '1') ++cnt;\n\n        int t = min(cnt, M - 1);               // nearest index (0 \u2026 M\u20111)\n        cout << t << \"\\n\";\n        cout.flush();\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Edge {\n    int idx;       // original index (0\u2011based)\n    int w;         // weight\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n\n    vector<Edge> edges;\n    edges.reserve(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        edges.push_back({i, w});\n    }\n\n    // vertex coordinates are irrelevant for the schedule\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    // Sort by weight descending: longest edges first (they influence distances least)\n    sort(edges.begin(), edges.end(),\n         [](const Edge& a, const Edge& b) { return a.w > b.w; });\n\n    vector<int> day_of_edge(M);\n    for (int i = 0; i < M; ++i) {\n        int original = edges[i].idx;\n        day_of_edge[original] = (i % D) + 1;   // 1\u2011based day number\n    }\n\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << day_of_edge[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int D;\n    if (!(cin >> D)) return 0;\n\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) cin >> f[i][z];\n        for (int z = 0; z < D; ++z) cin >> r[i][z];\n    }\n\n    const long long SZ = 1LL * D * D * D;\n    vector<int> out1(SZ, 0), out2(SZ, 0);\n    long long curId = 0;\n\n    auto idx = [&](int x, int y, int z) -> long long {\n        return 1LL * x * D * D + 1LL * y * D + z;\n    };\n\n    // object 1\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                if (f[0][z][x] == '1' && r[0][z][y] == '1') {\n                    ++curId;\n                    out1[idx(x, y, z)] = (int)curId;\n                }\n            }\n        }\n    }\n    // object 2\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            for (int z = 0; z < D; ++z) {\n                if (f[1][z][x] == '1' && r[1][z][y] == '1') {\n                    ++curId;\n                    out2[idx(x, y, z)] = (int)curId;\n                }\n            }\n        }\n    }\n\n    cout << curId << \"\\n\";\n    for (size_t i = 0; i < out1.size(); ++i) {\n        if (i) cout << ' ';\n        cout << out1[i];\n    }\n    cout << \"\\n\";\n    for (size_t i = 0; i < out2.size(); ++i) {\n        if (i) cout << ' ';\n        cout << out2[i];\n    }\n    cout << \"\\n\";\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) { p.resize(n); r.assign(n, 0); iota(p.begin(), p.end(), 0); }\n    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;\n\n    vector<long long> x(N + 1), y(N + 1);\n    for (int i = 1; i <= N; ++i) cin >> x[i] >> y[i];\n\n    struct Edge {int u, v; long long w;};\n    vector<Edge> edges(M + 1);\n    // adjacency for Floyd\u2011Warshall\n    const long long INF = (1LL << 60);\n    vector<vector<long long>> dist(N + 1, vector<long long>(N + 1, INF));\n    vector<vector<int>> nxt(N + 1, vector<int>(N + 1, -1));\n\n    map<pair<int,int>, int> pairToIdx;          // (min,max) -> edge id\n    for (int j = 1; j <= M; ++j) {\n        int u, v; long long w;\n        cin >> u >> v >> w;\n        edges[j] = {u, v, w};\n        if (w < dist[u][v]) {\n            dist[u][v] = dist[v][u] = w;\n            nxt[u][v] = v;\n            nxt[v][u] = u;\n        }\n        pair<int,int> p = {min(u,v), max(u,v)};\n        pairToIdx[p] = j;\n    }\n\n    for (int i = 1; i <= N; ++i) {\n        dist[i][i] = 0;\n        nxt[i][i] = i;\n    }\n\n    // Floyd\u2011Warshall with path reconstruction\n    for (int k = 1; k <= N; ++k) {\n        for (int i = 1; i <= N; ++i) if (dist[i][k] != INF) {\n            for (int j = 1; j <= N; ++j) if (dist[k][j] != INF) {\n                long long nd = dist[i][k] + dist[k][j];\n                if (nd < dist[i][j]) {\n                    dist[i][j] = nd;\n                    nxt[i][j] = nxt[i][k];\n                }\n            }\n        }\n    }\n\n    // read residents\n    struct Resident { long long a,b; };\n    vector<Resident> res(K);\n    for (int i = 0; i < K; ++i) cin >> res[i].a >> res[i].b;\n\n    // ---- 1. assign each resident to the nearest station ----\n    vector<vector<int>> assigned(N + 1);\n    for (int idx = 0; idx < K; ++idx) {\n        long long ax = res[idx].a, ay = res[idx].b;\n        int best = 1;\n        long long bestDist2 = (x[1]-ax)*(x[1]-ax) + (y[1]-ay)*(y[1]-ay);\n        for (int i = 2; i <= N; ++i) {\n            long long dx = x[i]-ax, dy = y[i]-ay;\n            long long d2 = dx*dx + dy*dy;\n            if (d2 < bestDist2) {\n                bestDist2 = d2;\n                best = i;\n            }\n        }\n        assigned[best].push_back(idx);\n    }\n\n    // ---- 2. required power for each station ----\n    vector<int> P(N + 1, 0);\n    for (int i = 1; i <= N; ++i) {\n        if (assigned[i].empty()) continue;\n        long double maxDist = 0.0L;\n        for (int idx : assigned[i]) {\n            long double dx = (long double)x[i] - (long double)res[idx].a;\n            long double dy = (long double)y[i] - (long double)res[idx].b;\n            long double d = sqrt(dx*dx + dy*dy);\n            if (d > maxDist) maxDist = d;\n        }\n        // ceil to integer, but never exceed 5000 (guaranteed by input)\n        long long pi = (long long)ceil(maxDist - 1e-12L);\n        if (pi > 5000) pi = 5000;\n        P[i] = (int)pi;\n    }\n\n    // ---- 3. list of active vertices (need to be reachable) ----\n    vector<int> active;\n    vector<int> idMap(N + 1, -1);   // vertex -> index in active list\n    if (P[1] > 0) { // source already active\n        idMap[1] = active.size();\n        active.push_back(1);\n    } else {\n        // we still need source as root of the tree\n        idMap[1] = active.size();\n        active.push_back(1);\n    }\n    for (int i = 2; i <= N; ++i) {\n        if (P[i] > 0) {\n            idMap[i] = active.size();\n            active.push_back(i);\n        }\n    }\n    if (active.size() == 1) { // no active stations at all, trivial solution\n        // output all zeros\n        for (int i = 1; i <= N; ++i) {\n            if (i > 1) cout << ' ';\n            cout << 0;\n        }\n        cout << \"\\n\";\n        for (int j = 1; j <= M; ++j) {\n            if (j > 1) cout << ' ';\n            cout << 0;\n        }\n        cout << \"\\n\";\n        return 0;\n    }\n\n    // ---- 4. build complete graph on active vertices, run Kruskal ----\n    struct EdgeM { long long w; int u, v; };\n    vector<EdgeM> metEdges;\n    int A = active.size();\n    for (int i = 0; i < A; ++i) {\n        for (int j = i + 1; j < A; ++j) {\n            int vi = active[i];\n            int vj = active[j];\n            metEdges.push_back({dist[vi][vj], vi, vj});\n        }\n    }\n    sort(metEdges.begin(), metEdges.end(),\n        [](const EdgeM& a, const EdgeM& b){ return a.w < b.w; });\n\n    DSU dsu(N + 1);\n    vector<pair<int,int>> mstEdges;\n    for (auto &e : metEdges) {\n        if (dsu.unite(e.u, e.v)) {\n            mstEdges.emplace_back(e.u, e.v);\n        }\n    }\n\n    // ---- 5. mark original edges used in the shortest paths of MST ----\n    vector<char> usedEdge(M + 1, 0);\n    auto addPath = [&](int s, int t){\n        int cur = s;\n        while (cur != t) {\n            int nxtv = nxt[cur][t];\n            int a = min(cur, nxtv), b = max(cur, nxtv);\n            int idx = pairToIdx[{a,b}];\n            usedEdge[idx] = 1;\n            cur = nxtv;\n        }\n    };\n    for (auto [u,v] : mstEdges) addPath(u, v);\n\n    // ---- 6. output ----\n    for (int i = 1; i <= N; ++i) {\n        if (i > 1) cout << ' ';\n        cout << P[i];\n    }\n    cout << \"\\n\";\n    for (int j = 1; j <= M; ++j) {\n        if (j > 1) cout << ' ';\n        cout << (int)usedEdge[j];\n    }\n    cout << \"\\n\";\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Swap {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 30;\n    const int M = N * (N + 1) / 2;          // 465\n\n    // read the pyramid\n    vector<vector<int>> a(N);\n    for (int x = 0; x < N; ++x) {\n        a[x].resize(x + 1);\n        for (int y = 0; y <= x; ++y) {\n            cin >> a[x][y];\n        }\n    }\n\n    vector<Swap> ops;\n    ops.reserve(10000);\n\n    // bottom\u2011up heapify\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            int cx = x, cy = y;\n            while (cx + 1 < N) {\n                int leftX = cx + 1, leftY = cy;\n                int rightX = cx + 1, rightY = cy + 1;\n\n                // choose the smaller child\n                int childX, childY;\n                if (a[leftX][leftY] <= a[rightX][rightY]) {\n                    childX = leftX; childY = leftY;\n                } else {\n                    childX = rightX; childY = rightY;\n                }\n\n                if (a[childX][childY] < a[cx][cy]) {\n                    // perform the swap\n                    swap(a[cx][cy], a[childX][childY]);\n                    ops.push_back({cx, cy, childX, childY});\n                    if ((int)ops.size() >= 10000) break; // safety\n                    // continue from child's position\n                    cx = childX; cy = childY;\n                } else {\n                    break; // heap property satisfied at this node\n                }\n            }\n            if ((int)ops.size() >= 10000) break;\n        }\n        if ((int)ops.size() >= 10000) break;\n    }\n\n    // output\n    cout << ops.size() << '\\n';\n    for (auto &s : ops) {\n        cout << s.x1 << ' ' << s.y1 << ' '\n             << s.x2 << ' ' << s.y2 << '\\n';\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int i, j;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int D = 9;\n    int N;\n    if(!(cin >> D >> N)) return 0;          // D is always 9 in all tests\n    vector<vector<int>> blocked(D, vector<int>(D, 0));\n    // entrance\n    const int ei = 0, ej = (D - 1) / 2;\n    blocked[ei][ej] = 1;                    // cannot be used for storage\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        blocked[ri][rj] = 1;\n    }\n\n    auto inside = [&](int x, int y) {\n        return 0 <= x && x < D && 0 <= y && y < D;\n    };\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n\n    // give each cell an id\n    auto id = [&](int i, int j) { return i * D + j; };\n    const int V = D * D;\n    vector<int> dist(V, -1);\n    vector<int> parent(V, -1);\n    vector<vector<int>> adj(V);\n    // BFS from entrance to compute distances and adjacency\n    queue<int> q;\n    int start = id(ei, ej);\n    dist[start] = 0;\n    q.push(start);\n    while (!q.empty()) {\n        int v = q.front(); q.pop();\n        int ci = v / D, cj = v % D;\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = ci + di[dir], nj = cj + dj[dir];\n            if (!inside(ni, nj)) continue;\n            if (blocked[ni][nj]) continue;\n            int nv = id(ni, nj);\n            adj[v].push_back(nv);\n            adj[nv].push_back(v);\n            if (dist[nv] == -1) {\n                dist[nv] = dist[v] + 1;\n                parent[nv] = v;\n                q.push(nv);\n            }\n        }\n    }\n\n    // list of all usable cells (not blocked, not entrance)\n    vector<int> cells;\n    for (int i = 0; i < D; ++i)\n        for (int j = 0; j < D; ++j)\n            if (!blocked[i][j] && !(i == ei && j == ej))\n                cells.push_back(id(i, j));\n\n    const int M = (int)cells.size();      // number of containers\n\n    // degree = number of neighbours that are still empty (initially all free neighbours)\n    vector<int> deg(V, 0);\n    for (int v : cells) {\n        int cnt = 0;\n        for (int nb : adj[v]) {\n            int ni = nb / D, nj = nb % D;\n            if (!blocked[ni][nj]) ++cnt;\n        }\n        deg[v] = cnt;\n    }\n\n    // leaf set: empty cells with deg == 1 (and not entrance)\n    unordered_set<int> leafSet;\n    for (int v : cells) {\n        if (deg[v] == 1) leafSet.insert(v);\n    }\n\n    // container number stored in each cell, -1 = empty\n    vector<int> container(V, -1);\n    // ----- storing phase -----\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;               // container number received now\n\n        // pick any leaf (the set is tiny, just take the first)\n        int chosen = *leafSet.begin();\n        leafSet.erase(chosen);\n\n        // output coordinates\n        cout << (chosen / D) << ' ' << (chosen % D) << '\\n';\n        cout.flush();\n\n        container[chosen] = t;          // remember what is placed here\n\n        // update neighbours: this cell becomes occupied -> disappear from empty graph\n        for (int nb : adj[chosen]) {\n            if (blocked[nb / D][nb % D]) continue;          // obstacle\n            if (container[nb] != -1) continue;              // already occupied\n            // nb is still empty\n            deg[nb]--;\n            if (deg[nb] == 1) leafSet.insert(nb);\n        }\n    }\n\n    // ----- taking\u2011out phase -----\n    // bucket cells by distance\n    int maxDist = 0;\n    for (int v : cells) maxDist = max(maxDist, dist[v]);\n    vector<vector<int>> bucket(maxDist + 1);\n    for (int v : cells) {\n        int d = dist[v];\n        bucket[d].push_back(v);\n    }\n    // output in increasing distance, inside each bucket sorted by container number\n    for (int d = 1; d <= maxDist; ++d) {\n        auto &vec = bucket[d];\n        sort(vec.begin(), vec.end(),\n             [&](int a, int b) { return container[a] < container[b]; });\n        for (int v : vec) {\n            cout << (v / D) << ' ' << (v % D) << '\\n';\n        }\n    }\n    cout.flush();\n    return 0;\n}","ahc024":"#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    if (!(cin >> n >> m)) return 0;\n    vector<vector<int>> a(n, vector<int>(n));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (j) cout << ' ';\n            cout << a[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n    vector<long long> w(N);\n    for (int i = 0; i < N; ++i) cin >> w[i];   // offline version gives the weights\n    \n    // indices sorted by decreasing weight\n    vector<int> ids(N);\n    iota(ids.begin(), ids.end(), 0);\n    sort(ids.begin(), ids.end(), [&](int a, int b){ return w[a] > w[b]; });\n    \n    vector<long long> tot(D, 0);\n    vector<int> ans(N, -1);\n    \n    for (int id : ids) {\n        // find bin with minimal total weight\n        int best = 0;\n        for (int b = 1; b < D; ++b) {\n            if (tot[b] < tot[best]) best = b;\n        }\n        ans[id] = best;\n        tot[best] += w[id];\n    }\n    \n    // output division\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << ans[i];\n    }\n    cout << '\\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    int n, m;\n    if (!(cin >> n >> m)) return 0;          // n = 200, m = 10\n    const int per = n / m;                   // 20\n    vector<vector<int>> st(m);               // bottom -> top\n    for (int i = 0; i < m; ++i) {\n        st[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x; cin >> x;\n            st[i].push_back(x);\n        }\n    }\n\n    vector<pair<int,int>> ops;\n    ops.reserve(5000);\n\n    auto next_stack = [&](int cur) {\n        int nxt = (cur + 1) % m;\n        if (nxt == cur) nxt = (nxt + 1) % m;\n        return nxt;\n    };\n\n    for (int target = 1; target <= n; ++target) {\n        while (true) {\n            // locate the stack and position of target\n            int s = -1, pos = -1;\n            for (int i = 0; i < m; ++i) {\n                for (int j = 0; j < (int)st[i].size(); ++j) {\n                    if (st[i][j] == target) {\n                        s = i;\n                        pos = j;\n                        break;\n                    }\n                }\n                if (s != -1) break;\n            }\n            // must exist\n            int topIdx = (int)st[s].size() - 1;\n            if (pos == topIdx) {\n                // pop\n                ops.emplace_back(target, 0);\n                st[s].pop_back();\n                break;                      // go to next target\n            } else {\n                // move the whole block above target\n                int start = pos + 1;                // bottom of the block\n                int dest = next_stack(s);\n                // ensure dest != s\n                if (dest == s) dest = (dest + 1) % m;\n                int v = st[s][start];               // bottom element of block\n                ops.emplace_back(v, dest + 1);       // type 1\n\n                // extract block\n                vector<int> block(st[s].begin() + start, st[s].end());\n                st[s].erase(st[s].begin() + start, st[s].end());\n                // append to destination, preserving order\n                st[dest].insert(st[dest].end(), block.begin(), block.end());\n                // now target is on top; loop again to pop it\n            }\n        }\n    }\n\n    for (auto [v, i] : ops) {\n        cout << v << ' ' << i << '\\n';\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n\n    vector<string> h(N - 1);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    vector<string> v(N);\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    // d is read but not used\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            long long tmp;\n            cin >> tmp;\n        }\n    }\n\n    const int di[4] = {0, 1, 0, -1};\n    const int dj[4] = {1, 0, -1, 0};\n    const char moveChar[4] = {'R', 'D', 'L', 'U'};\n    const char backChar[4] = {'L', 'U', 'R', 'D'};\n\n    vector<vector<char>> visited(N, vector<char>(N, 0));\n    string answer;\n\n    function<void(int,int)> dfs = [&](int i, int j) {\n        visited[i][j] = 1;\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + di[dir];\n            int nj = j + dj[dir];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (visited[ni][nj]) continue;\n            // check wall\n            bool blocked = false;\n            if (dir == 0) { // right\n                blocked = (v[i][j] == '1');\n            } else if (dir == 2) { // left\n                blocked = (v[i][j-1] == '1');\n            } else if (dir == 1) { // down\n                blocked = (h[i][j] == '1');\n            } else { // up\n                blocked = (h[i-1][j] == '1');\n            }\n            if (blocked) continue;\n\n            answer.push_back(moveChar[dir]);\n            dfs(ni, nj);\n            answer.push_back(backChar[dir]);\n        }\n    };\n\n    dfs(0, 0);\n    cout << answer << '\\n';\n    return 0;\n}","ahc028":"#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    if (!(cin >> N >> M)) return 0;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    // store first occurrence of each letter\n    pair<int,int> pos[26];\n    for (int k = 0; k < 26; ++k) pos[k] = {-1,-1};\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int idx = board[i][j] - 'A';\n            if (pos[idx].first == -1) pos[idx] = {i, j};\n        }\n    }\n\n    vector<string> words(M);\n    for (int k = 0; k < M; ++k) cin >> words[k];\n\n    // generate answer\n    vector<pair<int,int>> answer;\n    answer.reserve(5 * M + 10);\n    int cur_i = si, cur_j = sj;          // current finger position (unused later)\n\n    for (const string& w : words) {\n        for (char ch : w) {\n            auto [ti, tj] = pos[ch - 'A'];   // a cell containing ch\n            answer.emplace_back(ti, tj);\n            cur_i = ti; cur_j = tj;\n        }\n    }\n\n    // output\n    for (auto [i, j] : answer) {\n        cout << i << ' ' << j << '\\n';\n    }\n    return 0;\n}","ahc030":"#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    double eps;\n    if (!(cin >> N >> M >> eps)) return 0;\n\n    // ---- read shapes (ignored later) ----\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        for (int t = 0; t < d; ++t) {\n            int a, b;\n            cin >> a >> b;\n        }\n    }\n\n    // ---- read positions of each field (unused) ----\n    for (int k = 0; k < M; ++k) {\n        int di, dj;\n        cin >> di >> dj;\n        (void)di; (void)dj;\n    }\n\n    // ---- read the whole v matrix ----\n    vector<vector<int>> v(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> v[i][j];\n\n    // ---- discard the remaining numbers (up to 2*N^2) ----\n    // The exact amount is not needed; just read until EOF.\n    double dummy;\n    while (cin >> dummy) { /* discard */ }\n\n    // ---- collect cells with v > 0 ----\n    vector<pair<int,int>> ans;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (v[i][j] > 0) ans.emplace_back(i, j);\n\n    // ---- output in the required format ----\n    cout << \"a \" << ans.size();\n    for (auto [i, j] : ans) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << \"\\n\";\n    cout.flush();\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    if (!(cin >> W >> D >> N)) return 0;\n    // read and ignore the desired areas\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            long long a;\n            cin >> a;\n            (void)a;\n        }\n    }\n\n    // output the simple vertical strips\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            int i0 = k;\n            int j0 = 0;\n            int i1 = k + 1;\n            int j1 = W;\n            cout << i0 << ' ' << j0 << ' ' << i1 << ' ' << j1 << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing int64 = long long;\nconst int64 MOD = 998244353LL;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;   // N=9, M=20, K=81\n    \n    vector<vector<int64>> board(N, vector<int64>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> board[i][j];\n    \n    // stamps[m][i][j]\n    vector<array<array<int64,3>,3>> stamp(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 >> stamp[m][i][j];\n    \n    struct Op { int m, p, q; };\n    vector<Op> ops;\n    ops.reserve(K);\n    \n    for (int step = 0; step < K; ++step) {\n        int best_m = -1, best_p = -1, best_q = -1;\n        int64 best_gain = 0;               // we only accept positive gain\n        \n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    int64 gain = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            int64 old_val = board[p+i][q+j];\n                            int64 old_rem = old_val % MOD;\n                            int64 new_rem = (old_val + stamp[m][i][j]) % MOD;\n                            gain += new_rem - old_rem;\n                        }\n                    }\n                    if (gain > best_gain) {\n                        best_gain = gain;\n                        best_m = m; best_p = p; best_q = q;\n                    }\n                }\n            }\n        }\n        if (best_gain <= 0) break;          // no improving move\n        \n        // apply best operation\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                board[best_p + i][best_q + j] += stamp[best_m][i][j];\n        \n        ops.push_back({best_m, best_p, best_q});\n    }\n    \n    // output\n    cout << ops.size() << '\\n';\n    for (auto &op : ops) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n    return 0;\n}","ahc033":"#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    if (!(cin >> N)) return 0;          // N is always 5\n    // read and ignore the matrix A\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            int x; cin >> x;\n            (void)x;\n        }\n\n    vector<string> ops(N);\n    for (int i = 0; i < N; ++i) {\n        string s;\n        // first N-1 containers: pick, go right 4, drop, go left 4\n        for (int cnt = 0; cnt < N - 1; ++cnt) {\n            s.push_back('P');\n            s.append(4, 'R');   // move to column N-1\n            s.push_back('Q');\n            s.append(4, 'L');   // return to column 0\n        }\n        // last container: pick, go right 4, drop\n        s.push_back('P');\n        s.append(4, 'R');\n        s.push_back('Q');\n        ops[i] = s;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << ops[i] << '\\n';\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int r, c;\n    int amt;          // for positives: amount to load; for negatives: amount to receive\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> h[i][j];\n    \n    vector<Cell> pos, neg;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (h[i][j] > 0) pos.push_back({i, j, h[i][j]});\n            else if (h[i][j] < 0) neg.push_back({i, j, -h[i][j]});\n        }\n    \n    int curR = 0, curC = 0;          // current truck position\n    long long load = 0;              // soil currently on the truck\n    \n    auto move_to = [&](int tr, int tc) {\n        while (curR < tr) { cout << \"D\\n\"; ++curR; }\n        while (curR > tr) { cout << \"U\\n\"; --curR; }\n        while (curC < tc) { cout << \"R\\n\"; ++curC; }\n        while (curC > tc) { cout << \"L\\n\"; --curC; }\n    };\n    \n    while (!pos.empty() || !neg.empty()) {\n        if (load == 0) {\n            // find nearest positive cell\n            int best = -1, bestDist = INT_MAX;\n            for (int i = 0; i < (int)pos.size(); ++i) {\n                int d = abs(pos[i].r - curR) + abs(pos[i].c - curC);\n                if (d < bestDist) {\n                    bestDist = d;\n                    best = i;\n                }\n            }\n            // move there and load\n            move_to(pos[best].r, pos[best].c);\n            load = pos[best].amt;\n            cout << \"+\" << load << \"\\n\";\n            // remove this cell\n            pos[best] = pos.back();\n            pos.pop_back();\n        } else {\n            // we have load, go to nearest negative cell\n            int best = -1, bestDist = INT_MAX;\n            for (int i = 0; i < (int)neg.size(); ++i) {\n                int d = abs(neg[i].r - curR) + abs(neg[i].c - curC);\n                if (d < bestDist) {\n                    bestDist = d;\n                    best = i;\n                }\n            }\n            // move there\n            move_to(neg[best].r, neg[best].c);\n            int need = neg[best].amt;\n            int d = (int)min<long long>(load, need);\n            cout << \"-\" << d << \"\\n\";\n            load -= d;\n            need -= d;\n            if (need == 0) {\n                // finished this negative cell\n                neg[best] = neg.back();\n                neg.pop_back();\n            } else {\n                neg[best].amt = need;   // still needs more soil\n            }\n        }\n    }\n    // At this point load == 0 and all heights are zero.\n    return 0;\n}","ahc035":"#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, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    const int SEED_CNT = 2 * N * (N - 1);          // 60 for N = 6\n    const int BOARD = N * N;                      // 36\n\n    // store the current seed vectors\n    vector<vector<int>> seed(SEED_CNT, vector<int>(M));\n\n    // read the initial seeds\n    for (int i = 0; i < SEED_CNT; ++i)\n        for (int j = 0; j < M; ++j)\n            cin >> seed[i][j];\n\n    for (int turn = 0; turn < T; ++turn) {\n        // ----------- choose the best BOARD seeds ----------\n        vector<pair<int,int>> order;                // (value, id)\n        order.reserve(SEED_CNT);\n        for (int id = 0; id < SEED_CNT; ++id) {\n            long long sum = 0;\n            for (int l = 0; l < M; ++l) sum += seed[id][l];\n            order.emplace_back(static_cast<int>(sum), id);\n        }\n        sort(order.begin(), order.end(),\n             [](const auto& a, const auto& b){ return a.first > b.first; });\n\n        // take the first BOARD ids\n        vector<int> chosen;\n        chosen.reserve(BOARD);\n        for (int i = 0; i < BOARD; ++i) chosen.push_back(order[i].second);\n\n        // ----------- output the placement (row\u2011major) ----------\n        int idx = 0;\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                if (j) cout << ' ';\n                cout << chosen[idx++];\n            }\n            cout << '\\n';\n        }\n        cout.flush();\n\n        // ----------- read the next generation of seeds ----------\n        for (int i = 0; i < SEED_CNT; ++i)\n            for (int j = 0; j < M; ++j)\n                cin >> seed[i][j];\n    }\n    return 0;\n}","ahc038":"#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, V;\n    if (!(cin >> N >> M >> V)) return 0;\n    string line;\n    // read initial grid\n    for (int i = 0; i < N; ++i) cin >> line;\n    // read target grid\n    for (int i = 0; i < N; ++i) cin >> line;\n\n    // ----- construct a trivial robot arm -----\n    // V' = 1 (only the root)\n    cout << 1 << \"\\n\";\n    // no parent/length lines because there are no other vertices\n    // root position (any cell inside the grid, choose (0,0))\n    cout << 0 << \" \" << 0 << \"\\n\";\n\n    // No turns are printed (empty sequence)\n    // program ends here\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    if (!(cin >> N)) return 0;\n    const int M = 2 * N;\n    vector<pair<int,int>> sardines; sardines.reserve(N);\n    \n    // bounding box of all mackerels\n    int minX = 100000, maxX = 0, minY = 100000, maxY = 0;\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        if (i < N) {                 // mackerel\n            if (x < minX) minX = x;\n            if (x > maxX) maxX = x;\n            if (y < minY) minY = y;\n            if (y > maxY) maxY = y;\n        } else {                     // sardine\n            sardines.emplace_back(x, y);\n        }\n    }\n\n    // guarantee a real rectangle (non\u2011zero area)\n    if (minX == maxX) ++maxX;\n    if (minY == maxY) ++maxY;\n\n    // count sardines inside the rectangle\n    long long b = 0;\n    for (auto [x, y] : sardines) {\n        if (minX <= x && x <= maxX && minY <= y && y <= maxY) ++b;\n    }\n\n    // Output the rectangle (clockwise order)\n    cout << 4 << '\\n';\n    cout << minX << ' ' << minY << '\\n';\n    cout << maxX << ' ' << minY << '\\n';\n    cout << maxX << ' ' << maxY << '\\n';\n    cout << minX << ' ' << maxY << '\\n';\n    // (the score that the judge will compute is max(0, N - b + 1))\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    long long sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n\n    vector<long long> w(N), h(N);\n    for (int i = 0; i < N; ++i) cin >> w[i] >> h[i];   // observed sizes\n\n    // ----- decide between horizontal (U) and vertical (L) line -----\n    // Horizontal line: height = max of min(w,h), width = sum of max(w,h)\n    long long horiz_width = 0, horiz_height = 0;\n    vector<int> rot_h(N);   // 1 = rotate (swap), 0 = keep\n    for (int i = 0; i < N; ++i) {\n        if (w[i] <= h[i]) {          // keep orientation\n            rot_h[i] = 0;\n            horiz_width += w[i];\n            horiz_height = max(horiz_height, h[i]);\n        } else {                     // rotate to make height smaller\n            rot_h[i] = 1;\n            horiz_width += h[i];\n            horiz_height = max(horiz_height, w[i]);\n        }\n    }\n\n    // Vertical line: width = max of min(w,h), height = sum of max(w,h)\n    long long vert_width = 0, vert_height = 0;\n    vector<int> rot_v(N);\n    for (int i = 0; i < N; ++i) {\n        if (w[i] <= h[i]) {          // keep\n            rot_v[i] = 0;\n            vert_height += h[i];\n            vert_width = max(vert_width, w[i]);\n        } else {                     // rotate\n            rot_v[i] = 1;\n            vert_height += w[i];\n            vert_width = max(vert_width, h[i]);\n        }\n    }\n\n    bool use_horizontal = (horiz_width + horiz_height) <= (vert_width + vert_height);\n    // ---------------------------------------------------------------\n\n    for (int turn = 0; turn < T; ++turn) {\n        // output placement\n        cout << N << '\\n';\n        for (int i = 0; i < N; ++i) {\n            int r = use_horizontal ? rot_h[i] : rot_v[i];\n            char d = use_horizontal ? 'U' : 'L';\n            int b = (i == 0 ? -1 : i - 1);\n            cout << i << ' ' << r << ' ' << d << ' ' << b << '\\n';\n        }\n        cout.flush();\n\n        // read judge's measurement (unused)\n        long long Wp, Hp;\n        if (!(cin >> Wp >> Hp)) return 0;\n        (void)Wp; (void)Hp;\n    }\n    return 0;\n}","ahc041":"#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, H;\n    if (!(cin >> N >> M >> H)) return 0;\n    \n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n    \n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    \n    // coordinates are irrelevant for the algorithm, just read them\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        (void)x; (void)y;\n    }\n    \n    // parent array, -1 means root\n    vector<int> parent(N, -1);\n    vector<int> depth(N, -1);\n    vector<char> assigned(N, 0);\n    \n    // max\u2011heap of (beauty, vertex)\n    priority_queue<pair<int,int>> pq;\n    for (int v = 0; v < N; ++v) pq.emplace(A[v], v);\n    \n    while (true) {\n        // find next unassigned vertex with maximal beauty\n        int root = -1;\n        while (!pq.empty()) {\n            auto [val, v] = pq.top(); pq.pop();\n            if (!assigned[v]) {\n                root = v;\n                break;\n            }\n        }\n        if (root == -1) break;            // all vertices are assigned\n        \n        // start a new tree with this root\n        parent[root] = -1;\n        depth[root] = 0;\n        assigned[root] = 1;\n        queue<int> q;\n        q.push(root);\n        \n        while (!q.empty()) {\n            int cur = q.front(); q.pop();\n            int d = depth[cur];\n            if (d == H) continue;   // cannot go deeper\n            for (int nb : adj[cur]) {\n                if (!assigned[nb]) {\n                    parent[nb] = cur;\n                    depth[nb] = d + 1;\n                    assigned[nb] = 1;\n                    q.push(nb);\n                }\n            }\n        }\n    }\n    \n    // output parent list\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << parent[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 20;\n    vector<string> g(N);\n    for (int i = 0; i < N; ++i) cin >> g[i];\n\n    struct Op { char d; int p; };\n    vector<Op> ans;\n\n    // collect all Oni positions\n    vector<pair<int,int>> oni;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (g[i][j] == 'x') oni.emplace_back(i, j);\n\n    for (auto [i, j] : oni) {\n        // check freedom in four directions\n        bool freeU = true, freeD = true, freeL = true, freeR = true;\n        for (int ii = 0; ii < i; ++ii) if (g[ii][j] == 'o') freeU = false;\n        for (int ii = i+1; ii < N; ++ii) if (g[ii][j] == 'o') freeD = false;\n        for (int jj = 0; jj < j; ++jj) if (g[i][jj] == 'o') freeL = false;\n        for (int jj = j+1; jj < N; ++jj) if (g[i][jj] == 'o') freeR = false;\n\n        // distances to the corresponding edge\n        int du = i + 1;\n        int dd = N - i;\n        int dl = j + 1;\n        int dr = N - j;\n\n        // choose the free direction with minimal distance\n        int bestDist = INT_MAX;\n        char dir = '?';\n        if (freeU && du < bestDist) { bestDist = du; dir = 'U'; }\n        if (freeD && dd < bestDist) { bestDist = dd; dir = 'D'; }\n        if (freeL && dl < bestDist) { bestDist = dl; dir = 'L'; }\n        if (freeR && dr < bestDist) { bestDist = dr; dir = 'R'; }\n\n        // apply the two opposite shifts\n        if (dir == 'U') {\n            for (int k = 0; k < du; ++k) ans.push_back({'U', j});\n            for (int k = 0; k < du; ++k) ans.push_back({'D', j});\n        } else if (dir == 'D') {\n            for (int k = 0; k < dd; ++k) ans.push_back({'D', j});\n            for (int k = 0; k < dd; ++k) ans.push_back({'U', j});\n        } else if (dir == 'L') {\n            for (int k = 0; k < dl; ++k) ans.push_back({'L', i});\n            for (int k = 0; k < dl; ++k) ans.push_back({'R', i});\n        } else if (dir == 'R') {\n            for (int k = 0; k < dr; ++k) ans.push_back({'R', i});\n            for (int k = 0; k < dr; ++k) ans.push_back({'L', i});\n        }\n        // after this Oni is considered removed; we do not modify g\n    }\n\n    for (auto [c, p] : ans) {\n        cout << c << ' ' << p << '\\n';\n    }\n    return 0;\n}","ahc044":"#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    long long L;\n    if (!(cin >> N >> L)) return 0;\n    vector<long long> T(N);\n    for (int i = 0; i < N; ++i) cin >> T[i];   // not used\n    \n    for (int i = 0; i < N; ++i) {\n        int nxt = (i + 1) % N;\n        cout << nxt << ' ' << nxt << \"\\n\";\n    }\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\n// ------------------------------------------------------------\n// Hilbert order for 2\u2011D points (0 \u2264 x, y < 2^k)\n// Implementation from AtCoder Library (ACL) style\n// ------------------------------------------------------------\nusing int64 = long long;\n\n// rotate/flip a quadrant appropriately\nstatic inline void rot(int n, int &x, int &y, int rx, int ry) {\n    if (ry == 0) {\n        if (rx == 1) {\n            x = n - 1 - x;\n            y = n - 1 - y;\n        }\n        // swap x and y\n        std::swap(x, y);\n    }\n}\n\n// return Hilbert order of (x, y) with grid size 2^k (k up to 14 here)\nstatic inline uint64_t hilbertOrder(int x, int y) {\n    const int LOG = 14;                 // because coordinates \u2264 10000 < 2^14\n    uint64_t d = 0;\n    int s = 1 << (LOG - 1);\n    for (int i = LOG; i > 0; --i) {\n        int rx = (x & s) > 0;\n        int ry = (y & s) > 0;\n        d <<= 2;\n        d |= (uint64_t)(rx * 3 ^ ry);\n        rot(s, x, y, rx, ry);\n        s >>= 1;\n    }\n    return d;\n}\n\n// ------------------------------------------------------------\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    vector<int> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cx[i] = (lx + rx) / 2;          // centre approximation\n        cy[i] = (ly + ry) / 2;\n    }\n\n    // compute Hilbert order for each city\n    vector<uint64_t> ord(N);\n    for (int i = 0; i < N; ++i) ord[i] = hilbertOrder(cx[i], cy[i]);\n\n    // ids = 0..N-1 sorted by Hilbert order\n    vector<int> ids(N);\n    iota(ids.begin(), ids.end(), 0);\n    sort(ids.begin(), ids.end(),\n         [&](int a, int b) { return ord[a] < ord[b]; });\n\n    // ------------------------------------------------------------\n    // output answer (no queries are used)\n    cout << \"!\\n\";\n\n    int pos = 0;                         // next unused position in ids\n    for (int g = 0; g < M; ++g) {\n        int sz = G[g];\n        vector<int> group;\n        group.reserve(sz);\n        for (int i = 0; i < sz; ++i) {\n            group.push_back(ids[pos++]);\n        }\n\n        // list of cities belonging to this group\n        for (int i = 0; i < sz; ++i) {\n            if (i) cout << ' ';\n            cout << group[i];\n        }\n        cout << '\\n';\n\n        // a simple spanning tree: a path inside the group\n        for (int i = 1; i < sz; ++i) {\n            cout << group[i - 1] << ' ' << group[i] << '\\n';\n        }\n    }\n    return 0;\n}","ahc046":"#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    if (!(cin >> N >> M)) return 0;\n    vector<pair<int,int>> p(M);\n    for (int i = 0; i < M; ++i) cin >> p[i].first >> p[i].second;\n\n    int cur_i = p[0].first;\n    int cur_j = p[0].second;\n\n    // store output lines to print at the end (optional)\n    vector<string> out;\n\n    for (int t = 1; t < M; ++t) {\n        int ti = p[t].first;\n        int tj = p[t].second;\n\n        // vertical moves\n        while (cur_i < ti) {\n            out.emplace_back(\"M D\");\n            ++cur_i;\n        }\n        while (cur_i > ti) {\n            out.emplace_back(\"M U\");\n            --cur_i;\n        }\n        // horizontal moves\n        while (cur_j < tj) {\n            out.emplace_back(\"M R\");\n            ++cur_j;\n        }\n        while (cur_j > tj) {\n            out.emplace_back(\"M L\");\n            --cur_j;\n        }\n    }\n\n    for (const auto& s : out) cout << s << '\\n';\n    return 0;\n}"},"4":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int x, y;\n    long long r;\n};\n\nstruct Rect {\n    int x0, y0, x1, y1;               // [x0,x1) \u00d7 [y0,y1)\n};\n\nint n;\nvector<Company> comp;\nvector<array<int,4>> answer;\n\n/*--------------------------------------------------------------*/\n\nvoid solve(const vector<int>& ids, const Rect& cur) {\n    if (ids.size() == 1) {\n        int i = ids[0];\n        answer[i] = {cur.x0, cur.y0, cur.x1, cur.y1};\n        return;\n    }\n\n    // total requested area of this group\n    long long total = 0;\n    for (int i : ids) total += comp[i].r;\n\n    // ---------- try vertical split ----------\n    if (cur.x1 - cur.x0 >= 2) {\n        vector<int> order = ids;\n        sort(order.begin(), order.end(),\n             [&](int a, int b){ return comp[a].x < comp[b].x; });\n\n        // find split index (closest to half total area)\n        long long pref = 0;\n        int splitIdx = 0;\n        for (int k = 0; k < (int)order.size(); ++k) {\n            pref += comp[order[k]].r;\n            if (pref * 2 >= total) { splitIdx = k + 1; break; }\n        }\n        if (splitIdx == 0) splitIdx = 1;\n        if (splitIdx == (int)order.size()) splitIdx = (int)order.size() - 1;\n\n        vector<int> left(order.begin(), order.begin() + splitIdx);\n        vector<int> right(order.begin() + splitIdx, order.end());\n\n        // limits forced by the points\n        int maxX = -1, minX = 10000;\n        for (int i : left)  maxX = max(maxX, comp[i].x);\n        for (int i : right) minX = min(minX, comp[i].x);\n\n        // ideal split proportional to area\n        long long leftArea = 0;\n        for (int i : left) leftArea += comp[i].r;\n        int w = cur.x1 - cur.x0;\n        int splitCoord = cur.x0 + int( ( (__int128)w * leftArea + total/2 ) / total );\n\n        // enforce point\u2011containment constraints\n        splitCoord = max(splitCoord, maxX + 1);\n        splitCoord = min(splitCoord, minX);\n\n        if (splitCoord > cur.x0 && splitCoord < cur.x1 && maxX + 1 <= minX) {\n            Rect leftR  {cur.x0, cur.y0, splitCoord, cur.y1};\n            Rect rightR {splitCoord, cur.y0, cur.x1, cur.y1};\n            solve(left,  leftR);\n            solve(right, rightR);\n            return;\n        }\n    }\n\n    // ---------- try horizontal split ----------\n    if (cur.y1 - cur.y0 >= 2) {\n        vector<int> order = ids;\n        sort(order.begin(), order.end(),\n             [&](int a, int b){ return comp[a].y < comp[b].y; });\n\n        long long pref = 0;\n        int splitIdx = 0;\n        for (int k = 0; k < (int)order.size(); ++k) {\n            pref += comp[order[k]].r;\n            if (pref * 2 >= total) { splitIdx = k + 1; break; }\n        }\n        if (splitIdx == 0) splitIdx = 1;\n        if (splitIdx == (int)order.size()) splitIdx = (int)order.size() - 1;\n\n        vector<int> top(order.begin(), order.begin() + splitIdx);\n        vector<int> bottom(order.begin() + splitIdx, order.end());\n\n        int maxY = -1, minY = 10000;\n        for (int i : top)    maxY = max(maxY, comp[i].y);\n        for (int i : bottom) minY = min(minY, comp[i].y);\n\n        long long topArea = 0;\n        for (int i : top) topArea += comp[i].r;\n        int h = cur.y1 - cur.y0;\n        int splitCoord = cur.y0 + int( ( (__int128)h * topArea + total/2 ) / total );\n\n        splitCoord = max(splitCoord, maxY + 1);\n        splitCoord = min(splitCoord, minY);\n\n        if (splitCoord > cur.y0 && splitCoord < cur.y1 && maxY + 1 <= minY) {\n            Rect topR    {cur.x0, cur.y0, cur.x1, splitCoord};\n            Rect bottomR {cur.x0, splitCoord, cur.x1, cur.y1};\n            solve(top,    topR);\n            solve(bottom, bottomR);\n            return;\n        }\n    }\n\n    /* ---------- fallback (very rare) ---------- */\n    // Give the whole region to the first company, tiny 1\u00d71 cells to the rest\n    int first = ids[0];\n    answer[first] = {cur.x0, cur.y0, cur.x1, cur.y1};\n\n    int w = cur.x1 - cur.x0;\n    int h = cur.y1 - cur.y0;\n    if (w == 0) w = 1;\n    if (h == 0) h = 1;\n    for (size_t k = 1; k < ids.size(); ++k) {\n        int i = ids[k];\n        int xx = cur.x0 + (int)((k - 1) % w);\n        int yy = cur.y0 + (int)((k - 1) / w);\n        if (xx + 1 > cur.x1) xx = cur.x0;\n        if (yy + 1 > cur.y1) yy = cur.y0;\n        answer[i] = {xx, yy, xx + 1, yy + 1};\n    }\n}\n\n/*--------------------------------------------------------------*/\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> n)) return 0;\n    comp.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> comp[i].x >> comp[i].y >> comp[i].r;\n    }\n    answer.assign(n, {0,0,0,0});\n\n    vector<int> allIds(n);\n    iota(allIds.begin(), allIds.end(), 0);\n    Rect whole{0, 0, 10000, 10000};\n\n    solve(allIds, whole);\n\n    for (int i = 0; i < n; ++i) {\n        const auto &a = answer[i];\n        cout << a[0] << ' ' << a[1] << ' ' << a[2] << ' ' << a[3] << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 50;\n    int si, sj;\n    if (!(cin >> si >> sj)) return 0;\n\n    // ----- read tiles ----------------------------------------------------\n    int tile[N][N];\n    int maxTid = -1;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            cin >> tile[i][j];\n            maxTid = max(maxTid, tile[i][j]);\n        }\n\n    // ----- read values ----------------------------------------------------\n    int cellVal[N][N];\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) cin >> cellVal[i][j];\n\n    // ----- pre\u2011compute tile scores (sum of its cells) --------------------\n    vector<int> tileScore(maxTid + 1, 0);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            tileScore[tile[i][j]] += cellVal[i][j];\n\n    // direction data\n    const char dirs[4] = {'U','D','L','R'};\n    const int  di[4]   = {-1, 1, 0, 0};\n    const int  dj[4]   = { 0, 0,-1, 1};\n\n    // random generator\n    std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_real_distribution<double> uni(0.0, 1.0);\n\n    const double alpha = 0.30;            // weight of future potential\n    const int   TIME_LIMIT_MS = 1850;    // leave a safety margin\n    const int   MAX_ITER   = 50000;      // upper bound, actual limited by time\n\n    // best answer over all walks\n    long long bestScore = -1;\n    string   bestPath;\n\n    auto startClock = chrono::high_resolution_clock::now();\n\n    for (int iter = 0; iter < MAX_ITER; ++iter) {\n        // time check\n        if (chrono::duration_cast<chrono::milliseconds>(\n                chrono::high_resolution_clock::now() - startClock).count()\n            > TIME_LIMIT_MS) break;\n\n        vector<char> used(maxTid + 1, 0);\n        int ci = si, cj = sj;\n        int curTid = tile[ci][cj];\n        used[curTid] = 1;\n        long long curScore = tileScore[curTid];\n        string curPath;\n\n        while (true) {\n            // collect candidates\n            struct Cand { int ni, nj, tid; double weight; char dir; };\n            vector<Cand> cand;\n            for (int d = 0; d < 4; ++d) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int tid = tile[ni][nj];\n                if (used[tid]) continue;\n\n                // future best neighbour of this candidate\n                int futureBest = 0;\n                for (int d2 = 0; d2 < 4; ++d2) {\n                    int ni2 = ni + di[d2];\n                    int nj2 = nj + dj[d2];\n                    if (ni2 < 0 || ni2 >= N || nj2 < 0 || nj2 >= N) continue;\n                    int tid2 = tile[ni2][nj2];\n                    if (used[tid2] || tid2 == tid) continue;\n                    futureBest = max(futureBest, tileScore[tid2]);\n                }\n\n                double w = tileScore[tid] + alpha * futureBest;\n                cand.push_back({ni, nj, tid, w, dirs[d]});\n            }\n\n            if (cand.empty()) break; // dead end\n\n            // choose randomly proportional to weight\n            double total = 0.0;\n            for (auto &c : cand) total += c.weight;\n            double r = uni(rng) * total;\n            double acc = 0.0;\n            int chosen = 0;\n            for (int i = 0; i < (int)cand.size(); ++i) {\n                acc += cand[i].weight;\n                if (r <= acc) { chosen = i; break; }\n            }\n\n            // perform move\n            const Cand &c = cand[chosen];\n            curPath.push_back(c.dir);\n            ci = c.ni; cj = c.nj;\n            used[c.tid] = 1;\n            curScore += tileScore[c.tid];\n        }\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestPath = curPath;\n        }\n    }\n\n    cout << bestPath << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Edge {\n    int to;   // neighbour vertex id\n    int id;   // unique edge id (0 \u2026 E-1)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int H = 30, W = 30;\n    const int V = H * W;\n    const int E = (H * (W - 1)) + ((H - 1) * W);   // total undirected edges\n\n    // ---------- build graph ----------\n    vector<vector<Edge>> g(V);\n    auto idx = [&](int i, int j) { return i * W + j; };\n    int eid = 0;\n    for (int i = 0; i < H; ++i) {\n        for (int j = 0; j < W - 1; ++j) {\n            int a = idx(i, j);\n            int b = idx(i, j + 1);\n            g[a].push_back({b, eid});\n            g[b].push_back({a, eid});\n            ++eid;\n        }\n    }\n    for (int i = 0; i < H - 1; ++i) {\n        for (int j = 0; j < W; ++j) {\n            int a = idx(i, j);\n            int b = idx(i + 1, j);\n            g[a].push_back({b, eid});\n            g[b].push_back({a, eid});\n            ++eid;\n        }\n    }\n    assert(eid == E);\n\n    // ---------- learning data ----------\n    vector<long double> total(E, 0.0L);\n    vector<int>        cnt(E, 0);\n    vector<long double> weight(E, 1.0L);   // initial guess\n\n    const int Q = 1000;\n    for (int q = 0; q < Q; ++q) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) break;\n        int s = idx(si, sj);\n        int t = idx(ti, tj);\n\n        // ---------- Dijkstra ----------\n        const long double INF = 1e100L;\n        vector<long double> dist(V, INF);\n        vector<int>    prev_v(V, -1);\n        vector<char>   prev_dir(V, 0);\n\n        using State = pair<long double, int>;\n        priority_queue<State, vector<State>, greater<State>> pq;\n        dist[s] = 0;\n        pq.emplace(0.0L, s);\n\n        while (!pq.empty()) {\n            auto [d, v] = pq.top(); pq.pop();\n            if (d != dist[v]) continue;\n            if (v == t) break;\n            for (const auto &e : g[v]) {\n                long double w = weight[e.id];\n                if (dist[e.to] > d + w) {\n                    dist[e.to] = d + w;\n                    prev_v[e.to] = v;\n                    int vi = v / W, vj = v % W;\n                    int ti2 = e.to / W, tj2 = e.to % W;\n                    char dir = '?';\n                    if (ti2 == vi - 1) dir = 'U';\n                    else if (ti2 == vi + 1) dir = 'D';\n                    else if (tj2 == vj - 1) dir = 'L';\n                    else if (tj2 == vj + 1) dir = 'R';\n                    prev_dir[e.to] = dir;\n                    pq.emplace(dist[e.to], e.to);\n                }\n            }\n        }\n\n        // ---------- reconstruct path ----------\n        string path_rev;\n        vector<int> used_edges;           // edge ids on the path\n        int cur = t;\n        while (cur != s) {\n            int p = prev_v[cur];\n            char dir = prev_dir[cur];\n            path_rev.push_back(dir);\n            // locate edge id between p and cur\n            int edge_used = -1;\n            for (const auto &e : g[p]) if (e.to == cur) { edge_used = e.id; break; }\n            used_edges.push_back(edge_used);\n            cur = p;\n        }\n        reverse(path_rev.begin(), path_rev.end());\n        reverse(used_edges.begin(), used_edges.end());\n\n        // ---------- output ----------\n        cout << path_rev << '\\n' << flush;\n\n        // ---------- read judge answer ----------\n        long long reported;\n        cin >> reported;                 // round(true_len * e_k)\n\n        // ---------- update learning ----------\n        int L = (int)used_edges.size();   // number of edges in this path, >=1\n        long double avg = (long double)reported / (long double)L; // unbiased per\u2011edge contribution\n        for (int id : used_edges) {\n            total[id] += avg;\n            ++cnt[id];\n            weight[id] = total[id] / cnt[id];\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Placement {\n    bool horiz;   // true = horizontal, false = vertical\n    int line;     // row (if horiz) or column (if vertical)\n    int start;    // starting column (if horiz) or row (if vertical)\n};\n\nint N = 20;\n\n/* check whether string s occurs as a subsequence in board (horizontal or vertical) */\nbool appears(const vector<string>& board, const string& s) {\n    int L = (int)s.size();\n    // rows\n    for (int r = 0; r < N; ++r) {\n        for (int start = 0; start < N; ++start) {\n            bool ok = true;\n            for (int p = 0; p < L; ++p) {\n                int c = (start + p) % N;\n                if (board[r][c] != s[p]) { ok = false; break; }\n            }\n            if (ok) return true;\n        }\n    }\n    // columns\n    for (int c = 0; c < N; ++c) {\n        for (int start = 0; start < N; ++start) {\n            bool ok = true;\n            for (int p = 0; p < L; ++p) {\n                int r = (start + p) % N;\n                if (board[r][c] != s[p]) { ok = false; break; }\n            }\n            if (ok) return true;\n        }\n    }\n    return false;\n}\n\n/* greedy construction, given an order of string indices, returns the built board */\nvector<string> greedy_build(const vector<string>& strs,\n                            const vector<int>& order,\n                            mt19937& rng) {\n    vector<string> board(N, string(N, '.'));\n\n    for (int idx : order) {\n        const string& s = strs[idx];\n        int L = (int)s.size();\n\n        Placement bestPl{};\n        int bestGain = -1;\n        vector<Placement> candidates;   // keep all with maximal gain for random tie\u2011break\n\n        for (int orient = 0; orient < 2; ++orient) {\n            bool horiz = (orient == 0);\n            for (int line = 0; line < N; ++line) {\n                for (int start = 0; start < N; ++start) {\n                    bool ok = true;\n                    int gain = 0;\n                    for (int p = 0; p < L; ++p) {\n                        int i = horiz ? line : (start + p) % N;\n                        int j = horiz ? (start + p) % N : line;\n                        char cur = board[i][j];\n                        if (cur != '.' && cur != s[p]) { ok = false; break; }\n                        if (cur == '.') ++gain;\n                    }\n                    if (!ok) continue;\n                    if (gain > bestGain) {\n                        bestGain = gain;\n                        candidates.clear();\n                        candidates.push_back({horiz, line, start});\n                    } else if (gain == bestGain) {\n                        candidates.push_back({horiz, line, start});\n                    }\n                }\n            }\n        }\n        if (candidates.empty()) continue;          // cannot place this string\n        uniform_int_distribution<int> dst(0, (int)candidates.size() - 1);\n        Placement pl = candidates[dst(rng)];        // random tie\u2011break\n\n        // write the string\n        for (int p = 0; p < L; ++p) {\n            int i = pl.horiz ? pl.line : (pl.start + p) % N;\n            int j = pl.horiz ? (pl.start + p) % N : pl.line;\n            board[i][j] = s[p];\n        }\n    }\n\n    // fill remaining '.' with random letters\n    uniform_int_distribution<int> ld(0, 7);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (board[i][j] == '.') board[i][j] = char('A' + ld(rng));\n\n    return board;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int M;\n    if (!(cin >> N >> M)) return 0;          // N is always 20\n    vector<string> strs(M);\n    for (int i = 0; i < M; ++i) cin >> strs[i];\n\n    // prepare a static order: longer strings first\n    vector<int> baseOrder(M);\n    iota(baseOrder.begin(), baseOrder.end(), 0);\n    sort(baseOrder.begin(), baseOrder.end(),\n         [&](int a, int b) { return strs[a].size() > strs[b].size(); });\n\n    random_device rd;\n    mt19937 rng(rd());\n\n    vector<string> bestBoard;\n    int bestScore = -1;\n\n    const auto deadline = chrono::steady_clock::now() + chrono::milliseconds(2800); // safety margin\n\n    while (chrono::steady_clock::now() < deadline) {\n        // random shuffle of strings with same length groups to obtain diversity\n        vector<int> order = baseOrder;\n        // small random swaps inside groups of equal length\n        for (size_t i = 0; i + 1 < order.size(); ++i) {\n            if (strs[order[i]].size() == strs[order[i+1]].size()) {\n                if (uniform_int_distribution<int>(0, 1)(rng)) swap(order[i], order[i+1]);\n            }\n        }\n\n        vector<string> board = greedy_build(strs, order, rng);\n\n        // evaluate score\n        int cnt = 0;\n        for (const string& s : strs) if (appears(board, s)) ++cnt;\n\n        if (cnt > bestScore) {\n            bestScore = cnt;\n            bestBoard = std::move(board);\n        }\n    }\n\n    // output the best board found\n    for (const string& row : bestBoard) cout << row << '\\n';\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell { int i, j; };\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, si, sj;\n    if (!(cin >> N >> si >> sj)) return 0;\n    vector<string> g(N);\n    for (int i = 0; i < N; ++i) cin >> g[i];\n\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char moveChar[4] = {'U', 'D', 'L', 'R'};\n\n    // map coordinate -> index\n    vector<vector<int>> idx(N, vector<int>(N, -1));\n    vector<Cell> cells;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (g[i][j] != '#') {\n                idx[i][j] = (int)cells.size();\n                cells.push_back({i, j});\n            }\n\n    int V = cells.size();\n    if (V == 0) { cout << \"\\n\"; return 0; }\n\n    // adjacency (only needed for BFS)\n    vector<vector<int>> adj(V);\n    for (int v = 0; v < V; ++v) {\n        int i = cells[v].i, j = cells[v].j;\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + di[d], nj = j + dj[d];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (g[ni][nj] == '#') continue;\n            int u = idx[ni][nj];\n            adj[v].push_back(u);\n        }\n    }\n\n    // helper: BFS from src to the nearest target satisfying predicate `ok`\n    auto bfs_path = [&](int src, const vector<char>& target) {\n        vector<int> pre(V, -1);\n        vector<char> preDir(V, -1);\n        queue<int> q;\n        q.push(src);\n        pre[src] = src;\n        while (!q.empty()) {\n            int v = q.front(); q.pop();\n            if (target[v]) break;               // reached a desired cell\n            int i = cells[v].i, j = cells[v].j;\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d], nj = j + dj[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                if (g[ni][nj] == '#') continue;\n                int u = idx[ni][nj];\n                if (pre[u] != -1) continue;\n                pre[u] = v;\n                preDir[u] = d;                  // direction from v to u\n                q.push(u);\n            }\n        }\n        // locate the first target reached (could be src itself)\n        int targetIdx = -1;\n        for (int v = 0; v < V; ++v)\n            if (target[v] && pre[v] != -1) { targetIdx = v; break; }\n\n        // reconstruct path (list of moves)\n        string path;\n        if (targetIdx == -1) return path;   // should not happen\n        int cur = targetIdx;\n        while (cur != src) {\n            char d = preDir[cur];\n            path.push_back(moveChar[d]);\n            cur = pre[cur];\n        }\n        reverse(path.begin(), path.end());\n        // also return the endpoint index via a static variable (or capture)\n        // but we need both path and endpoint, so we will return pair\n        // We'll wrap this lambda later; for now, just return path\n        return path;\n    };\n\n    // Because we also need the endpoint after reconstruction,\n    // rewrite bfs to return both path string and endpoint index.\n    struct BfsResult {\n        string path;\n        int endIdx;\n    };\n    auto bfs = [&](int src, const vector<char>& target) -> BfsResult {\n        vector<int> pre(V, -1);\n        vector<char> preDir(V, -1);\n        queue<int> q;\n        q.push(src);\n        pre[src] = src;\n        int found = -1;\n        while (!q.empty()) {\n            int v = q.front(); q.pop();\n            if (target[v]) { found = v; break; }\n            int i = cells[v].i, j = cells[v].j;\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d], nj = j + dj[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                if (g[ni][nj] == '#') continue;\n                int u = idx[ni][nj];\n                if (pre[u] != -1) continue;\n                pre[u] = v;\n                preDir[u] = d;\n                q.push(u);\n            }\n        }\n        string path;\n        int endIdx = src;\n        if (found != -1) {\n            endIdx = found;\n            int cur = found;\n            while (cur != src) {\n                char d = preDir[cur];\n                path.push_back(moveChar[d]);\n                cur = pre[cur];\n            }\n            reverse(path.begin(), path.end());\n        }\n        return {path, endIdx};\n    };\n\n    // -----------------------------------------------------------------\n    // Main heuristic tour\n    vector<char> covered(V, 0);\n    int startIdx = idx[si][sj];\n    covered[startIdx] = 1;                       // start cell already visited\n    int remaining = V - 1;\n\n    int curIdx = startIdx;\n    string answer;\n\n    while (remaining > 0) {\n        // build target mask: any uncovered cell\n        vector<char> target(V, 0);\n        for (int v = 0; v < V; ++v) if (!covered[v]) target[v] = 1;\n\n        BfsResult bfsRes = bfs(curIdx, target);\n        // append path\n        answer += bfsRes.path;\n        // mark all cells on the path as covered\n        int walk = curIdx;\n        for (char c : bfsRes.path) {\n            // move according to c\n            int d = (c == 'U') ? 0 : (c == 'D') ? 1 : (c == 'L') ? 2 : 3;\n            int ni = cells[walk].i + di[d];\n            int nj = cells[walk].j + dj[d];\n            walk = idx[ni][nj];\n            if (!covered[walk]) {\n                covered[walk] = 1;\n                --remaining;\n            }\n        }\n        curIdx = bfsRes.endIdx;\n    }\n\n    // finally return to start\n    if (curIdx != startIdx) {\n        vector<char> target(V, 0);\n        target[startIdx] = 1;\n        BfsResult bfsRes = bfs(curIdx, target);\n        answer += bfsRes.path;\n        // (no need to update covered any more)\n    }\n\n    cout << answer << '\\n';\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K, R;\n    if (!(cin >> N >> M >> K >> R)) return 0;\n\n    // required skill vectors \u2013 not used by the algorithm\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) cin >> d[i][j];\n\n    // build DAG\n    vector<vector<int>> out(N);\n    vector<int> indeg(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;  cin >> u >> v;\n        --u; --v;\n        out[u].push_back(v);\n        ++indeg[v];\n    }\n\n    // task states\n    vector<int> task_state(N, -1);          // -1 not started, 0 started, 1 finished\n    deque<int> ready;\n    for (int i = 0; i < N; ++i) if (indeg[i] == 0) ready.push_back(i);\n\n    // member data\n    vector<int> member_task(M, -1);                 // current task ( -1 = idle )\n    vector<int> start_day(M, -1);                  // day when current task started\n    vector<double> avg_days(M, 1e9);                // estimated average duration\n    vector<int> cnt_done(M, 0);                    // number of completed tasks\n\n    int day = 0;\n    while (true) {\n        ++day;\n\n        // ----------- assignment phase ----------\n        vector<int> idle;\n        for (int j = 0; j < M; ++j) if (member_task[j] == -1) idle.push_back(j);\n        sort(idle.begin(), idle.end(),\n             [&](int a, int b){ return avg_days[a] < avg_days[b]; });\n\n        vector<pair<int,int>> assign;   // (member, task)\n        size_t p = 0;\n        while (p < idle.size() && !ready.empty()) {\n            int j = idle[p];\n            int t = ready.front(); ready.pop_front();\n            member_task[j] = t;\n            start_day[j] = day;\n            task_state[t] = 0;\n            assign.emplace_back(j, t);\n            ++p;\n        }\n\n        // output\n        cout << assign.size();\n        for (auto [mem, tas] : assign) {\n            cout << ' ' << mem + 1 << ' ' << tas + 1;\n        }\n        cout << '\\n';\n        cout.flush();\n\n        // ----------- read judge reply ----------\n        string line;\n        if (!getline(cin, line)) break;\n        while (line.size() && (line.back() == '\\r' || line.back() == '\\n')) line.pop_back();\n        if (line.empty()) {                     // consume possible empty line after previous >>\n            if (!getline(cin, line)) break;\n            while (line.size() && (line.back() == '\\r' || line.back() == '\\n')) line.pop_back();\n        }\n\n        if (line == \"-1\") break;                // finished / day limit\n\n        stringstream ss(line);\n        int cnt;\n        ss >> cnt;\n        vector<int> fin_members(cnt);\n        for (int i = 0; i < cnt; ++i) {\n            ss >> fin_members[i];\n            --fin_members[i];                   // to 0\u2011based\n        }\n\n        // process each finishing member\n        for (int j : fin_members) {\n            int t = member_task[j];\n            if (t == -1) continue;              // safety\n            int dur = day - start_day[j] + 1;    // inclusive\n            // update average duration\n            avg_days[j] = (avg_days[j] * cnt_done[j] + dur) / double(cnt_done[j] + 1);\n            ++cnt_done[j];\n\n            member_task[j] = -1;                // becomes idle\n            task_state[t] = 1;                  // finished\n\n            for (int nxt : out[t]) {\n                if (--indeg[nxt] == 0 && task_state[nxt] == -1) {\n                    ready.push_back(nxt);\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Order {\n    int a, b, c, d;\n};\n\ninline int manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n// total distance of the route that visits the orders in the given order\nlong long totalDistance(const vector<int>& ord,\n                        const vector<Order>& orders,\n                        const pair<int,int>& office) {\n    long long tot = 0;\n    int curx = office.first, cury = office.second;\n    for (int idx : ord) {\n        const Order& o = orders[idx];\n        tot += manhattan(curx, cury, o.a, o.b);\n        curx = o.a; cury = o.b;\n        tot += manhattan(curx, cury, o.c, o.d);\n        curx = o.c; cury = o.d;\n    }\n    tot += manhattan(curx, cury, office.first, office.second);\n    return tot;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const pair<int,int> office = {400, 400};\n\n    vector<Order> orders(1000);\n    for (auto &o : orders) {\n        cin >> o.a >> o.b >> o.c >> o.d;\n    }\n\n    // ----- 1. choose 50 cheapest orders (round\u2011trip cost) -----\n    vector<long long> roundCost(1000);\n    for (int i = 0; i < 1000; ++i) {\n        const auto& o = orders[i];\n        roundCost[i] = (long long)manhattan(office.first, office.second, o.a, o.b)\n                     + (long long)manhattan(o.a, o.b, o.c, o.d)\n                     + (long long)manhattan(o.c, o.d, office.first, office.second);\n    }\n\n    vector<int> idx(1000);\n    iota(idx.begin(), idx.end(), 0);\n    nth_element(idx.begin(), idx.begin() + 50, idx.end(),\n                [&](int i, int j){ return roundCost[i] < roundCost[j]; });\n    idx.resize(50);                     // now contains 50 cheapest indices\n\n    // ----- 2. initial ordering (by distance of pickup from office) -----\n    sort(idx.begin(), idx.end(),\n         [&](int i, int j){\n             const auto& oi = orders[i];\n             const auto& oj = orders[j];\n             int di = manhattan(office.first, office.second, oi.a, oi.b);\n             int dj = manhattan(office.first, office.second, oj.a, oj.b);\n             return di < dj;\n         });\n\n    // ----- 3. simple local search: random swaps of whole pairs -----\n    long long bestScore = totalDistance(idx, orders, office);\n    std::mt19937 rng((unsigned)chrono::high_resolution_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> distPos(0, 49);\n\n    const int ITER = 2000;\n    for (int it = 0; it < ITER; ++it) {\n        int p = distPos(rng);\n        int q = distPos(rng);\n        if (p == q) continue;\n        if (p > q) swap(p, q);\n        swap(idx[p], idx[q]);\n        long long cur = totalDistance(idx, orders, office);\n        if (cur < bestScore) {\n            bestScore = cur;               // keep swap\n        } else {\n            swap(idx[p], idx[q]);           // revert\n        }\n    }\n\n    // ----- 4. output -----\n    cout << 50;\n    for (int id : idx) cout << ' ' << (id + 1);   // convert to 1\u2011based\n    cout << '\\n';\n\n    // build the full route\n    vector<pair<int,int>> route;\n    route.emplace_back(office);               // start\n    for (int id : idx) {\n        const Order& o = orders[id];\n        route.emplace_back(o.a, o.b);         // pickup\n        route.emplace_back(o.c, o.d);         // delivery\n    }\n    route.emplace_back(office);               // return\n\n    cout << route.size();\n    for (auto [x, y] : route) cout << ' ' << x << ' ' << y;\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        if (p[x] == x) return x;\n        return p[x] = find(p[x]);\n    }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    const int N = 400;\n    const int M = 1995;\n    // read vertex coordinates (unused later)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        if(!(cin >> x >> y)) return 0;\n    }\n    // read edges\n    vector<int> u(M), v(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> u[i] >> v[i];\n    }\n    \n    DSU dsu(N);\n    for (int i = 0; i < M; ++i) {\n        long long li;\n        cin >> li;                 // true length, not needed for decision\n        if (dsu.find(u[i]) != dsu.find(v[i])) {\n            cout << \"1\\n\";\n            dsu.unite(u[i], v[i]);\n        } else {\n            cout << \"0\\n\";\n        }\n        cout.flush();             // mandatory after each answer\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos { int x, y; };\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<Pos> petPos(N);\n    vector<int> petType(N);\n    for (int i = 0; i < N; ++i) cin >> petPos[i].x >> petPos[i].y >> petType[i];\n\n    int M;\n    cin >> M;\n    vector<Pos> humanPos(M);\n    for (int i = 0; i < M; ++i) cin >> humanPos[i].x >> humanPos[i].y;\n\n    const int H = 30, W = 30;\n    // 0 = free, 1 = wall\n    vector<vector<int>> wall(H + 2, vector<int>(W + 2, 0));\n    // borders are treated as walls (impassable)\n    for (int i = 0; i <= H + 1; ++i) {\n        wall[i][0] = wall[i][W + 1] = 1;\n    }\n    for (int j = 0; j <= W + 1; ++j) {\n        wall[0][j] = wall[H + 1][j] = 1;\n    }\n\n    // helper to check inside board\n    auto inside = [&](int x, int y) {\n        return 1 <= x && x <= H && 1 <= y && y <= W;\n    };\n\n    // directions: U,D,L,R with corresponding delta\n    const string dirs = \"UDLR\";\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n\n    // for fast pet lookup on the grid\n    vector<vector<int>> petCnt(H + 2, vector<int>(W + 2, 0));\n    for (auto &p : petPos) petCnt[p.x][p.y]++;\n\n    for (int turn = 0; turn < 300; ++turn) {\n        string actions(M, '.');\n\n        // decide actions for each human\n        for (int i = 0; i < M; ++i) {\n            int hx = humanPos[i].x;\n            int hy = humanPos[i].y;\n            bool placed = false;\n            for (int d = 0; d < 4; ++d) {\n                int nx = hx + dx[d];\n                int ny = hy + dy[d];\n                if (!inside(nx, ny)) continue;\n                if (wall[nx][ny]) continue;            // already wall\n                if (petCnt[nx][ny] > 0) continue;      // pet stands there now\n                // check that none of the four neighbours of (nx,ny) contain a pet\n                bool adjPet = false;\n                for (int k = 0; k < 4; ++k) {\n                    int ax = nx + dx[k];\n                    int ay = ny + dy[k];\n                    if (!inside(ax, ay)) continue;\n                    if (petCnt[ax][ay] > 0) { adjPet = true; break; }\n                }\n                if (adjPet) continue;\n                // also cannot wall a cell that currently holds a human\n                bool otherHuman = false;\n                for (int j = 0; j < M; ++j) {\n                    if (j == i) continue;\n                    if (humanPos[j].x == nx && humanPos[j].y == ny) {\n                        otherHuman = true; break;\n                    }\n                }\n                if (otherHuman) continue;\n\n                // all checks passed \u2192 build wall\n                actions[i] = tolower(dirs[d]); // u/d/l/r\n                wall[nx][ny] = 1;\n                placed = true;\n                break;\n            }\n            // if no safe neighbour, action stays '.'\n            (void)placed;\n        }\n\n        // output actions\n        cout << actions << \"\\n\";\n        cout.flush();\n\n        // read pet movement strings and update positions\n        for (int i = 0; i < N; ++i) {\n            string moveStr;\n            cin >> moveStr;\n            // erase old count\n            petCnt[petPos[i].x][petPos[i].y]--;\n            // apply each step\n            for (char c : moveStr) {\n                if (c == '.') continue;\n                int md = -1;\n                if (c == 'U') md = 0;\n                else if (c == 'D') md = 1;\n                else if (c == 'L') md = 2;\n                else if (c == 'R') md = 3;\n                if (md != -1) {\n                    petPos[i].x += dx[md];\n                    petPos[i].y += dy[md];\n                }\n            }\n            // add new count\n            petCnt[petPos[i].x][petPos[i].y]++;\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Prev {\n    int pi, pj;\n    char mv;                 // move taken from predecessor to this cell\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj, ti, tj;\n    double p;\n    if (!(cin >> si >> sj >> ti >> tj >> p)) return 0;\n\n    const int N = 20;\n    vector<string> h(N);          // 20 strings, length 19\n    for (int i = 0; i < N; ++i) cin >> h[i];\n    vector<string> v(N - 1);      // 19 strings, length 20\n    for (int i = 0; i < N - 1; ++i) cin >> v[i];\n\n    // ---------- BFS ----------\n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    vector<vector<Prev>> pre(N, vector<Prev>(N, {-1, -1, '?'}));\n    queue<pair<int,int>> q;\n    dist[si][sj] = 0;\n    q.emplace(si, sj);\n\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        if (i == ti && j == tj) break;\n\n        // Up\n        if (i > 0 && v[i-1][j] == '0' && dist[i-1][j] == -1) {\n            dist[i-1][j] = dist[i][j] + 1;\n            pre[i-1][j] = {i, j, 'U'};\n            q.emplace(i-1, j);\n        }\n        // Down\n        if (i + 1 < N && v[i][j] == '0' && dist[i+1][j] == -1) {\n            dist[i+1][j] = dist[i][j] + 1;\n            pre[i+1][j] = {i, j, 'D'};\n            q.emplace(i+1, j);\n        }\n        // Left\n        if (j > 0 && h[i][j-1] == '0' && dist[i][j-1] == -1) {\n            dist[i][j-1] = dist[i][j] + 1;\n            pre[i][j-1] = {i, j, 'L'};\n            q.emplace(i, j-1);\n        }\n        // Right\n        if (j + 1 < N && h[i][j] == '0' && dist[i][j+1] == -1) {\n            dist[i][j+1] = dist[i][j] + 1;\n            pre[i][j+1] = {i, j, 'R'};\n            q.emplace(i, j+1);\n        }\n    }\n\n    // ---------- reconstruct shortest path ----------\n    string path;\n    int ci = ti, cj = tj;\n    while (!(ci == si && cj == sj)) {\n        Prev pr = pre[ci][cj];\n        path.push_back(pr.mv);\n        ci = pr.pi;\n        cj = pr.pj;\n    }\n    reverse(path.begin(), path.end());\n\n    if (path.empty()) {               // should never happen (start != target)\n        cout << \"U\\n\";\n        return 0;\n    }\n\n    // ---------- repeat to increase robustness ----------\n    const int MAXLEN = 200;\n    int repeat = MAXLEN / static_cast<int>(path.size());\n    string answer;\n    answer.reserve(repeat * path.size());\n\n    for (int i = 0; i < repeat; ++i) answer += path;\n\n    // optional: fill the remaining characters (not required)\n    int remaining = MAXLEN - static_cast<int>(answer.size());\n    if (remaining > 0) answer.append(path.substr(0, remaining));\n\n    cout << answer << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nconst int DIR = 4;\nconst int di[DIR] = {0, -1, 0, 1};\nconst int dj[DIR] = {-1, 0, 1, 0};\n\nint to0[8][DIR] = {\n    { 1, 0, -1, -1},\n    { 3,-1, -1,  0},\n    {-1,-1,  3,  2},\n    {-1, 2,  1, -1},\n    { 1, 0,  3,  2},\n    { 3, 2,  1,  0},\n    { 2,-1,  0, -1},\n    {-1, 3, -1,  1},\n};\n\nint to_rot[8][4][DIR];                 // [type][rotation][enter_dir] -> leave_dir or -1\n\nvoid build_rot() {\n    for (int t = 0; t < 8; ++t)\n        for (int r = 0; r < 4; ++r)\n            for (int d = 0; d < DIR; ++d) {\n                int d0 = (d - r + 4) % 4;               // direction in original orientation\n                int nd = to0[t][d0];\n                if (nd == -1) to_rot[t][r][d] = -1;\n                else           to_rot[t][r][d] = (nd + r) % 4;\n            }\n}\n\n/* --------------------------------------------------------------- */\n/*  compute L1 * L2  (0 if < 2 loops)                              */\n/* --------------------------------------------------------------- */\nint score_board(const vector<string>& tile,\n                const int rot[N][N]) {\n    static bool seen[N][N][DIR];\n    memset(seen, 0, sizeof(seen));\n    vector<int> loops;\n\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            for (int d = 0; d < DIR; ++d) {\n                if (seen[i][j][d]) continue;\n                int t = tile[i][j] - '0';\n                int r = rot[i][j];\n                if (to_rot[t][r][d] == -1) continue; // dead edge\n\n                int ci = i, cj = j, cd = d;\n                int len = 0;\n                bool broken = false;\n                while (true) {\n                    int ct = tile[ci][cj] - '0';\n                    int cr = rot[ci][cj];\n                    int nd = to_rot[ct][cr][cd];\n                    if (nd == -1) { broken = true; break; }\n                    int ni = ci + di[nd];\n                    int nj = cj + dj[nd];\n                    if (ni < 0 || ni >= N || nj < 0 || nj >= N) { broken = true; break; }\n                    int ndir_next = (nd + 2) % 4;\n                    seen[ci][cj][cd] = true;\n                    ++len;\n                    ci = ni; cj = nj; cd = ndir_next;\n                    if (ci == i && cj == j && cd == d) break; // closed loop\n                }\n                if (!broken && len > 0) loops.push_back(len);\n            }\n\n    if (loops.size() < 2) return 0;\n    nth_element(loops.begin(), loops.begin(),   loops.end(), greater<int>());\n    nth_element(loops.begin()+1, loops.begin()+1, loops.end(), greater<int>());\n    return loops[0] * loops[1];\n}\n\n/* --------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    build_rot();\n\n    vector<string> tile(N);\n    for (int i = 0; i < N; ++i) cin >> tile[i];\n\n    std::mt19937 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> dist4(0,3);\n    uniform_int_distribution<int> celldist(0, N-1);\n    uniform_real_distribution<double> prob01(0.0, 1.0);\n\n    const double TOTAL_TIME = 1.95;               // seconds\n    auto start_all = chrono::steady_clock::now();\n\n    int best_score = 0;\n    static int best_rot[N][N];\n    static int cur_rot[N][N];\n\n    while (true) {\n        // time check\n        double elapsed_all = chrono::duration<double>(chrono::steady_clock::now() - start_all).count();\n        if (elapsed_all >= TOTAL_TIME) break;\n\n        // --- random initial configuration ---------------------------------\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                cur_rot[i][j] = dist4(rng);\n\n        int cur_score = score_board(tile, cur_rot);\n        if (cur_score > best_score) {\n            best_score = cur_score;\n            for (int i = 0; i < N; ++i)\n                for (int j = 0; j < N; ++j)\n                    best_rot[i][j] = cur_rot[i][j];\n        }\n\n        // --- simulated annealing phase ------------------------------------\n        const int MAX_ITER = 30000;                // enough for the remaining time\n        const double TEMP_START = 2000.0, TEMP_END = 30.0;\n\n        for (int it = 0; it < MAX_ITER; ++it) {\n            // stop early if total time exhausted\n            double now = chrono::duration<double>(chrono::steady_clock::now() - start_all).count();\n            if (now >= TOTAL_TIME) break;\n\n            // cooling\n            double tfrac = (double)it / MAX_ITER;\n            double temp = TEMP_START + (TEMP_END - TEMP_START) * tfrac;\n\n            // propose a change\n            int i = celldist(rng);\n            int j = celldist(rng);\n            int old_r = cur_rot[i][j];\n            int new_r = dist4(rng);\n            if (new_r == old_r) continue;\n            cur_rot[i][j] = new_r;\n\n            int new_score = score_board(tile, cur_rot);\n            bool accept = false;\n            if (new_score >= cur_score) accept = true;\n            else {\n                double p = exp((new_score - cur_score) / temp);\n                if (prob01(rng) < p) accept = true;\n            }\n\n            if (accept) {\n                cur_score = new_score;\n                if (cur_score > best_score) {\n                    best_score = cur_score;\n                    for (int x = 0; x < N; ++x)\n                        for (int y = 0; y < N; ++y)\n                            best_rot[x][y] = cur_rot[x][y];\n                }\n            } else {\n                cur_rot[i][j] = old_r; // revert\n            }\n        }\n    }\n\n    // output the best board found\n    string out;\n    out.reserve(N * N);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            out.push_back(char('0' + best_rot[i][j]));\n    cout << out << '\\n';\n    return 0;\n}","ahc011":"#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    long long T;\n    if (!(cin >> N >> T)) return 0;\n    vector<string> board(N);\n    for (int i = 0; i < N; ++i) cin >> board[i];\n\n    // locate the empty cell (character '0')\n    int ex = -1, ey = -1;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (board[i][j] == '0') { ex = i; ey = j; }\n\n    const string dirs = \"UDLR\";\n    const int dx[4] = {-1, 1, 0, 0};   // U D L R\n    const int dy[4] = {0, 0, -1, 1};\n\n    string answer;\n    answer.reserve(T);\n\n    mt19937 rng(71236789);               // deterministic seed\n    int prev_dir = -1;                    // previous direction, -1 = none\n\n    long long steps = T;                  // we may use the whole budget\n    for (long long step = 0; step < steps; ++step) {\n        vector<int> cand;\n        // collect all moves that stay inside the board\n        for (int d = 0; d < 4; ++d) {\n            int nx = ex + dx[d];\n            int ny = ey + dy[d];\n            if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;\n            cand.push_back(d);\n        }\n\n        // try to avoid immediately reversing the previous move\n        vector<int> filtered;\n        if (prev_dir != -1) {\n            for (int d : cand) {\n                if ((d ^ 1) != prev_dir) filtered.push_back(d);\n            }\n        }\n\n        // if filtering removed everything, fall back to the original list\n        const vector<int> &use = (!filtered.empty() ? filtered : cand);\n        int chosen = use[uniform_int_distribution<int>(0, (int)use.size() - 1)(rng)];\n\n        // perform the slide\n        int nx = ex + dx[chosen];\n        int ny = ey + dy[chosen];\n        swap(board[ex][ey], board[nx][ny]);\n        ex = nx; ey = ny;\n\n        answer.push_back(dirs[chosen]);\n        prev_dir = chosen;\n    }\n\n    cout << answer << '\\n';\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing int64 = long long;\n\n/*---------------------------------------------------------------*/\n/*  Normalise a direction vector (dx,dy) to a unique representation\n    \u2013 divide by gcd and force a canonical sign                     */\nstatic pair<int64,int64> norm_dir(int64 dx, int64 dy){\n    int64 g = std::gcd(std::abs(dx), std::abs(dy));\n    dx /= g;  dy /= g;\n    if (dx < 0 || (dx == 0 && dy < 0)){\n        dx = -dx; dy = -dy;\n    }\n    return {dx, dy};\n}\n\n/*---------------------------------------------------------------*/\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    long long N;\n    int K;\n    if(!(cin >> N >> K)) return 0;\n    for(int i=0;i<10;i++){ long long a; cin >> a; }\n    for(long long i=0;i<N;i++){ long long x,y; cin >> x >> y; }\n    \n    const int MAX_CUTS = 100;                 // problem states K = 100\n    const int64 LIM_COORD = 1000000000LL;      // \u00b11e9\n    const int64 RADIUS   = 10000LL;            // cake radius\n    const int64 RADIUS2  = RADIUS * RADIUS;\n    const int64 SCALE    = 20000LL;            // length multiplier for Q\n    \n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int64> dist_coord(-RADIUS, RADIUS);   // for interior point\n    uniform_int_distribution<int64> dist_dir(-1000, 1000);        // direction components\n    \n    vector<array<int64,4>> lines;\n    unordered_set<unsigned long long> used;    // hash of normalised direction\n    \n    while((int)lines.size() < MAX_CUTS){\n        // ---- pick a point inside the cake ----------\n        int64 px, py;\n        do{\n            px = dist_coord(rng);\n            py = dist_coord(rng);\n        }while(px*px + py*py >= RADIUS2);      // ensure inside the circle\n        \n        // ---- pick a new direction -------------------\n        int64 dx, dy;\n        pair<int64,int64> nd;\n        unsigned long long key;\n        do{\n            dx = dist_dir(rng);\n            dy = dist_dir(rng);\n            if(dx==0 && dy==0) continue;\n            nd = norm_dir(dx, dy);\n            key = ( (unsigned long long)(nd.first  & 0xffffffffULL) << 32 )\n                | ( (unsigned long long)(nd.second & 0xffffffffULL) );\n        }while(used.find(key)!=used.end());\n        used.insert(key);\n        \n        // ---- build second point far enough ------------\n        int64 qx = px + dx * SCALE;\n        int64 qy = py + dy * SCALE;\n        // ensure we stay inside the allowed coordinate range\n        qx = max(min(qx, LIM_COORD), -LIM_COORD);\n        qy = max(min(qy, LIM_COORD), -LIM_COORD);\n        \n        lines.push_back({px, py, qx, qy});\n    }\n    \n    cout << lines.size() << '\\n';\n    for(const auto &ln : lines){\n        cout << ln[0] << ' ' << ln[1] << ' '\n             << ln[2] << ' ' << ln[3] << '\\n';\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int x1, y1, x2, y2, x3, y3, x4, y4;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n    vector<vector<char>> has(N, vector<char>(N, 0));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        has[x][y] = 1;\n    }\n\n    vector<Op> ops;\n    bool progress = true;\n    while (progress) {\n        progress = false;\n        for (int x = 0; x + 1 < N; ++x) {\n            for (int y = 0; y + 1 < N; ++y) {\n                // keep only squares of one colour of the chessboard \u2192 no shared edges\n                if ( (x + y) & 1 ) continue;\n\n                // corners in clockwise order: LL, LR, UR, UL\n                const int cx[4] = {x, x+1, x+1, x};\n                const int cy[4] = {y, y,   y+1, y+1};\n\n                int cnt = 0, missing = -1;\n                for (int k = 0; k < 4; ++k) {\n                    if (has[cx[k]][cy[k]]) ++cnt;\n                    else missing = k;\n                }\n                if (cnt == 3 && missing != -1) {\n                    // place the missing dot\n                    int mx = cx[missing];\n                    int my = cy[missing];\n                    has[mx][my] = 1;\n\n                    // output rectangle starting with the missing corner,\n                    // then the remaining three in clockwise order\n                    Op op;\n                    op.x1 = mx; op.y1 = my;\n                    int idx = 0;\n                    for (int k = 1; k <= 3; ++k) {\n                        int cur = (missing + k) % 4; // next corner clockwise\n                        if (idx == 0) { op.x2 = cx[cur]; op.y2 = cy[cur]; }\n                        else if (idx == 1) { op.x3 = cx[cur]; op.y3 = cy[cur]; }\n                        else { op.x4 = cx[cur]; op.y4 = cy[cur]; }\n                        ++idx;\n                    }\n                    ops.push_back(op);\n                    progress = true;\n                }\n            }\n        }\n    }\n\n    cout << ops.size() << '\\n';\n    for (const auto &op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' '\n             << op.x2 << ' ' << op.y2 << ' '\n             << op.x3 << ' ' << op.y3 << ' '\n             << op.x4 << ' ' << op.y4 << '\\n';\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 10;                     // board dimension\nusing Board = array<array<int, N>, N>;\n\nstruct Pos { int r, c; };\n\n/// Apply a tilt:\n/// 0 = Forward (up), 1 = Backward (down), 2 = Left, 3 = Right\nBoard tilt(const Board &src, int dir) {\n    Board dst = src;\n    if (dir == 0) {                   // Forward (compress upwards)\n        for (int c = 0; c < N; ++c) {\n            int write = 0;\n            for (int r = 0; r < N; ++r) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[write][c] = v;\n                ++write;\n            }\n        }\n    } else if (dir == 1) {            // Backward (compress downwards)\n        for (int c = 0; c < N; ++c) {\n            int write = N - 1;\n            for (int r = N - 1; r >= 0; --r) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[write][c] = v;\n                --write;\n            }\n        }\n    } else if (dir == 2) {            // Left (compress leftwards)\n        for (int r = 0; r < N; ++r) {\n            int write = 0;\n            for (int c = 0; c < N; ++c) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[r][write] = v;\n                ++write;\n            }\n        }\n    } else {                           // Right (compress rightwards)\n        for (int r = 0; r < N; ++r) {\n            int write = N - 1;\n            for (int c = N - 1; c >= 0; --c) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[r][write] = v;\n                --write;\n            }\n        }\n    }\n    return dst;\n}\n\n/// Compute \u03a3 size\u00b2 of connected components **and** the number of same\u2011flavour edges.\npair<long long, long long> component_and_adjacent(const Board &b) {\n    static const int dr[4] = {-1, 1, 0, 0};\n    static const int dc[4] = {0, 0, -1, 1};\n\n    bool vis[N][N] = {};\n    long long compScore = 0;\n    long long adjEdges  = 0;                 // each unordered edge counted once\n\n    for (int r = 0; r < N; ++r) for (int c = 0; c < N; ++c) {\n        if (b[r][c] == 0 || vis[r][c]) continue;\n        int flavour = b[r][c];\n        int sz = 0;\n        queue<Pos> q;\n        q.push({r, c});\n        vis[r][c] = true;\n        while (!q.empty()) {\n            Pos cur = q.front(); q.pop();\n            ++sz;\n            for (int d = 0; d < 4; ++d) {\n                int nr = cur.r + dr[d];\n                int nc = cur.c + dc[d];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                if (b[nr][nc] == flavour) {\n                    // count edge once (only when neighbour is \"later\" in order)\n                    if (nr > cur.r || (nr == cur.r && nc > cur.c))\n                        ++adjEdges;\n                    if (!vis[nr][nc]) {\n                        vis[nr][nc] = true;\n                        q.push({nr, nc});\n                    }\n                }\n            }\n        }\n        compScore += 1LL * sz * sz;\n    }\n    return {compScore, adjEdges};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // 1) read flavours (they are used when placing candies)\n    vector<int> flavour(100);\n    for (int i = 0; i < 100; ++i) cin >> flavour[i];\n\n    Board board{};                 // all zero = empty\n    const char dirChar[4] = {'F', 'B', 'L', 'R'};\n    const long long LAMBDA = 1;    // weight for adjacency term\n\n    for (int step = 0; step < 100; ++step) {\n        int p;                     // 1\u2011based index of the empty cell\n        cin >> p;\n\n        // ---- place the new candy ---------------------------------\n        vector<Pos> empties;\n        empties.reserve(100);\n        for (int r = 0; r < N; ++r)\n            for (int c = 0; c < N; ++c)\n                if (board[r][c] == 0) empties.push_back({r, c});\n\n        Pos where = empties[p - 1];\n        board[where.r][where.c] = flavour[step];\n\n        // ---- evaluate the four possible tilts --------------------\n        long long bestScore = LLONG_MIN;\n        int bestDir = 0;                // default to Forward\n\n        for (int d = 0; d < 4; ++d) {\n            Board nb = tilt(board, d);\n            auto [comp, adj] = component_and_adjacent(nb);\n            long long total = comp + LAMBDA * adj;\n            if (total > bestScore) {\n                bestScore = total;\n                bestDir = d;\n            }\n        }\n\n        // ---- output and really apply the chosen tilt ------------\n        cout << dirChar[bestDir] << '\\n';\n        cout.flush();\n\n        board = tilt(board, bestDir);   // update state for next step\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n\n    const int N = 20;                         // fixed vertex count\n    const int L = N * (N - 1) / 2;            // length of each graph string\n\n    cout << N << \"\\n\";\n    for (int k = 0; k < M; ++k) {\n        string s(k, '1');                     // k ones\n        s.append(L - k, '0');                 // remaining zeros\n        cout << s << \"\\n\";\n    }\n    cout.flush();\n\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;                             // length L\n        int cnt = 0;\n        for (char c : H) if (c == '1') ++cnt;\n\n        int t = min(cnt, M - 1);               // nearest index (0 \u2026 M\u20111)\n        cout << t << \"\\n\";\n        cout.flush();\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union for Kruskal ***/\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) { p.resize(n); r.assign(n, 0); iota(p.begin(), p.end(), 0); }\n    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\nstruct Edge {\n    int idx;   // original index (0\u2011based)\n    int u, v;\n    int w;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n\n    vector<Edge> edges;\n    edges.reserve(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u; --v;                     // make 0\u2011based\n        edges.push_back({i, u, v, w});\n    }\n\n    // read and discard coordinates (not needed for scheduling)\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    /* ---------- Build MST (Kruskal) ---------- */\n    vector<int> mst_flag(M, 0);        // 1 if edge belongs to MST\n    vector<int> order; order.reserve(M);\n\n    // sort edges by weight (ascending) for Kruskal\n    vector<int> idx_by_weight(M);\n    iota(idx_by_weight.begin(), idx_by_weight.end(), 0);\n    sort(idx_by_weight.begin(), idx_by_weight.end(),\n         [&](int a, int b) { return edges[a].w < edges[b].w; });\n\n    DSU dsu(N);\n    int mst_edges = 0;\n    for (int id : idx_by_weight) {\n        const Edge &e = edges[id];\n        if (dsu.unite(e.u, e.v)) {\n            mst_flag[id] = 1;\n            ++mst_edges;\n            if (mst_edges == N - 1) break;\n        }\n    }\n\n    /* ---------- Build final ordering ----------\n       First all MST edges (keep their weight order),\n       then all non\u2011MST edges (also weight order). */\n    vector<int> mst_list, nonmst_list;\n    mst_list.reserve(N - 1);\n    nonmst_list.reserve(M - (N - 1));\n    for (int id : idx_by_weight) {\n        if (mst_flag[id]) mst_list.push_back(id);\n        else            nonmst_list.push_back(id);\n    }\n    order.insert(order.end(), mst_list.begin(), mst_list.end());\n    order.insert(order.end(), nonmst_list.begin(), nonmst_list.end());\n\n    /* ---------- Round\u2011robin assignment ---------- */\n    vector<int> day_of_edge(M);\n    for (int i = 0; i < M; ++i) {\n        int original_idx = edges[ order[i] ].idx;\n        day_of_edge[original_idx] = (i % D) + 1;   // 1\u2011based day number\n    }\n\n    /* ---------- Output ---------- */\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << day_of_edge[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int D;\n    if (!(cin >> D)) return 0;\n\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) cin >> f[i][z];\n        for (int z = 0; z < D; ++z) cin >> r[i][z];\n    }\n\n    const long long SZ = 1LL * D * D * D;\n    auto idx = [&](int x, int y, int z) -> long long {\n        return 1LL * x * D * D + 1LL * y * D + z;\n    };\n\n    vector<int> out1(SZ, 0), out2(SZ, 0);\n    long long curId = 0;\n\n    for (int x = 0; x < D; ++x)\n        for (int y = 0; y < D; ++y)\n            for (int z = 0; z < D; ++z) {\n                bool in1 = (f[0][z][x] == '1' && r[0][z][y] == '1');\n                bool in2 = (f[1][z][x] == '1' && r[1][z][y] == '1');\n                if (!in1 && !in2) continue;\n                ++curId;\n                long long p = idx(x, y, z);\n                if (in1) out1[p] = (int)curId;\n                if (in2) out2[p] = (int)curId;\n            }\n\n    cout << curId << '\\n';\n    for (size_t i = 0; i < out1.size(); ++i) {\n        if (i) cout << ' ';\n        cout << out1[i];\n    }\n    cout << '\\n';\n    for (size_t i = 0; i < out2.size(); ++i) {\n        if (i) cout << ' ';\n        cout << out2[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) { p.resize(n); r.assign(n, 0); iota(p.begin(), p.end(), 0); }\n    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;\n\n    vector<long long> x(N + 1), y(N + 1);\n    for (int i = 1; i <= N; ++i) cin >> x[i] >> y[i];\n\n    struct Edge {int u, v; long long w;};\n    vector<Edge> edges(M + 1);\n    const long long INF = (1LL << 60);\n    vector<vector<long long>> sp(N + 1, vector<long long>(N + 1, INF));\n    vector<vector<int>> nxt(N + 1, vector<int>(N + 1, -1));\n    map<pair<int,int>, int> pairToIdx;\n\n    for (int j = 1; j <= M; ++j) {\n        int u, v; long long w;\n        cin >> u >> v >> w;\n        edges[j] = {u, v, w};\n        if (w < sp[u][v]) {\n            sp[u][v] = sp[v][u] = w;\n            nxt[u][v] = v;\n            nxt[v][u] = u;\n        }\n        pairToIdx[{min(u, v), max(u, v)}] = j;\n    }\n    for (int i = 1; i <= N; ++i) {\n        sp[i][i] = 0;\n        nxt[i][i] = i;\n    }\n\n    // Floyd\u2011Warshall\n    for (int k = 1; k <= N; ++k)\n        for (int i = 1; i <= N; ++i) if (sp[i][k] != INF)\n            for (int j = 1; j <= N; ++j) if (sp[k][j] != INF) {\n                long long nd = sp[i][k] + sp[k][j];\n                if (nd < sp[i][j]) {\n                    sp[i][j] = nd;\n                    nxt[i][j] = nxt[i][k];\n                }\n            }\n\n    // residents\n    struct Resident { long long a, b; };\n    vector<Resident> residents(K);\n    for (int i = 0; i < K; ++i) cin >> residents[i].a >> residents[i].b;\n\n    // distance resident -> vertex\n    vector<vector<double>> dRes(K, vector<double>(N + 1));\n    for (int r = 0; r < K; ++r) {\n        for (int v = 1; v <= N; ++v) {\n            long double dx = (long double)x[v] - (long double)residents[r].a;\n            long double dy = (long double)y[v] - (long double)residents[r].b;\n            dRes[r][v] = sqrt(dx*dx + dy*dy);\n        }\n    }\n\n    // ----------  iterative reduction ----------\n    vector<char> active(N + 1, 1);         // all vertices start as possible\n    active[1] = 1;                        // source must stay active (may have P=0)\n\n    bool changed = true;\n    while (changed) {\n        changed = false;\n        // assignment to nearest active vertex\n        vector<int> assign(K, -1);\n        vector<double> assignDist(K, 1e100);\n        for (int r = 0; r < K; ++r) {\n            double best = 1e100;\n            int bestv = -1;\n            for (int v = 1; v <= N; ++v) if (active[v]) {\n                if (dRes[r][v] < best) {\n                    best = dRes[r][v];\n                    bestv = v;\n                }\n            }\n            assign[r] = bestv;\n            assignDist[r] = best;\n        }\n\n        // compute required powers\n        vector<int> P(N + 1, 0);\n        vector<double> maxDist(N + 1, -1.0);\n        for (int r = 0; r < K; ++r) {\n            int v = assign[r];\n            if (v == -1) continue;\n            if (assignDist[r] > maxDist[v]) maxDist[v] = assignDist[r];\n        }\n        for (int v = 1; v <= N; ++v) if (active[v] && maxDist[v] >= 0) {\n            int pi = (int)ceil(maxDist[v] - 1e-12);\n            if (pi > 5000) pi = 5000;\n            P[v] = pi;\n        }\n\n        // find removable vertices (except source)\n        vector<char> removable(N + 1, 0);\n        for (int v = 1; v <= N; ++v) {\n            if (!active[v] || v == 1) continue;\n            bool canRemove = true;\n            // if no resident assigned -> removable\n            bool hasResident = false;\n            for (int r = 0; r < K; ++r) if (assign[r] == v) {\n                hasResident = true;\n                // is this resident already covered by another active vertex?\n                bool covered = false;\n                for (int u = 1; u <= N; ++u) if (u != v && active[u]) {\n                    if (P[u] > 0 && dRes[r][u] <= P[u] + 1e-9) {\n                        covered = true; break;\n                    }\n                }\n                if (!covered) { canRemove = false; break; }\n            }\n            if (!hasResident) canRemove = true;\n            if (canRemove) removable[v] = 1;\n        }\n\n        // apply removals\n        for (int v = 1; v <= N; ++v) if (removable[v]) {\n            active[v] = 0;\n            changed = true;\n        }\n    }\n\n    // ---------- final assignment & powers ----------\n    // assign again (now active set is final)\n    vector<int> finalAssign(K, -1);\n    for (int r = 0; r < K; ++r) {\n        double best = 1e100;\n        int bestv = -1;\n        for (int v = 1; v <= N; ++v) if (active[v]) {\n            if (dRes[r][v] < best) {\n                best = dRes[r][v];\n                bestv = v;\n            }\n        }\n        finalAssign[r] = bestv;\n    }\n    vector<int> P(N + 1, 0);\n    vector<double> maxDist(N + 1, -1.0);\n    for (int r = 0; r < K; ++r) {\n        int v = finalAssign[r];\n        if (v == -1) continue;\n        if (dRes[r][v] > maxDist[v]) maxDist[v] = dRes[r][v];\n    }\n    for (int v = 1; v <= N; ++v) if (active[v] && maxDist[v] >= 0) {\n        int pi = (int)ceil(maxDist[v] - 1e-12);\n        if (pi > 5000) pi = 5000;\n        P[v] = pi;\n    }\n    // source must be present in the connectivity set even if P[1]==0\n    active[1] = 1;\n\n    // ---------- build metric MST ----------\n    vector<int> actList;\n    for (int v = 1; v <= N; ++v) if (active[v]) actList.push_back(v);\n    struct EdgeM { long long w; int u, v; };\n    vector<EdgeM> metricEdges;\n    int A = actList.size();\n    for (int i = 0; i < A; ++i) {\n        for (int j = i + 1; j < A; ++j) {\n            int u = actList[i], v = actList[j];\n            metricEdges.push_back({sp[u][v], u, v});\n        }\n    }\n    sort(metricEdges.begin(), metricEdges.end(),\n         [](const EdgeM& a, const EdgeM& b){ return a.w < b.w; });\n\n    DSU dsu(N + 1);\n    vector<pair<int,int>> mstPairs;\n    for (auto &e : metricEdges) {\n        if (dsu.unite(e.u, e.v)) {\n            mstPairs.emplace_back(e.u, e.v);\n            if ((int)mstPairs.size() == A - 1) break;\n        }\n    }\n\n    // ---------- mark original edges used ----------\n    vector<char> usedEdge(M + 1, 0);\n    auto addPath = [&](int s, int t){\n        int cur = s;\n        while (cur != t) {\n            int nx = nxt[cur][t];\n            int a = min(cur, nx), b = max(cur, nx);\n            int idx = pairToIdx[{a, b}];\n            usedEdge[idx] = 1;\n            cur = nx;\n        }\n    };\n    for (auto [u, v] : mstPairs) addPath(u, v);\n\n    // ---------- output ----------\n    for (int i = 1; i <= N; ++i) {\n        if (i > 1) cout << ' ';\n        cout << P[i];\n    }\n    cout << '\\n';\n    for (int j = 1; j <= M; ++j) {\n        if (j > 1) cout << ' ';\n        cout << (int)usedEdge[j];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Swap {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 30;\n    const int M = N * (N + 1) / 2;          // 465\n\n    // read the pyramid\n    vector<vector<int>> a(N);\n    for (int x = 0; x < N; ++x) {\n        a[x].resize(x + 1);\n        for (int y = 0; y <= x; ++y) {\n            cin >> a[x][y];\n        }\n    }\n\n    vector<Swap> ops;\n    ops.reserve(10000);\n\n    // bottom\u2011up heapify\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            int cx = x, cy = y;\n            while (cx + 1 < N) {\n                int leftX = cx + 1, leftY = cy;\n                int rightX = cx + 1, rightY = cy + 1;\n\n                // choose the smaller child\n                int childX, childY;\n                if (a[leftX][leftY] <= a[rightX][rightY]) {\n                    childX = leftX; childY = leftY;\n                } else {\n                    childX = rightX; childY = rightY;\n                }\n\n                if (a[childX][childY] < a[cx][cy]) {\n                    // perform the swap\n                    swap(a[cx][cy], a[childX][childY]);\n                    ops.push_back({cx, cy, childX, childY});\n                    if ((int)ops.size() >= 10000) break; // safety\n                    // continue from child's position\n                    cx = childX; cy = childY;\n                } else {\n                    break; // heap property satisfied at this node\n                }\n            }\n            if ((int)ops.size() >= 10000) break;\n        }\n        if ((int)ops.size() >= 10000) break;\n    }\n\n    // output\n    cout << ops.size() << '\\n';\n    for (auto &s : ops) {\n        cout << s.x1 << ' ' << s.y1 << ' '\n             << s.x2 << ' ' << s.y2 << '\\n';\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int D_input, N;\n    if (!(cin >> D_input >> N)) return 0;   // D = 9\n    const int D = D_input;\n    const int entrance_i = 0, entrance_j = (D - 1) / 2;\n    const int entrance_id = entrance_i * D + entrance_j;\n\n    vector<vector<int>> blocked(D, vector<int>(D, 0));\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        blocked[ri][rj] = 1;\n    }\n\n    auto inside = [&](int i, int j) {\n        return 0 <= i && i < D && 0 <= j && j < D;\n    };\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n\n    const int V = D * D;\n    vector<vector<int>> adj(V);\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            if (blocked[i][j]) continue;\n            int v = i * D + j;\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d], nj = j + dj[d];\n                if (!inside(ni, nj)) continue;\n                if (blocked[ni][nj]) continue;\n                int nb = ni * D + nj;\n                adj[v].push_back(nb);\n            }\n        }\n    }\n\n    /* BFS distances from the entrance */\n    vector<int> dist(V, -1);\n    queue<int> q;\n    dist[entrance_id] = 0;\n    q.push(entrance_id);\n    while (!q.empty()) {\n        int v = q.front(); q.pop();\n        for (int nb : adj[v]) {\n            if (dist[nb] == -1) {\n                dist[nb] = dist[v] + 1;\n                q.push(nb);\n            }\n        }\n    }\n\n    /* list of all usable cells (except entrance) sorted by distance decreasing */\n    vector<int> orderDesc;\n    for (int v = 0; v < V; ++v) {\n        if (blocked[v / D][v % D]) continue;\n        if (v == entrance_id) continue;\n        orderDesc.push_back(v);\n    }\n    sort(orderDesc.begin(), orderDesc.end(),\n         [&](int a, int b) { return dist[a] > dist[b]; });\n\n    vector<int> container(V, -1);               // -1 = empty\n    const int M = D * D - 1 - N;                 // number of containers\n    size_t ptr = 0;                             // first still empty cell in orderDesc\n\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;                               // label of the arriving container\n\n        while (ptr < orderDesc.size() && container[orderDesc[ptr]] != -1) ++ptr;\n        int v = orderDesc[ptr];                 // farthest still empty cell\n        ++ptr;\n\n        cout << v / D << ' ' << v % D << '\\n' << flush;\n        container[v] = t;\n    }\n\n    /* ----- taking\u2011out order ----- */\n    int maxDist = 0;\n    for (int v = 0; v < V; ++v) {\n        if (blocked[v / D][v % D]) continue;\n        maxDist = max(maxDist, dist[v]);\n    }\n\n    for (int d = 1; d <= maxDist; ++d) {\n        vector<int> layer;\n        for (int v = 0; v < V; ++v) {\n            if (blocked[v / D][v % D]) continue;\n            if (dist[v] == d) layer.push_back(v);\n        }\n        sort(layer.begin(), layer.end(),\n             [&](int a, int b) { return container[a] < container[b]; });\n        for (int v : layer) {\n            cout << v / D << ' ' << v % D << '\\n';\n        }\n    }\n    cout << flush;\n    return 0;\n}","ahc024":"#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    if (!(cin >> n >> m)) return 0;\n    vector<vector<int>> a(n, vector<int>(n));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (j) cout << ' ';\n            cout << a[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n    vector<long long> w(N);\n    for (int i = 0; i < N; ++i) cin >> w[i];   // offline version gives the weights\n    \n    // indices sorted by decreasing weight\n    vector<int> ids(N);\n    iota(ids.begin(), ids.end(), 0);\n    sort(ids.begin(), ids.end(), [&](int a, int b){ return w[a] > w[b]; });\n    \n    vector<long long> tot(D, 0);\n    vector<int> ans(N, -1);\n    \n    for (int id : ids) {\n        // find bin with minimal total weight\n        int best = 0;\n        for (int b = 1; b < D; ++b) {\n            if (tot[b] < tot[best]) best = b;\n        }\n        ans[id] = best;\n        tot[best] += w[id];\n    }\n    \n    // output division\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << ans[i];\n    }\n    cout << '\\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    if (!(cin >> n >> m)) return 0;            // n = 200, m = 10\n    const int per = n / m;                     // 20\n    vector<vector<int>> st(m);                 // bottom -> top\n    for (int i = 0; i < m; ++i) {\n        st[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x; cin >> x;\n            st[i].push_back(x);\n        }\n    }\n\n    vector<pair<int,int>> ops;\n    ops.reserve(5000);\n\n    const int INF = n + 1;                     // larger than any label\n\n    for (int target = 1; target <= n; ++target) {\n        while (true) {\n            // locate the stack and position of the current target\n            int s = -1, pos = -1;\n            for (int i = 0; i < m; ++i) {\n                const auto &vec = st[i];\n                for (int j = 0; j < (int)vec.size(); ++j) {\n                    if (vec[j] == target) {\n                        s = i;\n                        pos = j;\n                        break;\n                    }\n                }\n                if (s != -1) break;\n            }\n\n            int topIdx = (int)st[s].size() - 1;\n            if (pos == topIdx) {                         // already on top\n                ops.emplace_back(target, 0);              // pop\n                st[s].pop_back();\n                break;                                    // next target\n            }\n\n            // ----- move the whole block that hides target -----\n            int start = pos + 1;                         // first element of block\n            vector<int> block(st[s].begin() + start, st[s].end());\n\n            int maxInBlock = *max_element(block.begin(), block.end());\n\n            // choose destination\n            int dest = -1;\n            int bestSize = INT_MAX;\n\n            // first try to find a \"safe\" stack (top > maxInBlock)\n            for (int i = 0; i < m; ++i) {\n                if (i == s) continue;\n                int topVal = st[i].empty() ? INF : st[i].back();\n                if (topVal > maxInBlock) {\n                    if ((int)st[i].size() < bestSize) {\n                        bestSize = (int)st[i].size();\n                        dest = i;\n                    }\n                }\n            }\n\n            // if no safe stack exists, fall back to the smallest stack\n            if (dest == -1) {\n                bestSize = INT_MAX;\n                for (int i = 0; i < m; ++i) {\n                    if (i == s) continue;\n                    if ((int)st[i].size() < bestSize) {\n                        bestSize = (int)st[i].size();\n                        dest = i;\n                    }\n                }\n            }\n\n            // perform the move (type 1)\n            int v = block.front();                       // bottom of the block\n            ops.emplace_back(v, dest + 1);\n\n            // erase block from source stack\n            st[s].erase(st[s].begin() + start, st[s].end());\n            // append block to destination stack preserving order\n            st[dest].insert(st[dest].end(), block.begin(), block.end());\n            // after this target becomes top; loop again to pop it\n        }\n    }\n\n    for (auto [v, i] : ops) {\n        cout << v << ' ' << i << '\\n';\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n\n    vector<string> h(N - 1);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    vector<string> v(N);\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    // d is read but not used\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            long long tmp;\n            cin >> tmp;\n        }\n    }\n\n    const int di[4] = {0, 1, 0, -1};\n    const int dj[4] = {1, 0, -1, 0};\n    const char moveChar[4] = {'R', 'D', 'L', 'U'};\n    const char backChar[4] = {'L', 'U', 'R', 'D'};\n\n    vector<vector<char>> visited(N, vector<char>(N, 0));\n    string answer;\n\n    function<void(int,int)> dfs = [&](int i, int j) {\n        visited[i][j] = 1;\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + di[dir];\n            int nj = j + dj[dir];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (visited[ni][nj]) continue;\n            // check wall\n            bool blocked = false;\n            if (dir == 0) { // right\n                blocked = (v[i][j] == '1');\n            } else if (dir == 2) { // left\n                blocked = (v[i][j-1] == '1');\n            } else if (dir == 1) { // down\n                blocked = (h[i][j] == '1');\n            } else { // up\n                blocked = (h[i-1][j] == '1');\n            }\n            if (blocked) continue;\n\n            answer.push_back(moveChar[dir]);\n            dfs(ni, nj);\n            answer.push_back(backChar[dir]);\n        }\n    };\n\n    dfs(0, 0);\n    cout << answer << '\\n';\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing pii = pair<int,int>;\n\nint manhattan(const pii& a, const pii& b){\n    return abs(a.first - b.first) + abs(a.second - b.second);\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if(!(cin >> N >> M)) return 0;          // N = 15, M = 200 (fixed)\n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> board(N);\n    for(int i=0;i<N;i++) cin >> board[i];\n    \n    // positions of each letter\n    vector<pii> pos[26];\n    for(int i=0;i<N;i++)\n        for(int j=0;j<N;j++)\n            pos[ board[i][j] - 'A' ].push_back({i,j});\n    \n    vector<string> words(M);\n    for(int k=0;k<M;k++) cin >> words[k];\n    \n    // ---------- compute optimal internal path for each word ----------\n    struct WordInfo{\n        vector<pii> path;   // 5 coordinates\n        pii start, finish;\n    };\n    vector<WordInfo> info(M);\n    \n    for(int idx=0; idx<M; ++idx){\n        const string& w = words[idx];\n        // lists of positions for each character\n        array<vector<pii>*,5> lst;\n        for(int p=0;p<5;p++) lst[p] = &pos[w[p]-'A'];\n        int sz[5];\n        for(int p=0;p<5;p++) sz[p] = (int)lst[p]->size();\n        \n        // dp[i][k] : minimal cost after processing character i and being at k-th position of lst[i]\n        vector<vector<int>> dp(5);\n        vector<vector<int>> pre(5);   // store previous index\n        for(int i=0;i<5;i++){\n            dp[i].assign(sz[i], INT_MAX);\n            pre[i].assign(sz[i], -1);\n        }\n        // first character: only press cost = 1\n        for(int k=0;k<sz[0];k++) dp[0][k] = 1;\n        \n        // transition\n        for(int i=1;i<5;i++){\n            for(int k=0;k<sz[i];k++){\n                const pii& cur = (*lst[i])[k];\n                int best = INT_MAX, bestPrev = -1;\n                for(int q=0;q<sz[i-1];q++){\n                    const pii& prev = (*lst[i-1])[q];\n                    int cand = dp[i-1][q] + manhattan(prev,cur) + 1;\n                    if(cand < best){\n                        best = cand;\n                        bestPrev = q;\n                    }\n                }\n                dp[i][k] = best;\n                pre[i][k] = bestPrev;\n            }\n        }\n        // find minimal end\n        int bestEnd = 0;\n        for(int k=1;k<sz[4];k++) if(dp[4][k] < dp[4][bestEnd]) bestEnd = k;\n        // reconstruct path (indices)\n        array<int,5> idxs;\n        idxs[4] = bestEnd;\n        for(int i=4;i>=1;i--){\n            idxs[i-1] = pre[i][ idxs[i] ];\n        }\n        // store coordinates\n        info[idx].path.resize(5);\n        for(int i=0;i<5;i++){\n            info[idx].path[i] = (*lst[i])[ idxs[i] ];\n        }\n        info[idx].start = info[idx].path.front();\n        info[idx].finish = info[idx].path.back();\n    }\n    \n    // ---------- greedy ordering ----------\n    vector<int> remaining(M);\n    iota(remaining.begin(), remaining.end(), 0);\n    vector<char> used(M, 0);\n    pii cur = {si, sj};\n    vector<pii> answer;\n    answer.reserve(5*M + 10);\n    \n    int left = M;\n    while(left){\n        int bestIdx = -1;\n        int bestDist = INT_MAX;\n        for(int id : remaining){\n            if(used[id]) continue;\n            int d = manhattan(cur, info[id].start);\n            if(d < bestDist){\n                bestDist = d;\n                bestIdx = id;\n            }\n        }\n        // move to start (the movement cost is automatically counted when we type)\n        // we just output the whole path\n        for(const pii& p : info[bestIdx].path){\n            answer.push_back(p);\n        }\n        cur = info[bestIdx].finish;\n        used[bestIdx] = 1;\n        --left;\n    }\n    \n    // ---------- output ----------\n    for(const auto& p : answer){\n        cout << p.first << ' ' << p.second << '\\n';\n    }\n    return 0;\n}","ahc030":"#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    double eps;\n    if (!(cin >> N >> M >> eps)) return 0;\n\n    // ---- read shapes (ignored later) ----\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        for (int t = 0; t < d; ++t) {\n            int a, b;\n            cin >> a >> b;\n        }\n    }\n\n    // ---- read positions of each field (unused) ----\n    for (int k = 0; k < M; ++k) {\n        int di, dj;\n        cin >> di >> dj;\n        (void)di; (void)dj;\n    }\n\n    // ---- read the whole v matrix ----\n    vector<vector<int>> v(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> v[i][j];\n\n    // ---- discard the remaining numbers (up to 2*N^2) ----\n    // The exact amount is not needed; just read until EOF.\n    double dummy;\n    while (cin >> dummy) { /* discard */ }\n\n    // ---- collect cells with v > 0 ----\n    vector<pair<int,int>> ans;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (v[i][j] > 0) ans.emplace_back(i, j);\n\n    // ---- output in the required format ----\n    cout << \"a \" << ans.size();\n    for (auto [i, j] : ans) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << \"\\n\";\n    cout.flush();\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    if (!(cin >> W >> D >> N)) return 0;\n    // read and ignore the desired areas\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            long long a;\n            cin >> a;\n            (void)a;\n        }\n    }\n\n    // output the simple vertical strips\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            int i0 = k;\n            int j0 = 0;\n            int i1 = k + 1;\n            int j1 = W;\n            cout << i0 << ' ' << j0 << ' ' << i1 << ' ' << j1 << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing int64 = long long;\nconst int64 MOD = 998244353LL;\n\nstruct Op {\n    int m, p, q;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;          // N = 9, M = 20, K = 81\n\n    vector<vector<int64>> init(N, vector<int64>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> init[i][j];\n\n    // stamps[m][i][j]\n    vector<array<array<int64, 3>, 3>> stamp(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 >> stamp[m][i][j];\n\n    // ---------- Greedy construction ----------\n    vector<Op> best_ops;\n    best_ops.reserve(K);\n    vector<vector<int64>> board = init;   // current board\n\n    for (int step = 0; step < K; ++step) {\n        int best_m = -1, best_p = -1, best_q = -1;\n        int64 best_gain = 0;   // we only accept strictly positive gain\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    int64 gain = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            int64 oldv = board[p + i][q + j];\n                            int64 oldr = oldv % MOD;\n                            int64 newr = (oldv + stamp[m][i][j]) % MOD;\n                            gain += newr - oldr;\n                        }\n                    }\n                    if (gain > best_gain) {\n                        best_gain = gain;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_gain <= 0) break;   // no improving press exists\n\n        // apply the chosen press\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                board[best_p + i][best_q + j] += stamp[best_m][i][j];\n\n        best_ops.push_back({best_m, best_p, best_q});\n    }\n\n    // ---------- Local\u2011search improvement ----------\n    // random generator\n    std::mt19937 rng(static_cast<unsigned>(chrono::steady_clock::now().time_since_epoch().count()));\n    uniform_int_distribution<int> dist_m(0, M - 1);\n    uniform_int_distribution<int> dist_pos(0, N - 3);\n    uniform_int_distribution<int> dist_bool(0, 1);\n    uniform_int_distribution<int> dist_idx;   // will be set later when needed\n\n    // helper to compute total score of a given operation list\n    auto compute_score = [&](const vector<Op>& ops) -> int64 {\n        vector<vector<int64>> cur = init;\n        for (const Op& op : ops) {\n            for (int i = 0; i < 3; ++i)\n                for (int j = 0; j < 3; ++j)\n                    cur[op.p + i][op.q + j] += stamp[op.m][i][j];\n        }\n        int64 sum = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                sum += cur[i][j] % MOD;\n        return sum;\n    };\n\n    int64 best_score = compute_score(best_ops);\n    const double TIME_LIMIT = 1.70;   // seconds\n    auto start_time = chrono::steady_clock::now();\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        vector<Op> cur_ops = best_ops;\n\n        if (!cur_ops.empty()) {\n            dist_idx = uniform_int_distribution<int>(0, (int)cur_ops.size() - 1);\n            int replace_idx = dist_idx(rng);\n            cur_ops[replace_idx] = {dist_m(rng), dist_pos(rng), dist_pos(rng)};\n        }\n\n        // occasionally try to add one more operation (if we still have quota)\n        if ((int)cur_ops.size() < K && dist_bool(rng) == 0) {\n            cur_ops.push_back({dist_m(rng), dist_pos(rng), dist_pos(rng)});\n        }\n\n        int64 cur_score = compute_score(cur_ops);\n        if (cur_score > best_score) {\n            best_score = cur_score;\n            best_ops.swap(cur_ops);\n        }\n    }\n\n    // ---------- Output ----------\n    cout << best_ops.size() << '\\n';\n    for (const Op& op : best_ops) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n    return 0;\n}","ahc033":"#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    if (!(cin >> N)) return 0;          // N is always 5\n    // read and ignore the matrix A\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            int x; cin >> x;\n            (void)x;\n        }\n\n    vector<string> ops(N);\n    for (int i = 0; i < N; ++i) {\n        string s;\n        // first N-1 containers: pick, go right 4, drop, go left 4\n        for (int cnt = 0; cnt < N - 1; ++cnt) {\n            s.push_back('P');\n            s.append(4, 'R');   // move to column N-1\n            s.push_back('Q');\n            s.append(4, 'L');   // return to column 0\n        }\n        // last container: pick, go right 4, drop\n        s.push_back('P');\n        s.append(4, 'R');\n        s.push_back('Q');\n        ops[i] = s;\n    }\n\n    for (int i = 0; i < N; ++i) {\n        cout << ops[i] << '\\n';\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int r, c;\n    int amt;          // for positives: amount to load; for negatives: amount to receive\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> h[i][j];\n    \n    vector<Cell> pos, neg;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (h[i][j] > 0) pos.push_back({i, j, h[i][j]});\n            else if (h[i][j] < 0) neg.push_back({i, j, -h[i][j]});\n        }\n    \n    int curR = 0, curC = 0;          // current truck position\n    long long load = 0;              // soil currently on the truck\n    \n    auto move_to = [&](int tr, int tc) {\n        while (curR < tr) { cout << \"D\\n\"; ++curR; }\n        while (curR > tr) { cout << \"U\\n\"; --curR; }\n        while (curC < tc) { cout << \"R\\n\"; ++curC; }\n        while (curC > tc) { cout << \"L\\n\"; --curC; }\n    };\n    \n    while (!pos.empty() || !neg.empty()) {\n        if (load == 0) {\n            // find nearest positive cell\n            int best = -1, bestDist = INT_MAX;\n            for (int i = 0; i < (int)pos.size(); ++i) {\n                int d = abs(pos[i].r - curR) + abs(pos[i].c - curC);\n                if (d < bestDist) {\n                    bestDist = d;\n                    best = i;\n                }\n            }\n            // move there and load\n            move_to(pos[best].r, pos[best].c);\n            load = pos[best].amt;\n            cout << \"+\" << load << \"\\n\";\n            // remove this cell\n            pos[best] = pos.back();\n            pos.pop_back();\n        } else {\n            // we have load, go to nearest negative cell\n            int best = -1, bestDist = INT_MAX;\n            for (int i = 0; i < (int)neg.size(); ++i) {\n                int d = abs(neg[i].r - curR) + abs(neg[i].c - curC);\n                if (d < bestDist) {\n                    bestDist = d;\n                    best = i;\n                }\n            }\n            // move there\n            move_to(neg[best].r, neg[best].c);\n            int need = neg[best].amt;\n            int d = (int)min<long long>(load, need);\n            cout << \"-\" << d << \"\\n\";\n            load -= d;\n            need -= d;\n            if (need == 0) {\n                // finished this negative cell\n                neg[best] = neg.back();\n                neg.pop_back();\n            } else {\n                neg[best].amt = need;   // still needs more soil\n            }\n        }\n    }\n    // At this point load == 0 and all heights are zero.\n    return 0;\n}","ahc035":"#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, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    const int SEED_CNT = 2 * N * (N - 1);   // 60 (N = 6)\n    const int BOARD = N * N;               // 36\n\n    // current seed vectors\n    vector<vector<int>> seed(SEED_CNT, vector<int>(M));\n\n    // read initial seeds\n    for (int i = 0; i < SEED_CNT; ++i)\n        for (int j = 0; j < M; ++j)\n            cin >> seed[i][j];\n\n    // adjacency of cells (0 \u2026 BOARD-1) on a 6\u00d76 grid\n    vector<vector<int>> neigh(BOARD);\n    auto id = [&](int r, int c) { return r * N + c; };\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            int v = id(r, c);\n            if (c + 1 < N) neigh[v].push_back(id(r, c + 1));\n            if (c - 1 >= 0) neigh[v].push_back(id(r, c - 1));\n            if (r + 1 < N) neigh[v].push_back(id(r + 1, c));\n            if (r - 1 >= 0) neigh[v].push_back(id(r - 1, c));\n        }\n    }\n\n    mt19937 rng(123456789);           // deterministic RNG, change seed if desired\n    uniform_int_distribution<int> cellDist(0, BOARD - 1);\n    uniform_int_distribution<int> seedDist(0, SEED_CNT - 1);\n\n    for (int turn = 0; turn < T; ++turn) {\n        /* ------------------------------------------------------------\n           1) per\u2011dimension maxima X[l]\n        ------------------------------------------------------------ */\n        vector<int> X(M, 0);\n        for (int i = 0; i < SEED_CNT; ++i)\n            for (int l = 0; l < M; ++l)\n                X[l] = max(X[l], seed[i][l]);\n\n        /* ------------------------------------------------------------\n           2) normalized scores\n        ------------------------------------------------------------ */\n        vector<double> score(SEED_CNT, 0.0);\n        for (int i = 0; i < SEED_CNT; ++i) {\n            double s = 0.0;\n            for (int l = 0; l < M; ++l) {\n                if (X[l] > 0) s += static_cast<double>(seed[i][l]) / X[l];\n            }\n            score[i] = s;\n        }\n\n        /* ------------------------------------------------------------\n           3) initial selection: one best per dimension + best scores\n        ------------------------------------------------------------ */\n        vector<int> chosen;                 // size will become BOARD\n        vector<char> inSet(SEED_CNT, 0);\n\n        // best seed for each dimension\n        for (int l = 0; l < M; ++l) {\n            int best = 0;\n            for (int i = 1; i < SEED_CNT; ++i)\n                if (seed[i][l] > seed[best][l]) best = i;\n            if (!inSet[best]) {\n                inSet[best] = 1;\n                chosen.push_back(best);\n            }\n        }\n\n        // fill remaining slots with highest normalized score\n        vector<int> order(SEED_CNT);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) { return score[a] > score[b]; });\n\n        for (int idd : order) {\n            if ((int)chosen.size() >= BOARD) break;\n            if (inSet[idd]) continue;\n            inSet[idd] = 1;\n            chosen.push_back(idd);\n        }\n\n        /* ------------------------------------------------------------\n           4) hill\u2011climbing to improve edge score\n        ------------------------------------------------------------ */\n        // placement: cell -> seed id\n        vector<int> placed(BOARD);\n        for (int c = 0; c < BOARD; ++c) placed[c] = chosen[c];\n\n        // compute current edge score\n        auto edgeScore = [&](const vector<int>& placement) -> long long {\n            long long total = 0;\n            for (int u = 0; u < BOARD; ++u) {\n                for (int v : neigh[u]) {\n                    if (v < u) continue;               // each edge once\n                    for (int l = 0; l < M; ++l)\n                        total += max(seed[placement[u]][l],\n                                    seed[placement[v]][l]);\n                }\n            }\n            return total;\n        };\n\n        long long curScore = edgeScore(placed);\n\n        const int MAX_ITER = 12000;   // enough for 2\u202fsec total\n        for (int it = 0; it < MAX_ITER; ++it) {\n            // pick a random placed cell and a random outside seed\n            int cell = cellDist(rng);\n            int outSeed = seedDist(rng);\n            if (inSet[outSeed]) continue;          // already placed\n\n            int oldSeed = placed[cell];\n            // compute delta only on edges incident to 'cell'\n            long long delta = 0;\n            for (int nb : neigh[cell]) {\n                // edge (cell, nb) before swap\n                for (int l = 0; l < M; ++l)\n                    delta -= max(seed[oldSeed][l], seed[placed[nb]][l]);\n                // after swap\n                for (int l = 0; l < M; ++l)\n                    delta += max(seed[outSeed][l], seed[placed[nb]][l]);\n            }\n\n            // accept if not worse\n            if (curScore + delta >= curScore) {\n                // update structures\n                curScore += delta;\n                placed[cell] = outSeed;\n                inSet[oldSeed] = 0;\n                inSet[outSeed] = 1;\n            }\n        }\n\n        /* ------------------------------------------------------------\n           5) output placement in row\u2011major order\n        ------------------------------------------------------------ */\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (c) cout << ' ';\n                cout << placed[id(r, c)];\n            }\n            cout << '\\n';\n        }\n        cout.flush();\n\n        /* ------------------------------------------------------------\n           6) read next generation of seeds\n        ------------------------------------------------------------ */\n        for (int i = 0; i < SEED_CNT; ++i)\n            for (int j = 0; j < M; ++j)\n                cin >> seed[i][j];\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- Hungarian algorithm (min cost assignment) ---------- */\nconst long long INF = (1LL << 60);\n\nvector<int> hungarian(const vector<vector<long long>>& a) {\n    // a is n x n matrix, returns vector p where p[i] = matched column for row i\n    int n = (int)a.size();\n    vector<long long> u(n + 1), v(n + 1);\n    vector<int> p(n + 1), way(n + 1);\n    for (int i = 1; i <= n; ++i) {\n        p[0] = i;\n        long long j0 = 0;\n        vector<long long> minv(n + 1, INF);\n        vector<char> used(n + 1, false);\n        do {\n            used[j0] = true;\n            int i0 = p[j0];\n            long long delta = INF;\n            long long j1 = 0;\n            for (int j = 1; j <= n; ++j) if (!used[j]) {\n                long long cur = a[i0 - 1][j - 1] - u[i0] - v[j];\n                if (cur < minv[j]) { minv[j] = cur; way[j] = (int)j0; }\n                if (minv[j] < delta) { delta = minv[j]; j1 = j; }\n            }\n            for (int j = 0; j <= n; ++j) {\n                if (used[j]) { u[p[j]] += delta; v[j] -= delta; }\n                else           minv[j] -= delta;\n            }\n            j0 = j1;\n        } while (p[j0] != 0);\n        // augmenting\n        do {\n            int j1 = way[j0];\n            p[j0] = p[j1];\n            j0 = j1;\n        } while (j0);\n    }\n    vector<int> ans(n);\n    for (int j = 1; j <= n; ++j) ans[p[j] - 1] = j - 1;\n    return ans; // row i -> column ans[i]\n}\n\n/* ------------------------------------------------------------- */\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, V;\n    if (!(cin >> N >> M >> V)) return 0;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) cin >> s[i];\n    for (int i = 0; i < N; ++i) cin >> t[i];\n\n    /* ---- robot arm description (2 vertices) ---- */\n    cout << 2 << \"\\n\";                // V'\n    cout << 0 << ' ' << 1 << \"\\n\";    // parent of vertex 1, length = 1\n    cout << 0 << ' ' << 0 << \"\\n\";    // root initial position\n\n    /* ---- collect cells, removing already\u2011correct ones ---- */\n    using P = pair<int,int>;\n    vector<P> src, dst;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            bool has = (s[i][j] == '1');\n            bool need = (t[i][j] == '1');\n            if (has && need) continue;          // already correct\n            if (has) src.emplace_back(i, j);\n            if (need) dst.emplace_back(i, j);\n        }\n    }\n    int K = (int)src.size();               // = dst.size()\n    if (K == 0) return 0;                  // nothing to do\n\n    /* ---- build cost matrix (Manhattan distance) ---- */\n    vector<vector<long long>> cost(K, vector<long long>(K));\n    for (int i = 0; i < K; ++i) {\n        for (int j = 0; j < K; ++j) {\n            cost[i][j] = llabs(src[i].first - dst[j].first) +\n                         llabs(src[i].second - dst[j].second);\n        }\n    }\n\n    /* ---- optimal matching ---- */\n    vector<int> match = hungarian(cost);    // src i -> dst[ match[i] ]\n\n    /* ---- create vector of pairs and sort for better travel order ---- */\n    struct Job { int sx, sy, dx, dy; };\n    vector<Job> jobs;\n    jobs.reserve(K);\n    for (int i = 0; i < K; ++i) {\n        auto [sx, sy] = src[i];\n        auto [dx, dy] = dst[match[i]];\n        jobs.push_back({sx, sy, dx, dy});\n    }\n    sort(jobs.begin(), jobs.end(),\n         [](const Job& a, const Job& b){\n             if (a.sx != b.sx) return a.sx < b.sx;\n             return a.sy < b.sy;\n         });\n\n    /* ---- state of the robot ---- */\n    const int dx_dir[4] = {0, 1, 0, -1};   // U D L R   (x downwards)\n    const int dy_dir[4] = {1, 0, -1, 0};\n\n    int cur_x = 0, cur_y = 0;   // root position\n    int cur_dir = 0;            // 0 = right, 1 = down, 2 = left, 3 = up\n\n    auto output_turn = [&](char mv, char rot,\n                           char act_root = '.', char act_leaf = '.') {\n        string S;\n        S.reserve(4);\n        S.push_back(mv);          // move whole arm\n        S.push_back(rot);         // rotate leaf\n        S.push_back(act_root);    // vertex 0 action\n        S.push_back(act_leaf);    // vertex 1 action\n        cout << S << \"\\n\";\n    };\n\n    auto move_root_to = [&](int tx, int ty) {\n        while (cur_x != tx || cur_y != ty) {\n            char mv = '.';\n            if (cur_x < tx) { ++cur_x; mv = 'D'; }\n            else if (cur_x > tx) { --cur_x; mv = 'U'; }\n            else if (cur_y < ty) { ++cur_y; mv = 'R'; }\n            else if (cur_y > ty) { --cur_y; mv = 'L'; }\n            output_turn(mv, '.');\n        }\n    };\n\n    auto rotate_to = [&](int desired_dir) {\n        while (cur_dir != desired_dir) {\n            output_turn('.', 'R');          // clockwise\n            cur_dir = (cur_dir + 1) & 3;\n        }\n    };\n\n    // move fingertip to a given cell (cx,cy)\n    auto go_to_cell = [&](int cx, int cy) {\n        int chosen = -1, rx = 0, ry = 0;\n        for (int d = 0; d < 4; ++d) {\n            int nx = cx - dx_dir[d];\n            int ny = cy - dy_dir[d];\n            if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                chosen = d;\n                rx = nx; ry = ny;\n                break;\n            }\n        }\n        move_root_to(rx, ry);\n        rotate_to(chosen);\n    };\n\n    /* ---- execute all jobs ---- */\n    for (const auto& j : jobs) {\n        // go to source, pick\n        go_to_cell(j.sx, j.sy);\n        output_turn('.', '.', '.', 'P');   // pick\n        // go to destination, drop\n        go_to_cell(j.dx, j.dy);\n        output_turn('.', '.', '.', 'P');   // drop\n    }\n\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n    const int M = 2 * N;\n    vector<Point> mackerel(N), sardine(N);\n    for (int i = 0; i < N; ++i) cin >> mackerel[i].x >> mackerel[i].y;\n    for (int i = 0; i < N; ++i) cin >> sardine[i].x >> sardine[i].y;\n\n    // ------------------------------------------------------------\n    // 1. collect coordinates for compression\n    vector<int> xs_all, ys_all;\n    xs_all.reserve(M);\n    ys_all.reserve(M);\n    for (auto &p : mackerel) {\n        xs_all.push_back(p.x);\n        ys_all.push_back(p.y);\n    }\n    for (auto &p : sardine) {\n        xs_all.push_back(p.x);\n        ys_all.push_back(p.y);\n    }\n    sort(xs_all.begin(), xs_all.end());\n    xs_all.erase(unique(xs_all.begin(), xs_all.end()), xs_all.end());\n    sort(ys_all.begin(), ys_all.end());\n    ys_all.erase(unique(ys_all.begin(), ys_all.end()), ys_all.end());\n\n    const int LIMIT = 200;                 // maximal number of grid lines\n    vector<int> X, Y;\n    auto downsample = [&](const vector<int>& src, vector<int>& dst) {\n        int sz = (int)src.size();\n        if (sz <= LIMIT) {\n            dst = src;\n            return;\n        }\n        int step = sz / LIMIT;\n        for (int i = 0; i < sz; i += step) dst.push_back(src[i]);\n        if (dst.back() != src.back()) dst.push_back(src.back());\n    };\n    downsample(xs_all, X);\n    downsample(ys_all, Y);\n    int Tx = (int)X.size();\n    int Ty = (int)Y.size();\n\n    // ------------------------------------------------------------\n    // 2. build weight matrix\n    vector<vector<int>> mat(Tx, vector<int>(Ty, 0));\n\n    auto add_point = [&](const Point& p, int w) {\n        int cx = int(upper_bound(X.begin(), X.end(), p.x) - X.begin()) - 1;\n        int cy = int(upper_bound(Y.begin(), Y.end(), p.y) - Y.begin()) - 1;\n        // safety \u2013 clamp\n        if (cx < 0) cx = 0;\n        if (cy < 0) cy = 0;\n        if (cx >= Tx) cx = Tx - 1;\n        if (cy >= Ty) cy = Ty - 1;\n        mat[cx][cy] += w;\n    };\n    for (auto &p : mackerel) add_point(p, +1);\n    for (auto &p : sardine)  add_point(p, -1);\n\n    // ------------------------------------------------------------\n    // 3. maximum\u2011sum rectangle (Kadane 2\u2011D)\n    long long bestSum = LLONG_MIN;\n    int bestL = 0, bestR = 0, bestYlow = 0, bestYhigh = 0;\n\n    vector<long long> tmp(Ty);\n    for (int L = 0; L < Tx; ++L) {\n        fill(tmp.begin(), tmp.end(), 0);\n        for (int R = L; R < Tx; ++R) {\n            for (int y = 0; y < Ty; ++y) tmp[y] += mat[R][y];\n\n            // Kadane on tmp\n            long long cur = tmp[0];\n            long long bestRow = tmp[0];\n            int curStart = 0, bestStart = 0, bestEnd = 0;\n            for (int y = 1; y < Ty; ++y) {\n                if (cur < 0) {\n                    cur = tmp[y];\n                    curStart = y;\n                } else {\n                    cur += tmp[y];\n                }\n                if (cur > bestRow) {\n                    bestRow = cur;\n                    bestStart = curStart;\n                    bestEnd = y;\n                }\n            }\n            if (bestRow > bestSum) {\n                bestSum = bestRow;\n                bestL = L; bestR = R;\n                bestYlow = bestStart;\n                bestYhigh = bestEnd;\n            }\n        }\n    }\n\n    // ------------------------------------------------------------\n    // 4. output\n    if (bestSum <= 0) {           // fallback to a tiny empty rectangle\n        cout << 4 << '\\n';\n        cout << 0 << ' ' << 0 << '\\n';\n        cout << 1 << ' ' << 0 << '\\n';\n        cout << 1 << ' ' << 1 << '\\n';\n        cout << 0 << ' ' << 1 << '\\n';\n        return 0;\n    }\n\n    int xl = X[bestL];\n    int xr = X[bestR];\n    int yl = Y[bestYlow];\n    int yr = Y[bestYhigh];\n\n    if (xl == xr) { ++xr; if (xr > 100000) xr = 100000; }\n    if (yl == yr) { ++yr; if (yr > 100000) yr = 100000; }\n\n    cout << 4 << '\\n';\n    cout << xl << ' ' << yl << '\\n';\n    cout << xr << ' ' << yl << '\\n';\n    cout << xr << ' ' << yr << '\\n';\n    cout << xl << ' ' << yr << '\\n';\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Placed {\n    long long x, y;          // bottom\u2011left corner\n    long long w, h;          // width, height after rotation\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    long long sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n\n    vector<long long> w_obs(N), h_obs(N);\n    for (int i = 0; i < N; ++i) cin >> w_obs[i] >> h_obs[i];\n\n    /* ------------------------------------------------------------\n       1. Greedy placement (order 0 .. N-1, only direction U)\n       ------------------------------------------------------------ */\n    vector<int>     chosen_rot(N);   // 0 = keep, 1 = rotate\n    vector<int>     chosen_ref(N);   // -1 or previous index\n    vector<Placed>  placed(N);\n\n    long long curW = 0, curH = 0;    // current bounding box\n\n    for (int i = 0; i < N; ++i) {\n        long long bestScore = LLONG_MAX;\n        int      bestRot   = 0;\n        int      bestRef   = -1;\n        long long bestX    = 0, bestY = 0;\n\n        // try both rotations\n        for (int rot = 0; rot <= 1; ++rot) {\n            long long rw = (rot == 0 ? w_obs[i] : h_obs[i]);\n            long long rh = (rot == 0 ? h_obs[i] : w_obs[i]);\n\n            // every possible reference rectangle (or -1)\n            for (int ref = -1; ref < i; ++ref) {\n                long long x = (ref == -1) ? 0LL : placed[ref].x + placed[ref].w;\n\n                // compute y by looking at already placed rectangles whose\n                // horizontal interval intersects [x, x+rw)\n                long long y = 0;\n                for (int j = 0; j < i; ++j) {\n                    long long lx = placed[j].x;\n                    long long rx = placed[j].x + placed[j].w;\n                    if (rx <= x || lx >= x + rw) continue;   // no overlap in x\n                    y = max(y, placed[j].y + placed[j].h);\n                }\n\n                long long newW = max(curW, x + rw);\n                long long newH = max(curH, y + rh);\n                long long score = newW + newH;\n\n                if (score < bestScore) {\n                    bestScore = score;\n                    bestRot   = rot;\n                    bestRef   = ref;\n                    bestX     = x;\n                    bestY     = y;\n                }\n            }\n        }\n\n        // store the chosen placement\n        chosen_rot[i] = bestRot;\n        chosen_ref[i] = bestRef;\n        placed[i] = {bestX, bestY,\n                     (bestRot == 0 ? w_obs[i] : h_obs[i]),\n                     (bestRot == 0 ? h_obs[i] : w_obs[i])};\n\n        curW = max(curW, bestX + placed[i].w);\n        curH = max(curH, bestY + placed[i].h);\n    }\n\n    /* ------------------------------------------------------------\n       2. Output the same placement for every turn\n       ------------------------------------------------------------ */\n    for (int turn = 0; turn < T; ++turn) {\n        cout << N << '\\n';\n        for (int i = 0; i < N; ++i) {\n            cout << i << ' ' << chosen_rot[i] << ' ' << 'U' << ' '\n                 << chosen_ref[i] << '\\n';\n        }\n        cout.flush();\n\n        // read judge's measured box size (ignore)\n        long long Wp, Hp;\n        if (!(cin >> Wp >> Hp)) return 0;\n        (void)Wp; (void)Hp;\n    }\n    return 0;\n}","ahc041":"#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, H;\n    if (!(cin >> N >> M >> H)) return 0;\n\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n\n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n\n    // coordinates are irrelevant for the algorithm \u2013 just consume them\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        (void)x; (void)y;\n    }\n\n    vector<int> parent(N, -1);\n    vector<int> depth(N, -1);\n    vector<char> assigned(N, 0);\n\n    using P = pair<int,int>;                     // (beauty , vertex)\n\n    // heap of all still\u2011unassigned vertices (min\u2011beauty first)\n    priority_queue<P, vector<P>, greater<P>> unassignedHeap;\n    for (int v = 0; v < N; ++v) unassignedHeap.emplace(A[v], v);\n\n    while (!unassignedHeap.empty()) {\n        // find the smallest\u2011beauty vertex that is still free\n        int root = -1;\n        while (!unassignedHeap.empty()) {\n            auto [val, v] = unassignedHeap.top(); unassignedHeap.pop();\n            if (!assigned[v]) { root = v; break; }\n        }\n        if (root == -1) break;   // all vertices are assigned\n\n        // start a new tree with this root\n        parent[root] = -1;\n        depth[root] = 0;\n        assigned[root] = 1;\n\n        // frontier ordered by beauty (min first)\n        priority_queue<P, vector<P>, greater<P>> frontier;\n        frontier.emplace(A[root], root);\n\n        while (!frontier.empty()) {\n            auto [_, u] = frontier.top(); frontier.pop();\n            if (depth[u] == H) continue;          // cannot go deeper\n            for (int v : adj[u]) {\n                if (assigned[v]) continue;\n                parent[v] = u;\n                depth[v] = depth[u] + 1;\n                assigned[v] = 1;\n                frontier.emplace(A[v], v);\n            }\n        }\n    }\n\n    // output parent list\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << parent[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 20;\n    vector<string> g(N);\n    for (int i = 0; i < N; ++i) cin >> g[i];\n\n    struct Op { char d; int p; };\n    vector<Op> ans;\n\n    // collect all Oni positions\n    vector<pair<int,int>> oni;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (g[i][j] == 'x') oni.emplace_back(i, j);\n\n    for (auto [i, j] : oni) {\n        // check freedom in four directions\n        bool freeU = true, freeD = true, freeL = true, freeR = true;\n        for (int ii = 0; ii < i; ++ii) if (g[ii][j] == 'o') freeU = false;\n        for (int ii = i+1; ii < N; ++ii) if (g[ii][j] == 'o') freeD = false;\n        for (int jj = 0; jj < j; ++jj) if (g[i][jj] == 'o') freeL = false;\n        for (int jj = j+1; jj < N; ++jj) if (g[i][jj] == 'o') freeR = false;\n\n        // distances to the corresponding edge\n        int du = i + 1;\n        int dd = N - i;\n        int dl = j + 1;\n        int dr = N - j;\n\n        // choose the free direction with minimal distance\n        int bestDist = INT_MAX;\n        char dir = '?';\n        if (freeU && du < bestDist) { bestDist = du; dir = 'U'; }\n        if (freeD && dd < bestDist) { bestDist = dd; dir = 'D'; }\n        if (freeL && dl < bestDist) { bestDist = dl; dir = 'L'; }\n        if (freeR && dr < bestDist) { bestDist = dr; dir = 'R'; }\n\n        // apply the two opposite shifts\n        if (dir == 'U') {\n            for (int k = 0; k < du; ++k) ans.push_back({'U', j});\n            for (int k = 0; k < du; ++k) ans.push_back({'D', j});\n        } else if (dir == 'D') {\n            for (int k = 0; k < dd; ++k) ans.push_back({'D', j});\n            for (int k = 0; k < dd; ++k) ans.push_back({'U', j});\n        } else if (dir == 'L') {\n            for (int k = 0; k < dl; ++k) ans.push_back({'L', i});\n            for (int k = 0; k < dl; ++k) ans.push_back({'R', i});\n        } else if (dir == 'R') {\n            for (int k = 0; k < dr; ++k) ans.push_back({'R', i});\n            for (int k = 0; k < dr; ++k) ans.push_back({'L', i});\n        }\n        // after this Oni is considered removed; we do not modify g\n    }\n\n    for (auto [c, p] : ans) {\n        cout << c << ' ' << p << '\\n';\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = double;\n\n/* ---------- global data ---------- */\nstatic const int N = 100;          // fixed by the problem\nstatic const ll L = 500000;       // fixed\nstatic vector<int> T;             // target frequencies\nstatic vector<ll> pref;           // prefix sums of T\n\n/* ---------- weighted sampler (probability proportional to T[i]) ---------- */\nint weighted_sample(mt19937 &rng) {\n    uniform_int_distribution<ll> dist(0, L - 1);\n    ll r = dist(rng);\n    int lo = 0, hi = N - 1;\n    while (lo < hi) {\n        int mid = (lo + hi) >> 1;\n        if (pref[mid] > r) hi = mid;\n        else lo = mid + 1;\n    }\n    return lo;                    // 0 <= lo < N\n}\n\n/* ---------- fast evaluation using power iteration ---------- */\nld evaluate(const array<array<int, N>, N> &ab) {\n    // build transition matrix prob[i][j] (double)\n    static ld prob[N][N];\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            prob[i][j] = 0.0;\n\n    for (int i = 0; i < N; ++i) {\n        prob[i][ab[i][0]] += 0.5;   // a[i]\n        prob[i][ab[i][1]] += 0.5;   // b[i]\n    }\n\n    // power iteration\n    static ld v[N], v2[N];\n    for (int i = 0; i < N; ++i) v[i] = 1.0 / N;   // uniform start\n\n    const int ITER = 500;        // enough for convergence (N=100)\n    for (int it = 0; it < ITER; ++it) {\n        for (int j = 0; j < N; ++j) v2[j] = 0.0;\n        for (int i = 0; i < N; ++i) {\n            if (v[i] == 0.0) continue;\n            for (int j = 0; j < N; ++j) {\n                if (prob[i][j] != 0.0) v2[j] += v[i] * prob[i][j];\n            }\n        }\n        for (int i = 0; i < N; ++i) v[i] = v2[i];\n    }\n\n    // compute error \u03a3 |v[i]*L - T[i]|\n    ld err = 0.0;\n    for (int i = 0; i < N; ++i) {\n        ld expected = v[i] * (ld)L;\n        err += fabs(expected - (ld)T[i]);\n    }\n    return err;\n}\n\n/* ---------- main ---------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // input (N and L are fixed, but we read them for completeness)\n    int readN; ll readL;\n    if (!(cin >> readN >> readL)) return 0;\n    T.assign(N, 0);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n\n    // prefix sums for weighted sampling\n    pref.assign(N, 0);\n    ll acc = 0;\n    for (int i = 0; i < N; ++i) {\n        acc += T[i];\n        pref[i] = acc;\n    }\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    // initial candidate (both edges drawn proportionally to T)\n    array<array<int, N>, N> cur;          // cur[i][0]=a[i], cur[i][1]=b[i]\n    for (int i = 0; i < N; ++i) {\n        cur[i][0] = weighted_sample(rng);\n        cur[i][1] = weighted_sample(rng);\n    }\n\n    ld bestErr = evaluate(cur);\n    auto best = cur;\n\n    // time\u2011controlled hill climbing\n    const double TIME_BUDGET = 1.90;       // seconds\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_BUDGET) break;\n\n        // propose a small mutation\n        array<array<int, N>, N> cand = best;\n        int i = rng() % N;\n        bool changeA = (rng() & 1);\n        if (changeA) cand[i][0] = weighted_sample(rng);\n        else        cand[i][1] = weighted_sample(rng);\n\n        ld curErr = evaluate(cand);\n        if (curErr < bestErr) {\n            bestErr = curErr;\n            best = cand;\n        }\n    }\n\n    // output the best plan found\n    for (int i = 0; i < N; ++i) {\n        cout << best[i][0] << ' ' << best[i][1] << '\\n';\n    }\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing int64 = long long;\nusing u64   = unsigned long long;\n\n/* -------------------------------------------------------------\n   Hilbert order (grid size 2^14 > 10000)\n   ------------------------------------------------------------- */\nstatic inline void rot(int n, int &x, int &y, int rx, int ry) {\n    if (ry == 0) {\n        if (rx == 1) {\n            x = n - 1 - x;\n            y = n - 1 - y;\n        }\n        swap(x, y);\n    }\n}\nstatic inline u64 hilbertOrder(int x, int y) {\n    const int LOG = 14;                     // 2^14 = 16384 > 10000\n    u64 d = 0;\n    int s = 1 << (LOG - 1);\n    for (int i = LOG; i > 0; --i) {\n        int rx = (x & s) > 0;\n        int ry = (y & s) > 0;\n        d <<= 2;\n        d |= (u64)(rx * 3 ^ ry);\n        rot(s, x, y, rx, ry);\n        s >>= 1;\n    }\n    return d;\n}\n\n/* -------------------------------------------------------------\n   Disjoint Set Union\n   ------------------------------------------------------------- */\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\n/* -------------------------------------------------------------\n   Main\n   ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    vector<int> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cx[i] = (lx + rx) / 2;\n        cy[i] = (ly + ry) / 2;\n    }\n\n    // Hilbert order for each city\n    vector<u64> ord(N);\n    for (int i = 0; i < N; ++i) ord[i] = hilbertOrder(cx[i], cy[i]);\n\n    // ids sorted by Hilbert order\n    vector<int> ids(N);\n    iota(ids.begin(), ids.end(), 0);\n    sort(ids.begin(), ids.end(),\n         [&](int a, int b) { return ord[a] < ord[b]; });\n\n    cout << \"!\\n\";\n\n    int pos = 0;                       // next unused position in ids\n    for (int g = 0; g < M; ++g) {\n        int sz = G[g];\n        vector<int> group;\n        group.reserve(sz);\n        for (int i = 0; i < sz; ++i) group.push_back(ids[pos++]);\n\n        // output the list of cities belonging to this group\n        for (int i = 0; i < sz; ++i) {\n            if (i) cout << ' ';\n            cout << group[i];\n        }\n        cout << '\\n';\n\n        if (sz == 1) continue;        // no edge needed\n\n        // ---- build MST of this group (Kruskal) ----\n        struct Edge {\n            int64 w;\n            int u, v;\n            bool operator<(Edge const& other) const {\n                if (w != other.w) return w < other.w;\n                if (u != other.u) return u < other.u;\n                return v < other.v;\n            }\n        };\n        vector<Edge> edges;\n        edges.reserve( (size_t)sz * (sz - 1) / 2 );\n        for (int i = 0; i < sz; ++i) {\n            int a = group[i];\n            for (int j = i + 1; j < sz; ++j) {\n                int b = group[j];\n                int64 dx = (int64)cx[a] - cx[b];\n                int64 dy = (int64)cy[a] - cy[b];\n                edges.push_back({dx * dx + dy * dy, a, b});\n            }\n        }\n        sort(edges.begin(), edges.end());\n\n        DSU dsu(N);                     // global DSU, works on city ids\n        int added = 0;\n        for (auto const& e : edges) {\n            if (dsu.unite(e.u, e.v)) {\n                cout << e.u << ' ' << e.v << '\\n';\n                if (++added == sz - 1) break;\n            }\n        }\n    }\n    return 0;\n}","ahc046":"#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    if (!(cin >> N >> M)) return 0;\n    vector<pair<int,int>> p(M);\n    for (int i = 0; i < M; ++i) cin >> p[i].first >> p[i].second;\n\n    int cur_i = p[0].first;\n    int cur_j = p[0].second;\n\n    // store output lines to print at the end (optional)\n    vector<string> out;\n\n    for (int t = 1; t < M; ++t) {\n        int ti = p[t].first;\n        int tj = p[t].second;\n\n        // vertical moves\n        while (cur_i < ti) {\n            out.emplace_back(\"M D\");\n            ++cur_i;\n        }\n        while (cur_i > ti) {\n            out.emplace_back(\"M U\");\n            --cur_i;\n        }\n        // horizontal moves\n        while (cur_j < tj) {\n            out.emplace_back(\"M R\");\n            ++cur_j;\n        }\n        while (cur_j > tj) {\n            out.emplace_back(\"M L\");\n            --cur_j;\n        }\n    }\n\n    for (const auto& s : out) cout << s << '\\n';\n    return 0;\n}"},"8":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int x, y;\n    long long r;\n};\n\nstruct Rect {\n    int x0, y0, x1, y1;                 // half\u2011open [x0,x1) \u00d7 [y0,y1)\n};\n\nint n;\nvector<Company> comp;\nvector<Rect> ans;                      // final rectangles\n\n/*--------------------------------------------------------------*/\n/* Split information */\nstruct SplitInfo {\n    bool feasible = false;\n    bool isVertical = false;\n    long long error = LLONG_MAX;\n    int splitCoord = -1;\n    vector<int> leftIds, rightIds;\n};\n\n/*--------------------------------------------------------------*/\n/* Evaluate all vertical splits inside 'cur' */\nSplitInfo evaluateVertical(const vector<int>& ids, const Rect& cur) {\n    SplitInfo best;\n    if (cur.x1 - cur.x0 < 2) return best;\n\n    vector<int> order = ids;\n    sort(order.begin(), order.end(),\n         [&](int a, int b){ return comp[a].x < comp[b].x; });\n\n    int m = order.size();\n    vector<long long> pref(m);\n    pref[0] = comp[order[0]].r;\n    for (int i = 1; i < m; ++i) pref[i] = pref[i-1] + comp[order[i]].r;\n    long long total = pref.back();\n\n    int height = cur.y1 - cur.y0;\n\n    for (int k = 1; k < m; ++k) {\n        vector<int> left(order.begin(), order.begin() + k);\n        vector<int> right(order.begin() + k, order.end());\n\n        int maxX = -1, minX = 10000;\n        for (int i : left)  maxX = max(maxX, comp[i].x);\n        for (int i : right) minX = min(minX, comp[i].x);\n        if (maxX + 1 > minX) continue;\n\n        long long sumL = pref[k-1];\n        long long sumR = total - sumL;\n\n        long long ideal = cur.x0 + ( (__int128)sumL + height/2 ) / height;\n        int split = (int)min<long long>(max<long long>(ideal, maxX + 1), minX);\n        if (split <= cur.x0 || split >= cur.x1) continue;\n\n        long long areaL = 1LL * (split - cur.x0) * height;\n        long long areaR = 1LL * (cur.x1 - split) * height;\n        long long err = llabs(areaL - sumL) + llabs(areaR - sumR);\n\n        if (err < best.error) {\n            best.feasible = true;\n            best.isVertical = true;\n            best.error = err;\n            best.splitCoord = split;\n            best.leftIds = move(left);\n            best.rightIds = move(right);\n        }\n    }\n    return best;\n}\n\n/* Evaluate all horizontal splits inside 'cur' */\nSplitInfo evaluateHorizontal(const vector<int>& ids, const Rect& cur) {\n    SplitInfo best;\n    if (cur.y1 - cur.y0 < 2) return best;\n\n    vector<int> order = ids;\n    sort(order.begin(), order.end(),\n         [&](int a, int b){ return comp[a].y < comp[b].y; });\n\n    int m = order.size();\n    vector<long long> pref(m);\n    pref[0] = comp[order[0]].r;\n    for (int i = 1; i < m; ++i) pref[i] = pref[i-1] + comp[order[i]].r;\n    long long total = pref.back();\n\n    int width = cur.x1 - cur.x0;\n\n    for (int k = 1; k < m; ++k) {\n        vector<int> top(order.begin(), order.begin() + k);\n        vector<int> bottom(order.begin() + k, order.end());\n\n        int maxY = -1, minY = 10000;\n        for (int i : top)    maxY = max(maxY, comp[i].y);\n        for (int i : bottom) minY = min(minY, comp[i].y);\n        if (maxY + 1 > minY) continue;\n\n        long long sumT = pref[k-1];\n        long long sumB = total - sumT;\n\n        long long ideal = cur.y0 + ( (__int128)sumT + width/2 ) / width;\n        int split = (int)min<long long>(max<long long>(ideal, maxY + 1), minY);\n        if (split <= cur.y0 || split >= cur.y1) continue;\n\n        long long areaT = 1LL * (split - cur.y0) * width;\n        long long areaB = 1LL * (cur.y1 - split) * width;\n        long long err = llabs(areaT - sumT) + llabs(areaB - sumB);\n\n        if (err < best.error) {\n            best.feasible = true;\n            best.isVertical = false;\n            best.error = err;\n            best.splitCoord = split;\n            best.leftIds = move(top);\n            best.rightIds = move(bottom);\n        }\n    }\n    return best;\n}\n\n/*--------------------------------------------------------------*/\n/* Guillotine partition (same as before) */\nvoid guillotine(const vector<int>& ids, const Rect& cur) {\n    if (ids.size() == 1) {\n        int i = ids[0];\n        ans[i] = cur;\n        return;\n    }\n\n    SplitInfo vInfo = evaluateVertical(ids, cur);\n    SplitInfo hInfo = evaluateHorizontal(ids, cur);\n\n    SplitInfo best;\n    if (vInfo.feasible && (!hInfo.feasible || vInfo.error <= hInfo.error))\n        best = vInfo;\n    else if (hInfo.feasible)\n        best = hInfo;\n\n    if (best.feasible) {\n        if (best.isVertical) {\n            Rect leftR  {cur.x0, cur.y0, best.splitCoord, cur.y1};\n            Rect rightR {best.splitCoord, cur.y0, cur.x1, cur.y1};\n            guillotine(best.leftIds,  leftR);\n            guillotine(best.rightIds, rightR);\n        } else {\n            Rect topR    {cur.x0, cur.y0, cur.x1, best.splitCoord};\n            Rect bottomR {cur.x0, best.splitCoord, cur.x1, cur.y1};\n            guillotine(best.leftIds,  topR);\n            guillotine(best.rightIds, bottomR);\n        }\n        return;\n    }\n\n    // fallback \u2013 unit cells (always feasible)\n    for (int i : ids) {\n        ans[i] = {comp[i].x, comp[i].y, comp[i].x + 1, comp[i].y + 1};\n    }\n}\n\n/*--------------------------------------------------------------*/\n/* Geometry helpers */\ninline bool overlapPositive(const Rect& a, const Rect& b) {\n    return (a.x0 < b.x1 && a.x1 > b.x0 && a.y0 < b.y1 && a.y1 > b.y0);\n}\ninline long long area(const Rect& r) {\n    return 1LL * (r.x1 - r.x0) * (r.y1 - r.y0);\n}\n\n/*--------------------------------------------------------------*/\n/* Safe local border improvement */\nvoid improveBorders(int passes = 3, int range = 2) {\n    // pre\u2011compute point locations (they are the lower\u2011left integer cell)\n    vector<int> px(n), py(n);\n    for (int i = 0; i < n; ++i) {\n        px[i] = comp[i].x;\n        py[i] = comp[i].y;\n    }\n\n    for (int it = 0; it < passes; ++it) {\n        bool anyChange = false;\n\n        // ---- vertical neighbours ----\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) if (i != j) {\n                // i is left of j and they share a vertical side\n                if (ans[i].x1 != ans[j].x0) continue;\n                int y0 = max(ans[i].y0, ans[j].y0);\n                int y1 = min(ans[i].y1, ans[j].y1);\n                if (y0 >= y1) continue;               // no common segment\n\n                int border = ans[i].x1;                // current split x\n                int curErr = llabs(area(ans[i]) - comp[i].r) + llabs(area(ans[j]) - comp[j].r);\n                int bestDelta = 0;\n                long long bestErr = curErr;\n\n                for (int d = -range; d <= range; ++d) if (d != 0) {\n                    int nb = border + d;\n                    // widths must stay positive\n                    if (nb - ans[i].x0 <= 0) continue;\n                    if (ans[j].x1 - nb <= 0) continue;\n                    // point containment\n                    if (px[i] + 1 > nb) continue;          // point i must stay left\n                    if (px[j]     < nb) continue;          // point j must stay right\n\n                    // temporary rectangles\n                    Rect ti = ans[i];\n                    Rect tj = ans[j];\n                    ti.x1 = nb;\n                    tj.x0 = nb;\n\n                    // check against all other rectangles\n                    bool ok = true;\n                    for (int k = 0; k < n; ++k) if (k != i && k != j) {\n                        if (overlapPositive(ti, ans[k]) || overlapPositive(tj, ans[k])) {\n                            ok = false; break;\n                        }\n                    }\n                    if (!ok) continue;\n\n                    long long newErr = llabs(area(ti) - comp[i].r) + llabs(area(tj) - comp[j].r);\n                    if (newErr < bestErr) {\n                        bestErr = newErr;\n                        bestDelta = d;\n                    }\n                }\n\n                if (bestDelta != 0) {\n                    int nb = border + bestDelta;\n                    ans[i].x1 = nb;\n                    ans[j].x0 = nb;\n                    anyChange = true;\n                }\n            }\n        }\n\n        // ---- horizontal neighbours ----\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) if (i != j) {\n                // i is above j and they share a horizontal side\n                if (ans[i].y1 != ans[j].y0) continue;\n                int x0 = max(ans[i].x0, ans[j].x0);\n                int x1 = min(ans[i].x1, ans[j].x1);\n                if (x0 >= x1) continue;               // no common segment\n\n                int border = ans[i].y1;                // current split y\n                int curErr = llabs(area(ans[i]) - comp[i].r) + llabs(area(ans[j]) - comp[j].r);\n                int bestDelta = 0;\n                long long bestErr = curErr;\n\n                for (int d = -range; d <= range; ++d) if (d != 0) {\n                    int nb = border + d;\n                    if (nb - ans[i].y0 <= 0) continue;\n                    if (ans[j].y1 - nb <= 0) continue;\n                    if (py[i] + 1 > nb) continue;          // point i must stay above\n                    if (py[j]     < nb) continue;          // point j must stay below\n\n                    Rect ti = ans[i];\n                    Rect tj = ans[j];\n                    ti.y1 = nb;\n                    tj.y0 = nb;\n\n                    bool ok = true;\n                    for (int k = 0; k < n; ++k) if (k != i && k != j) {\n                        if (overlapPositive(ti, ans[k]) || overlapPositive(tj, ans[k])) {\n                            ok = false; break;\n                        }\n                    }\n                    if (!ok) continue;\n\n                    long long newErr = llabs(area(ti) - comp[i].r) + llabs(area(tj) - comp[j].r);\n                    if (newErr < bestErr) {\n                        bestErr = newErr;\n                        bestDelta = d;\n                    }\n                }\n\n                if (bestDelta != 0) {\n                    int nb = border + bestDelta;\n                    ans[i].y1 = nb;\n                    ans[j].y0 = nb;\n                    anyChange = true;\n                }\n            }\n        }\n\n        if (!anyChange) break;\n    }\n}\n\n/*--------------------------------------------------------------*/\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> n)) return 0;\n    comp.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> comp[i].x >> comp[i].y >> comp[i].r;\n    }\n    ans.assign(n, {0,0,0,0});\n\n    vector<int> allIds(n);\n    iota(allIds.begin(), allIds.end(), 0);\n    Rect whole{0,0,10000,10000};\n\n    guillotine(allIds, whole);          // initial guillotine partition\n    improveBorders(3,2);                 // safe local refinement\n\n    for (int i = 0; i < n; ++i) {\n        const auto &r = ans[i];\n        cout << r.x0 << ' ' << r.y0 << ' ' << r.x1 << ' ' << r.y1 << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 50;\n    int si, sj;\n    if (!(cin >> si >> sj)) return 0;\n\n    /* ---------- read tile ids ---------- */\n    int tile[N][N];\n    int maxTid = -1;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            cin >> tile[i][j];\n            maxTid = max(maxTid, tile[i][j]);\n        }\n\n    /* ---------- read cell values ---------- */\n    int cell[N][N];\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) cin >> cell[i][j];\n\n    int M = maxTid + 1;                     // number of tiles\n    vector<vector<pair<int,int>>> tilePos(M);   // cells belonging to each tile\n    vector<int> tileScore(M, 0);                // sum of cell values per tile\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            int id = tile[i][j];\n            tilePos[id].push_back({i,j});\n            tileScore[id] += cell[i][j];\n        }\n\n    /* ---------- build adjacency list of tiles ---------- */\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    vector<vector<int>> adj(M);\n    set<pair<int,int>> addedEdge;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int a = tile[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d];\n                int nj = j + dj[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int b = tile[ni][nj];\n                if (a == b) continue;\n                auto e = make_pair(min(a,b), max(a,b));\n                if (addedEdge.insert(e).second) {\n                    adj[a].push_back(b);\n                    adj[b].push_back(a);\n                }\n            }\n        }\n    }\n\n    /* ---------- random engine ---------- */\n    std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_real_distribution<double> uni01(0.0, 1.0);\n    std::uniform_real_distribution<double> tiny(0.0, 1e-6);\n\n    const double ALPHA = 0.30;   // weight of bestFuture\n    const double GAMMA = 0.10;   // weight of degree\n    const int TIME_LIMIT_MS = 1850;   // stop a bit before the hard limit\n    const int MAX_ITER = 100000;      // generous upper bound\n\n    string bestPath;\n    long long bestScore = -1;\n\n    auto startClock = chrono::high_resolution_clock::now();\n\n    for (int iter = 0; iter < MAX_ITER; ++iter) {\n        // time guard\n        if (chrono::duration_cast<chrono::milliseconds>(\n                chrono::high_resolution_clock::now() - startClock).count()\n            > TIME_LIMIT_MS) break;\n\n        vector<char> used(M, 0);\n        int ci = si, cj = sj;\n        int curTid = tile[ci][cj];\n        used[curTid] = 1;\n        long long curScore = tileScore[curTid];\n        string curPath;\n\n        while (true) {\n            struct Cand {\n                int tid;\n                int ni, nj;\n                double weight;\n                char dir;\n            };\n            vector<Cand> cand;\n\n            for (int d = 0; d < 4; ++d) {\n                int ni = ci + di[d];\n                int nj = cj + dj[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nid = tile[ni][nj];\n                if (used[nid]) continue;\n\n                // bestFuture: max tileScore among unused neighbours of nid\n                int bestFuture = 0;\n                int degree = 0;\n                for (int nb : adj[nid]) {\n                    if (!used[nb]) {\n                        ++degree;\n                        bestFuture = max(bestFuture, tileScore[nb]);\n                    }\n                }\n\n                double w = tileScore[nid] + ALPHA * bestFuture\n                                          + GAMMA * degree + tiny(rng);\n                char dir = (d == 0 ? 'U' : d == 1 ? 'D' : d == 2 ? 'L' : 'R');\n                cand.push_back({nid, ni, nj, w, dir});\n            }\n\n            if (cand.empty()) break;   // dead end\n\n            // weighted random selection\n            double totalW = 0.0;\n            for (auto &c : cand) totalW += c.weight;\n            double r = uni01(rng) * totalW;\n            double acc = 0.0;\n            int chosen = 0;\n            for (int i = 0; i < (int)cand.size(); ++i) {\n                acc += cand[i].weight;\n                if (r <= acc) { chosen = i; break; }\n            }\n\n            const Cand &c = cand[chosen];\n            curPath.push_back(c.dir);\n            ci = c.ni;  cj = c.nj;\n            used[c.tid] = 1;\n            curScore += tileScore[c.tid];\n        }\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestPath = curPath;\n        }\n    }\n\n    cout << bestPath << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Edge {\n    int to;   // neighbour vertex id\n    int id;   // unique undirected edge id\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int H = 30, W = 30;\n    const int V = H * W;\n    const int E = (H * (W - 1)) + ((H - 1) * W);   // total undirected edges\n\n    // ---------- graph ----------\n    vector<vector<Edge>> g(V);\n    auto vid = [&](int i, int j) { return i * W + j; };\n    int eid = 0;\n\n    // horizontal edges (row i, col j)   0 \u2264 j < W\u20111\n    for (int i = 0; i < H; ++i)\n        for (int j = 0; j < W - 1; ++j) {\n            int a = vid(i, j), b = vid(i, j + 1);\n            g[a].push_back({b, eid});\n            g[b].push_back({a, eid});\n            ++eid;\n        }\n    // vertical edges (row i, col j)     0 \u2264 i < H\u20111\n    for (int i = 0; i < H - 1; ++i)\n        for (int j = 0; j < W; ++j) {\n            int a = vid(i, j), b = vid(i + 1, j);\n            g[a].push_back({b, eid});\n            g[b].push_back({a, eid});\n            ++eid;\n        }\n    assert(eid == E);\n\n    // ---------- learning data ----------\n    vector<long double> total(E, 0.0L);\n    vector<int>        cnt(E, 0);\n    vector<long double> raw(E, 1.0L);   // per\u2011edge average (total / cnt)\n\n    // row/column averages (initially 1.0)\n    vector<long double> horRow(H, 1.0L);\n    vector<long double> verCol(W, 1.0L);\n\n    const int Q = 1000;\n    const int K = 20;          // first K queries: Manhattan walk\n    const int TH = 5;          // threshold to trust per\u2011edge raw value\n\n    for (int q = 0; q < Q; ++q) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) break;\n        int s = vid(si, sj);\n        int t = vid(ti, tj);\n\n        string path;\n        vector<int> used_edges;   // edge ids of the printed path\n\n        if (q < K) {   // ---------- simple Manhattan walk ----------\n            int curi = si, curj = sj;\n            while (curi > ti) { path.push_back('U'); --curi; }\n            while (curi < ti) { path.push_back('D'); ++curi; }\n            while (curj > tj) { path.push_back('L'); --curj; }\n            while (curj < tj) { path.push_back('R'); ++curj; }\n            // collect edges that were traversed\n            curi = si; curj = sj;\n            for (char c : path) {\n                int ni = curi, nj = curj;\n                if (c == 'U') --ni;\n                else if (c == 'D') ++ni;\n                else if (c == 'L') --nj;\n                else ++nj; // 'R'\n                int a = vid(curi, curj);\n                int b = vid(ni, nj);\n                // find edge id between a and b\n                int edge_id = -1;\n                for (const auto &e : g[a]) if (e.to == b) { edge_id = e.id; break; }\n                used_edges.push_back(edge_id);\n                curi = ni; curj = nj;\n            }\n        } else {        // ---------- Dijkstra with learned weights ----------\n            const long double INF = 1e100L;\n            vector<long double> dist(V, INF);\n            vector<int>    prev_v(V, -1);\n            vector<char>   prev_dir(V, 0);\n\n            using State = pair<long double, int>;\n            priority_queue<State, vector<State>, greater<State>> pq;\n            dist[s] = 0;\n            pq.emplace(0.0L, s);\n\n            while (!pq.empty()) {\n                auto [d, v] = pq.top(); pq.pop();\n                if (d != dist[v]) continue;\n                if (v == t) break;\n                for (const auto &e : g[v]) {\n                    long double w;\n                    int vi = v / W, vj = v % W;\n                    int ti2 = e.to / W, tj2 = e.to % W;\n                    if (vi == ti2) {                     // horizontal edge\n                        if (cnt[e.id] >= TH) w = raw[e.id];\n                        else w = horRow[vi];\n                    } else {                             // vertical edge\n                        if (cnt[e.id] >= TH) w = raw[e.id];\n                        else w = verCol[vj];\n                    }\n                    if (dist[e.to] > d + w) {\n                        dist[e.to] = d + w;\n                        prev_v[e.to] = v;\n                        char dir = '?';\n                        if (ti2 == vi - 1) dir = 'U';\n                        else if (ti2 == vi + 1) dir = 'D';\n                        else if (tj2 == vj - 1) dir = 'L';\n                        else if (tj2 == vj + 1) dir = 'R';\n                        prev_dir[e.to] = dir;\n                        pq.emplace(dist[e.to], e.to);\n                    }\n                }\n            }\n\n            // reconstruct path\n            int cur = t;\n            while (cur != s) {\n                int p = prev_v[cur];\n                path.push_back(prev_dir[cur]);\n                // locate edge id between p and cur\n                int edge_id = -1;\n                for (const auto &e : g[p]) if (e.to == cur) { edge_id = e.id; break; }\n                used_edges.push_back(edge_id);\n                cur = p;\n            }\n            reverse(path.begin(), path.end());\n            reverse(used_edges.begin(), used_edges.end());\n        }\n\n        // ---------- output ----------\n        cout << path << '\\n' << flush;\n\n        // ---------- read judge reply ----------\n        long long reported;\n        cin >> reported;   // round(true_len * e_k)\n\n        // ---------- update per\u2011edge statistics ----------\n        int L = (int)used_edges.size();               // number of edges on this path\n        long double avg = (long double)reported / (long double)L; // unbiased contribution\n        for (int id : used_edges) {\n            total[id] += avg;\n            ++cnt[id];\n            raw[id] = total[id] / (long double)cnt[id];\n        }\n\n        // ---------- recompute row / column averages ----------\n        // Horizontal edges: first H*(W-1) ids\n        fill(horRow.begin(), horRow.end(), 0.0L);\n        vector<int> horCnt(H, 0);\n        for (int i = 0; i < H; ++i) {\n            for (int j = 0; j < W - 1; ++j) {\n                int id = i * (W - 1) + j;\n                horRow[i] += raw[id];\n                ++horCnt[i];\n            }\n        }\n        for (int i = 0; i < H; ++i) {\n            if (horCnt[i]) horRow[i] /= (long double)horCnt[i];\n            else horRow[i] = 1.0L;\n        }\n\n        // Vertical edges: ids start after all horizontals\n        fill(verCol.begin(), verCol.end(), 0.0L);\n        vector<int> verCnt(W, 0);\n        int baseVert = H * (W - 1);\n        for (int i = 0; i < H - 1; ++i) {\n            for (int j = 0; j < W; ++j) {\n                int id = baseVert + i * W + j;\n                verCol[j] += raw[id];\n                ++verCnt[j];\n            }\n        }\n        for (int j = 0; j < W; ++j) {\n            if (verCnt[j]) verCol[j] /= (long double)verCnt[j];\n            else verCol[j] = 1.0L;\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;                     // board size (fixed)\n\n/*------------------------------------------------------------*/\n/*  Does string s appear as a horizontal or vertical subsequence */\n/*------------------------------------------------------------*/\nbool appears(const vector<string>& board, const string& s) {\n    int L = (int)s.size();\n\n    // horizontal\n    for (int r = 0; r < N; ++r) {\n        for (int start = 0; start < N; ++start) {\n            bool ok = true;\n            for (int p = 0; p < L; ++p) {\n                int c = (start + p) % N;\n                if (board[r][c] != s[p]) { ok = false; break; }\n            }\n            if (ok) return true;\n        }\n    }\n\n    // vertical\n    for (int c = 0; c < N; ++c) {\n        for (int start = 0; start < N; ++start) {\n            bool ok = true;\n            for (int p = 0; p < L; ++p) {\n                int r = (start + p) % N;\n                if (board[r][c] != s[p]) { ok = false; break; }\n            }\n            if (ok) return true;\n        }\n    }\n    return false;\n}\n\n/*------------------------------------------------------------*/\n/*  Greedy construction of a board for a given order          */\n/*------------------------------------------------------------*/\nvector<string> greedy_build(const vector<string>& strs,\n                            const vector<int>& order,\n                            mt19937& rng) {\n    vector<string> board(N, string(N, '.'));\n\n    uniform_int_distribution<int> dist_letter(0, 7);   // A..H\n\n    for (int idx : order) {\n        const string& s = strs[idx];\n        int L = (int)s.size();\n\n        struct Placement { bool horiz; int line; int start; };\n        vector<Placement> bestList;\n        int bestGain = -1;\n\n        for (int orient = 0; orient < 2; ++orient) {          // 0 = horiz, 1 = vert\n            bool horiz = (orient == 0);\n            for (int line = 0; line < N; ++line) {\n                for (int start = 0; start < N; ++start) {\n                    bool ok = true;\n                    int gain = 0;\n                    for (int p = 0; p < L; ++p) {\n                        int i = horiz ? line : (start + p) % N;\n                        int j = horiz ? (start + p) % N : line;\n                        char cur = board[i][j];\n                        if (cur != '.' && cur != s[p]) { ok = false; break; }\n                        if (cur == '.') ++gain;\n                    }\n                    if (!ok) continue;\n                    if (gain > bestGain) {\n                        bestGain = gain;\n                        bestList.clear();\n                        bestList.push_back({horiz, line, start});\n                    } else if (gain == bestGain) {\n                        bestList.push_back({horiz, line, start});\n                    }\n                }\n            }\n        }\n\n        if (bestList.empty()) continue;   // cannot place this string\n\n        uniform_int_distribution<int> die(0, (int)bestList.size() - 1);\n        Placement pl = bestList[die(rng)];\n\n        // write the string\n        for (int p = 0; p < L; ++p) {\n            int i = pl.horiz ? pl.line : (pl.start + p) % N;\n            int j = pl.horiz ? (pl.start + p) % N : pl.line;\n            board[i][j] = s[p];\n        }\n    }\n\n    // fill remaining '.' with random letters\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (board[i][j] == '.')\n                board[i][j] = char('A' + dist_letter(rng));\n\n    return board;\n}\n\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_input, M;\n    if (!(cin >> N_input >> M)) return 0;   // N_input is always 20, ignored\n    vector<string> strs(M);\n    for (int i = 0; i < M; ++i) cin >> strs[i];\n\n    /*--- order strings by decreasing length (stable) ---*/\n    vector<int> baseOrder(M);\n    iota(baseOrder.begin(), baseOrder.end(), 0);\n    sort(baseOrder.begin(), baseOrder.end(),\n         [&](int a, int b) { return strs[a].size() > strs[b].size(); });\n\n    random_device rd;\n    mt19937 rng(rd());\n\n    vector<string> bestBoard;\n    int bestScore = -1;\n\n    const auto overall_deadline = chrono::steady_clock::now() + chrono::milliseconds(2800);\n    const auto greedy_deadline  = chrono::steady_clock::now() + chrono::milliseconds(1200);\n    const auto insert_deadline  = chrono::steady_clock::now() + chrono::milliseconds(2000);\n\n    /*------------------- greedy restarts -------------------*/\n    while (chrono::steady_clock::now() < greedy_deadline) {\n        // slight randomisation inside equal\u2011length groups\n        vector<int> order = baseOrder;\n        for (size_t i = 0; i + 1 < order.size(); ++i) {\n            if (strs[order[i]].size() == strs[order[i + 1]].size())\n                if (uniform_int_distribution<int>(0, 1)(rng))\n                    swap(order[i], order[i + 1]);\n        }\n\n        vector<string> board = greedy_build(strs, order, rng);\n\n        // evaluate score\n        int cnt = 0;\n        for (const string& s : strs) if (appears(board, s)) ++cnt;\n\n        if (cnt > bestScore) {\n            bestScore = cnt;\n            bestBoard = std::move(board);\n        }\n    }\n\n    /*--------------- insert still\u2011unmatched strings ---------------*/\n    if (!bestBoard.empty()) {\n        vector<string> board = bestBoard;\n        vector<char> matched(M, 0);\n        int curScore = bestScore;\n\n        for (int i = 0; i < M; ++i)\n            if (appears(board, strs[i])) matched[i] = 1;\n\n        while (chrono::steady_clock::now() < insert_deadline) {\n            bool anyPlaced = false;\n\n            // collect unmatched indices and shuffle\n            vector<int> undone;\n            undone.reserve(M);\n            for (int i = 0; i < M; ++i) if (!matched[i]) undone.push_back(i);\n            if (undone.empty()) break;\n            shuffle(undone.begin(), undone.end(), rng);\n\n            for (int idx : undone) {\n                const string& s = strs[idx];\n                int L = (int)s.size();\n\n                struct Placement { bool horiz; int line; int start; };\n                vector<Placement> cand;\n                int bestGain = -1;\n\n                for (int orient = 0; orient < 2; ++orient) {\n                    bool horiz = (orient == 0);\n                    for (int line = 0; line < N; ++line) {\n                        for (int start = 0; start < N; ++start) {\n                            bool ok = true;\n                            int gain = 0;\n                            for (int p = 0; p < L; ++p) {\n                                int i = horiz ? line : (start + p) % N;\n                                int j = horiz ? (start + p) % N : line;\n                                char cur = board[i][j];\n                                if (cur != '.' && cur != s[p]) { ok = false; break; }\n                                if (cur == '.') ++gain;\n                            }\n                            if (!ok) continue;\n                            if (gain > bestGain) {\n                                bestGain = gain;\n                                cand.clear();\n                                cand.push_back({horiz, line, start});\n                            } else if (gain == bestGain) {\n                                cand.push_back({horiz, line, start});\n                            }\n                        }\n                    }\n                }\n                if (cand.empty()) continue;           // cannot place now\n\n                uniform_int_distribution<int> die(0, (int)cand.size() - 1);\n                Placement pl = cand[die(rng)];\n\n                // write the string\n                for (int p = 0; p < L; ++p) {\n                    int i = pl.horiz ? pl.line : (pl.start + p) % N;\n                    int j = pl.horiz ? (pl.start + p) % N : pl.line;\n                    board[i][j] = s[p];\n                }\n                matched[idx] = 1;\n                ++curScore;\n                anyPlaced = true;\n            }\n            if (!anyPlaced) break;\n        }\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestBoard = std::move(board);\n        }\n    }\n\n    /*---------------------- hill\u2011climbing ----------------------*/\n    while (chrono::steady_clock::now() < overall_deadline) {\n        int i = uniform_int_distribution<int>(0, N - 1)(rng);\n        int j = uniform_int_distribution<int>(0, N - 1)(rng);\n        char old = bestBoard[i][j];\n        char nd = char('A' + uniform_int_distribution<int>(0, 7)(rng));\n        if (nd == old) continue;\n\n        bestBoard[i][j] = nd;\n\n        // recompute whole score\n        int newScore = 0;\n        for (const string& s : strs) if (appears(bestBoard, s)) ++newScore;\n\n        if (newScore >= bestScore) {\n            bestScore = newScore;\n        } else {\n            bestBoard[i][j] = old;   // revert\n        }\n    }\n\n    /*----------------------- output ------------------------*/\n    if (bestBoard.empty()) {            // fallback \u2013 completely random board\n        bestBoard.assign(N, string(N, '.'));\n        uniform_int_distribution<int> d(0, 7);\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                bestBoard[i][j] = char('A' + d(rng));\n    }\n\n    for (const string& row : bestBoard) cout << row << '\\n';\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell { int i, j; };\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, si, sj;\n    if (!(cin >> N >> si >> sj)) return 0;\n    vector<string> g(N);\n    for (int i = 0; i < N; ++i) cin >> g[i];\n\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char moveChar[4] = {'U', 'D', 'L', 'R'};\n\n    // map coordinate -> index\n    vector<vector<int>> idx(N, vector<int>(N, -1));\n    vector<Cell> cells;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (g[i][j] != '#') {\n                idx[i][j] = (int)cells.size();\n                cells.push_back({i, j});\n            }\n\n    int V = cells.size();\n    if (V == 0) { cout << \"\\n\"; return 0; }\n\n    // adjacency (only needed for BFS)\n    vector<vector<int>> adj(V);\n    for (int v = 0; v < V; ++v) {\n        int i = cells[v].i, j = cells[v].j;\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + di[d], nj = j + dj[d];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (g[ni][nj] == '#') continue;\n            int u = idx[ni][nj];\n            adj[v].push_back(u);\n        }\n    }\n\n    // helper: BFS from src to the nearest target satisfying predicate `ok`\n    auto bfs_path = [&](int src, const vector<char>& target) {\n        vector<int> pre(V, -1);\n        vector<char> preDir(V, -1);\n        queue<int> q;\n        q.push(src);\n        pre[src] = src;\n        while (!q.empty()) {\n            int v = q.front(); q.pop();\n            if (target[v]) break;               // reached a desired cell\n            int i = cells[v].i, j = cells[v].j;\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d], nj = j + dj[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                if (g[ni][nj] == '#') continue;\n                int u = idx[ni][nj];\n                if (pre[u] != -1) continue;\n                pre[u] = v;\n                preDir[u] = d;                  // direction from v to u\n                q.push(u);\n            }\n        }\n        // locate the first target reached (could be src itself)\n        int targetIdx = -1;\n        for (int v = 0; v < V; ++v)\n            if (target[v] && pre[v] != -1) { targetIdx = v; break; }\n\n        // reconstruct path (list of moves)\n        string path;\n        if (targetIdx == -1) return path;   // should not happen\n        int cur = targetIdx;\n        while (cur != src) {\n            char d = preDir[cur];\n            path.push_back(moveChar[d]);\n            cur = pre[cur];\n        }\n        reverse(path.begin(), path.end());\n        // also return the endpoint index via a static variable (or capture)\n        // but we need both path and endpoint, so we will return pair\n        // We'll wrap this lambda later; for now, just return path\n        return path;\n    };\n\n    // Because we also need the endpoint after reconstruction,\n    // rewrite bfs to return both path string and endpoint index.\n    struct BfsResult {\n        string path;\n        int endIdx;\n    };\n    auto bfs = [&](int src, const vector<char>& target) -> BfsResult {\n        vector<int> pre(V, -1);\n        vector<char> preDir(V, -1);\n        queue<int> q;\n        q.push(src);\n        pre[src] = src;\n        int found = -1;\n        while (!q.empty()) {\n            int v = q.front(); q.pop();\n            if (target[v]) { found = v; break; }\n            int i = cells[v].i, j = cells[v].j;\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d], nj = j + dj[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                if (g[ni][nj] == '#') continue;\n                int u = idx[ni][nj];\n                if (pre[u] != -1) continue;\n                pre[u] = v;\n                preDir[u] = d;\n                q.push(u);\n            }\n        }\n        string path;\n        int endIdx = src;\n        if (found != -1) {\n            endIdx = found;\n            int cur = found;\n            while (cur != src) {\n                char d = preDir[cur];\n                path.push_back(moveChar[d]);\n                cur = pre[cur];\n            }\n            reverse(path.begin(), path.end());\n        }\n        return {path, endIdx};\n    };\n\n    // -----------------------------------------------------------------\n    // Main heuristic tour\n    vector<char> covered(V, 0);\n    int startIdx = idx[si][sj];\n    covered[startIdx] = 1;                       // start cell already visited\n    int remaining = V - 1;\n\n    int curIdx = startIdx;\n    string answer;\n\n    while (remaining > 0) {\n        // build target mask: any uncovered cell\n        vector<char> target(V, 0);\n        for (int v = 0; v < V; ++v) if (!covered[v]) target[v] = 1;\n\n        BfsResult bfsRes = bfs(curIdx, target);\n        // append path\n        answer += bfsRes.path;\n        // mark all cells on the path as covered\n        int walk = curIdx;\n        for (char c : bfsRes.path) {\n            // move according to c\n            int d = (c == 'U') ? 0 : (c == 'D') ? 1 : (c == 'L') ? 2 : 3;\n            int ni = cells[walk].i + di[d];\n            int nj = cells[walk].j + dj[d];\n            walk = idx[ni][nj];\n            if (!covered[walk]) {\n                covered[walk] = 1;\n                --remaining;\n            }\n        }\n        curIdx = bfsRes.endIdx;\n    }\n\n    // finally return to start\n    if (curIdx != startIdx) {\n        vector<char> target(V, 0);\n        target[startIdx] = 1;\n        BfsResult bfsRes = bfs(curIdx, target);\n        answer += bfsRes.path;\n        // (no need to update covered any more)\n    }\n\n    cout << answer << '\\n';\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K, R;\n    if (!(cin >> N >> M >> K >> R)) return 0;\n\n    // required skill vectors \u2013 not used by the algorithm\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) cin >> d[i][j];\n\n    // build DAG\n    vector<vector<int>> out(N);\n    vector<int> indeg(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v;  cin >> u >> v;\n        --u; --v;\n        out[u].push_back(v);\n        ++indeg[v];\n    }\n\n    // task states\n    vector<int> task_state(N, -1);          // -1 not started, 0 started, 1 finished\n    deque<int> ready;\n    for (int i = 0; i < N; ++i) if (indeg[i] == 0) ready.push_back(i);\n\n    // member data\n    vector<int> member_task(M, -1);                 // current task ( -1 = idle )\n    vector<int> start_day(M, -1);                  // day when current task started\n    vector<double> avg_days(M, 1e9);                // estimated average duration\n    vector<int> cnt_done(M, 0);                    // number of completed tasks\n\n    int day = 0;\n    while (true) {\n        ++day;\n\n        // ----------- assignment phase ----------\n        vector<int> idle;\n        for (int j = 0; j < M; ++j) if (member_task[j] == -1) idle.push_back(j);\n        sort(idle.begin(), idle.end(),\n             [&](int a, int b){ return avg_days[a] < avg_days[b]; });\n\n        vector<pair<int,int>> assign;   // (member, task)\n        size_t p = 0;\n        while (p < idle.size() && !ready.empty()) {\n            int j = idle[p];\n            int t = ready.front(); ready.pop_front();\n            member_task[j] = t;\n            start_day[j] = day;\n            task_state[t] = 0;\n            assign.emplace_back(j, t);\n            ++p;\n        }\n\n        // output\n        cout << assign.size();\n        for (auto [mem, tas] : assign) {\n            cout << ' ' << mem + 1 << ' ' << tas + 1;\n        }\n        cout << '\\n';\n        cout.flush();\n\n        // ----------- read judge reply ----------\n        string line;\n        if (!getline(cin, line)) break;\n        while (line.size() && (line.back() == '\\r' || line.back() == '\\n')) line.pop_back();\n        if (line.empty()) {                     // consume possible empty line after previous >>\n            if (!getline(cin, line)) break;\n            while (line.size() && (line.back() == '\\r' || line.back() == '\\n')) line.pop_back();\n        }\n\n        if (line == \"-1\") break;                // finished / day limit\n\n        stringstream ss(line);\n        int cnt;\n        ss >> cnt;\n        vector<int> fin_members(cnt);\n        for (int i = 0; i < cnt; ++i) {\n            ss >> fin_members[i];\n            --fin_members[i];                   // to 0\u2011based\n        }\n\n        // process each finishing member\n        for (int j : fin_members) {\n            int t = member_task[j];\n            if (t == -1) continue;              // safety\n            int dur = day - start_day[j] + 1;    // inclusive\n            // update average duration\n            avg_days[j] = (avg_days[j] * cnt_done[j] + dur) / double(cnt_done[j] + 1);\n            ++cnt_done[j];\n\n            member_task[j] = -1;                // becomes idle\n            task_state[t] = 1;                  // finished\n\n            for (int nxt : out[t]) {\n                if (--indeg[nxt] == 0 && task_state[nxt] == -1) {\n                    ready.push_back(nxt);\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Order {\n    int a, b, c, d;\n};\n\ninline int manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n/* point inside the route */\nstruct Node {\n    int id;          // order index (0\u2011based)\n    bool pickup;     // true = restaurant, false = destination\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const pair<int,int> office = {400, 400};\n\n    /* ---------- read input ---------- */\n    vector<Order> orders(1000);\n    for (auto &o : orders) cin >> o.a >> o.b >> o.c >> o.d;\n\n    /* ---------- 1. select 50 orders with smallest round\u2011trip cost ---------- */\n    struct Cand { long long round; int idx; };\n    vector<Cand> cand(1000);\n    for (int i = 0; i < 1000; ++i) {\n        const Order &o = orders[i];\n        long long inner = manhattan(o.a, o.b, o.c, o.d);\n        long long round = manhattan(office.first, office.second, o.a, o.b)\n                        + inner\n                        + manhattan(o.c, o.d, office.first, office.second);\n        cand[i] = {round, i};\n    }\n    nth_element(cand.begin(), cand.begin() + 50, cand.end(),\n                [](const Cand& x, const Cand& y){ return x.round < y.round; });\n    vector<int> selected;\n    selected.reserve(50);\n    vector<char> isSelected(1000, 0);\n    for (int i = 0; i < 50; ++i) {\n        selected.push_back(cand[i].idx);\n        isSelected[cand[i].idx] = 1;\n    }\n\n    /* ---------- 2. greedy nearest\u2011neighbour (respecting precedence) ---------- */\n    vector<char> takenPickup(1000, 0);\n    vector<char> takenDelivery(1000, 0);\n    vector<Node> path;          // 100 points (pickup / delivery)\n    int curx = office.first, cury = office.second;\n\n    for (int step = 0; step < 100; ++step) {\n        int bestDist = INT_MAX;\n        int bestIdx  = -1;\n        bool bestIsPickup = true;\n\n        for (int id : selected) {\n            if (!takenPickup[id]) {\n                int d = manhattan(curx, cury, orders[id].a, orders[id].b);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx  = id;\n                    bestIsPickup = true;\n                }\n            } else if (!takenDelivery[id]) {\n                int d = manhattan(curx, cury, orders[id].c, orders[id].d);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx  = id;\n                    bestIsPickup = false;\n                }\n            }\n        }\n\n        if (bestIsPickup) {\n            path.push_back({bestIdx, true});\n            takenPickup[bestIdx] = 1;\n            curx = orders[bestIdx].a;\n            cury = orders[bestIdx].b;\n        } else {\n            path.push_back({bestIdx, false});\n            takenDelivery[bestIdx] = 1;\n            curx = orders[bestIdx].c;\n            cury = orders[bestIdx].d;\n        }\n    }\n\n    /* ---------- helper: length of the whole tour ---------- */\n    auto tourLength = [&](const vector<Node>& seq)->long long {\n        long long tot = 0;\n        int x = office.first, y = office.second;\n        for (const auto &nd : seq) {\n            const Order &o = orders[nd.id];\n            if (nd.pickup) {\n                tot += manhattan(x, y, o.a, o.b);\n                x = o.a; y = o.b;\n            } else {\n                tot += manhattan(x, y, o.c, o.d);\n                x = o.c; y = o.d;\n            }\n        }\n        tot += manhattan(x, y, office.first, office.second);\n        return tot;\n    };\n\n    /* ---------- 3. 2\u2011opt local search (respect precedence) ---------- */\n    long long bestLen = tourLength(path);\n    mt19937 rng((unsigned)chrono::high_resolution_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distPos(0, (int)path.size() - 1);\n    const double TIME_LIMIT = 1.8;                     // seconds\n    auto start = chrono::steady_clock::now();\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        int i = distPos(rng);\n        int j = distPos(rng);\n        if (i == j) continue;\n        if (i > j) swap(i, j);\n\n        // reverse segment [i , j]\n        reverse(path.begin() + i, path.begin() + j + 1);\n\n        // precedence check\n        bool ok = true;\n        static int posPickup[1000];\n        static int posDelivery[1000];\n        fill(begin(posPickup), end(posPickup), -1);\n        fill(begin(posDelivery), end(posDelivery), -1);\n        for (int p = 0; p < (int)path.size(); ++p) {\n            const Node &nd = path[p];\n            if (nd.pickup) posPickup[nd.id] = p;\n            else          posDelivery[nd.id] = p;\n        }\n        for (int id : selected) {\n            if (posPickup[id] == -1 || posDelivery[id] == -1 ||\n                posPickup[id] > posDelivery[id]) {\n                ok = false; break;\n            }\n        }\n\n        if (ok) {\n            long long curLen = tourLength(path);\n            if (curLen < bestLen) {\n                bestLen = curLen;               // keep improvement\n                continue;\n            }\n        }\n        // revert the reversal\n        reverse(path.begin() + i, path.begin() + j + 1);\n    }\n\n    /* ---------- 4. output ---------- */\n    cout << 50;\n    for (int id : selected) cout << ' ' << (id + 1);   // 1\u2011based\n    cout << '\\n';\n\n    // build the full coordinate list (office \u2192 points \u2192 office)\n    cout << ( (int)path.size() + 2 );\n    cout << ' ' << office.first << ' ' << office.second;\n    for (const auto &nd : path) {\n        const Order &o = orders[nd.id];\n        if (nd.pickup) cout << ' ' << o.a << ' ' << o.b;\n        else          cout << ' ' << o.c << ' ' << o.d;\n    }\n    cout << ' ' << office.first << ' ' << office.second;\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    // ---- read coordinates ----\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; ++i) cin >> x[i] >> y[i];\n\n    // ---- read edges ----\n    vector<int> u(M), v(M);\n    for (int i = 0; i < M; ++i) cin >> u[i] >> v[i];\n\n    // ---- compute rounded distances d_i ----\n    vector<long long> d(M);\n    for (int i = 0; i < M; ++i) {\n        long long dx = (long long)x[u[i]] - x[v[i]];\n        long long dy = (long long)y[u[i]] - y[v[i]];\n        double eu = sqrt((double)dx * dx + (double)dy * dy);\n        d[i] = llround(eu);\n    }\n\n    // ---- offline MST on d_i (Kruskal) ----\n    vector<int> idx(M);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(),\n         [&](int a, int b) { return d[a] < d[b]; });\n\n    vector<char> inMST(M, 0);\n    DSU dsu_off(N);\n    int added = 0;\n    for (int id : idx) {\n        if (dsu_off.unite(u[id], v[id])) {\n            inMST[id] = 1;\n            ++added;\n            if (added == N - 1) break;\n        }\n    }\n\n    // ---- online phase ----\n    DSU dsu(N);\n    int comp = N;                     // current number of components\n\n    for (int i = 0; i < M; ++i) {\n        long long li;\n        cin >> li;                    // true length (not used)\n\n        if (dsu.find(u[i]) == dsu.find(v[i])) {\n            cout << \"0\\n\";\n            cout.flush();\n            continue;\n        }\n\n        int rem  = M - i - 1;          // edges still unseen\n        int need = comp - 1;           // bridges still required\n\n        bool take = false;\n        if (rem == need)               // forced acceptance\n            take = true;\n        else if (inMST[i])             // promising edge from the lower\u2011bound MST\n            take = true;\n\n        if (take) {\n            cout << \"1\\n\";\n            dsu.unite(u[i], v[i]);\n            --comp;\n        } else {\n            cout << \"0\\n\";\n        }\n        cout.flush();\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos { int x, y; };\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<Pos> petPos(N);\n    vector<int> petType(N);\n    for (int i = 0; i < N; ++i) cin >> petPos[i].x >> petPos[i].y >> petType[i];\n\n    int M;\n    cin >> M;\n    vector<Pos> humanPos(M);\n    for (int i = 0; i < M; ++i) cin >> humanPos[i].x >> humanPos[i].y;\n\n    const int H = 30, W = 30;\n    // 0 = free, 1 = wall\n    vector<vector<int>> wall(H + 2, vector<int>(W + 2, 0));\n    // borders are treated as walls (impassable)\n    for (int i = 0; i <= H + 1; ++i) {\n        wall[i][0] = wall[i][W + 1] = 1;\n    }\n    for (int j = 0; j <= W + 1; ++j) {\n        wall[0][j] = wall[H + 1][j] = 1;\n    }\n\n    // helper to check inside board\n    auto inside = [&](int x, int y) {\n        return 1 <= x && x <= H && 1 <= y && y <= W;\n    };\n\n    // directions: U,D,L,R with corresponding delta\n    const string dirs = \"UDLR\";\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n\n    // for fast pet lookup on the grid\n    vector<vector<int>> petCnt(H + 2, vector<int>(W + 2, 0));\n    for (auto &p : petPos) petCnt[p.x][p.y]++;\n\n    for (int turn = 0; turn < 300; ++turn) {\n        string actions(M, '.');\n\n        // decide actions for each human\n        for (int i = 0; i < M; ++i) {\n            int hx = humanPos[i].x;\n            int hy = humanPos[i].y;\n            bool placed = false;\n            for (int d = 0; d < 4; ++d) {\n                int nx = hx + dx[d];\n                int ny = hy + dy[d];\n                if (!inside(nx, ny)) continue;\n                if (wall[nx][ny]) continue;            // already wall\n                if (petCnt[nx][ny] > 0) continue;      // pet stands there now\n                // check that none of the four neighbours of (nx,ny) contain a pet\n                bool adjPet = false;\n                for (int k = 0; k < 4; ++k) {\n                    int ax = nx + dx[k];\n                    int ay = ny + dy[k];\n                    if (!inside(ax, ay)) continue;\n                    if (petCnt[ax][ay] > 0) { adjPet = true; break; }\n                }\n                if (adjPet) continue;\n                // also cannot wall a cell that currently holds a human\n                bool otherHuman = false;\n                for (int j = 0; j < M; ++j) {\n                    if (j == i) continue;\n                    if (humanPos[j].x == nx && humanPos[j].y == ny) {\n                        otherHuman = true; break;\n                    }\n                }\n                if (otherHuman) continue;\n\n                // all checks passed \u2192 build wall\n                actions[i] = tolower(dirs[d]); // u/d/l/r\n                wall[nx][ny] = 1;\n                placed = true;\n                break;\n            }\n            // if no safe neighbour, action stays '.'\n            (void)placed;\n        }\n\n        // output actions\n        cout << actions << \"\\n\";\n        cout.flush();\n\n        // read pet movement strings and update positions\n        for (int i = 0; i < N; ++i) {\n            string moveStr;\n            cin >> moveStr;\n            // erase old count\n            petCnt[petPos[i].x][petPos[i].y]--;\n            // apply each step\n            for (char c : moveStr) {\n                if (c == '.') continue;\n                int md = -1;\n                if (c == 'U') md = 0;\n                else if (c == 'D') md = 1;\n                else if (c == 'L') md = 2;\n                else if (c == 'R') md = 3;\n                if (md != -1) {\n                    petPos[i].x += dx[md];\n                    petPos[i].y += dy[md];\n                }\n            }\n            // add new count\n            petCnt[petPos[i].x][petPos[i].y]++;\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Prev {\n    int pi, pj;\n    char mv;                 // move taken from predecessor to this cell\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj, ti, tj;\n    double p;\n    if (!(cin >> si >> sj >> ti >> tj >> p)) return 0;\n\n    const int N = 20;\n    vector<string> h(N);          // 20 strings, length 19\n    for (int i = 0; i < N; ++i) cin >> h[i];\n    vector<string> v(N - 1);      // 19 strings, length 20\n    for (int i = 0; i < N - 1; ++i) cin >> v[i];\n\n    // ---------- BFS ----------\n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    vector<vector<Prev>> pre(N, vector<Prev>(N, {-1, -1, '?'}));\n    queue<pair<int,int>> q;\n    dist[si][sj] = 0;\n    q.emplace(si, sj);\n\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        if (i == ti && j == tj) break;\n\n        // Up\n        if (i > 0 && v[i-1][j] == '0' && dist[i-1][j] == -1) {\n            dist[i-1][j] = dist[i][j] + 1;\n            pre[i-1][j] = {i, j, 'U'};\n            q.emplace(i-1, j);\n        }\n        // Down\n        if (i + 1 < N && v[i][j] == '0' && dist[i+1][j] == -1) {\n            dist[i+1][j] = dist[i][j] + 1;\n            pre[i+1][j] = {i, j, 'D'};\n            q.emplace(i+1, j);\n        }\n        // Left\n        if (j > 0 && h[i][j-1] == '0' && dist[i][j-1] == -1) {\n            dist[i][j-1] = dist[i][j] + 1;\n            pre[i][j-1] = {i, j, 'L'};\n            q.emplace(i, j-1);\n        }\n        // Right\n        if (j + 1 < N && h[i][j] == '0' && dist[i][j+1] == -1) {\n            dist[i][j+1] = dist[i][j] + 1;\n            pre[i][j+1] = {i, j, 'R'};\n            q.emplace(i, j+1);\n        }\n    }\n\n    // ---------- reconstruct shortest path ----------\n    string path;\n    int ci = ti, cj = tj;\n    while (!(ci == si && cj == sj)) {\n        Prev pr = pre[ci][cj];\n        path.push_back(pr.mv);\n        ci = pr.pi;\n        cj = pr.pj;\n    }\n    reverse(path.begin(), path.end());\n\n    if (path.empty()) {               // should never happen (start != target)\n        cout << \"U\\n\";\n        return 0;\n    }\n\n    // ---------- repeat to increase robustness ----------\n    const int MAXLEN = 200;\n    int repeat = MAXLEN / static_cast<int>(path.size());\n    string answer;\n    answer.reserve(repeat * path.size());\n\n    for (int i = 0; i < repeat; ++i) answer += path;\n\n    // optional: fill the remaining characters (not required)\n    int remaining = MAXLEN - static_cast<int>(answer.size());\n    if (remaining > 0) answer.append(path.substr(0, remaining));\n\n    cout << answer << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nconst int DIR = 4;\nconst int di[DIR] = {0, -1, 0, 1};\nconst int dj[DIR] = {-1, 0, 1, 0};\n\nint to0[8][DIR] = {\n    { 1, 0, -1, -1},\n    { 3,-1, -1,  0},\n    {-1,-1,  3,  2},\n    {-1, 2,  1, -1},\n    { 1, 0,  3,  2},\n    { 3, 2,  1,  0},\n    { 2,-1,  0, -1},\n    {-1, 3, -1,  1},\n};\n\nint to_rot[8][4][DIR];               // [type][rot][enter] -> leave or -1\n\nvoid build_rot() {\n    for (int t = 0; t < 8; ++t)\n        for (int r = 0; r < 4; ++r)\n            for (int d = 0; d < DIR; ++d) {\n                int d0 = (d - r + 4) % 4;\n                int nd = to0[t][d0];\n                to_rot[t][r][d] = (nd == -1) ? -1 : (nd + r) % 4;\n            }\n}\n\n/* --------------------------------------------------------------- */\n/*  Score = L1 * L2 (0 if < 2 loops)                               */\n/*  No dynamic allocation \u2013 uses static buffers for speed.          */\n/* --------------------------------------------------------------- */\nint board_score(const vector<string>& tile,\n                const int rot[N][N]) {\n    static bool seen[N][N][DIR];\n    memset(seen, 0, sizeof(seen));\n\n    static int loops[4000];\n    int loop_cnt = 0;\n\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            for (int d = 0; d < DIR; ++d) {\n                if (seen[i][j][d]) continue;\n                int t = tile[i][j] - '0';\n                int r = rot[i][j];\n                if (to_rot[t][r][d] == -1) continue;\n\n                int ci = i, cj = j, cd = d;\n                int len = 0;\n                bool broken = false;\n                while (true) {\n                    int ct = tile[ci][cj] - '0';\n                    int cr = rot[ci][cj];\n                    int nd = to_rot[ct][cr][cd];\n                    if (nd == -1) { broken = true; break; }\n                    int ni = ci + di[nd];\n                    int nj = cj + dj[nd];\n                    if (ni < 0 || ni >= N || nj < 0 || nj >= N) { broken = true; break; }\n                    int nd_next = (nd + 2) % 4;\n                    seen[ci][cj][cd] = true;\n                    ++len;\n                    ci = ni; cj = nj; cd = nd_next;\n                    if (ci == i && cj == j && cd == d) break;   // closed loop\n                }\n                if (!broken && len > 0) loops[loop_cnt++] = len;\n            }\n\n    if (loop_cnt < 2) return 0;\n    // find two largest lengths (simple linear scan, loop_cnt is tiny)\n    int max1 = 0, max2 = 0;\n    for (int k = 0; k < loop_cnt; ++k) {\n        int v = loops[k];\n        if (v > max1) { max2 = max1; max1 = v; }\n        else if (v > max2) max2 = v;\n    }\n    return max1 * max2;\n}\n\n/* --------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    build_rot();\n\n    vector<string> tile(N);\n    for (int i = 0; i < N; ++i) cin >> tile[i];\n\n    std::mt19937 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> rot_dist(0, 3);\n    uniform_int_distribution<int> cell_dist(0, N - 1);\n    uniform_real_distribution<double> prob01(0.0, 1.0);\n\n    static int cur[N][N];\n    static int best[N][N];\n    int bestScore = 0;\n\n    // ---- one random start -------------------------------------------------\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cur[i][j] = rot_dist(rng);\n\n    int curScore = board_score(tile, cur);\n    if (curScore > bestScore) {\n        bestScore = curScore;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                best[i][j] = cur[i][j];\n    }\n\n    // ---- simulated annealing ---------------------------------------------\n    const int MAX_ITER = 30000;                // fits comfortably in 2\u202fs\n    const double T0 = 4000.0, T1 = 0.2;          // exponential cooling\n\n    for (int it = 0; it < MAX_ITER; ++it) {\n        double progress = (double)it / MAX_ITER;\n        double temp = T0 * pow(T1 / T0, progress);   // decreasing temperature\n\n        int i = cell_dist(rng);\n        int j = cell_dist(rng);\n        int oldR = cur[i][j];\n        int newR = rot_dist(rng);\n        if (newR == oldR) continue;\n        cur[i][j] = newR;\n\n        int newScore = board_score(tile, cur);\n        bool accept = false;\n        if (newScore >= curScore) accept = true;\n        else {\n            double p = exp((newScore - curScore) / temp);\n            if (prob01(rng) < p) accept = true;\n        }\n\n        if (accept) {\n            curScore = newScore;\n            if (curScore > bestScore) {\n                bestScore = curScore;\n                for (int x = 0; x < N; ++x)\n                    for (int y = 0; y < N; ++y)\n                        best[x][y] = cur[x][y];\n            }\n        } else {\n            cur[i][j] = oldR;            // revert\n        }\n    }\n\n    // ---- output the best board found --------------------------------------\n    string out;\n    out.reserve(N * N);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            out.push_back(char('0' + best[i][j]));\n    cout << out << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* --------------------------------------------------------------- */\n/* hex character \u2192 integer mask (0 \u2026 15)                             */\nstatic inline int hex2int(char c) {\n    if ('0' <= c && c <= '9') return c - '0';\n    return c - 'a' + 10;\n}\n\n/* --------------------------------------------------------------- */\n/* size of the largest tree in the current board                    */\nint largestTree(const vector<string>& board, int N) {\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n\n    vector<vector<int>> id(N, vector<int>(N, -1));\n    int V = 0;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (board[i][j] != '0')\n                id[i][j] = V++;\n\n    vector<vector<int>> adj(V);\n    auto addEdge = [&](int a, int b) {\n        adj[a].push_back(b);\n        adj[b].push_back(a);\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            int m = hex2int(board[i][j]);\n\n            // down\n            if ((m & 8) && i + 1 < N && board[i + 1][j] != '0') {\n                int m2 = hex2int(board[i + 1][j]);\n                if (m2 & 2) addEdge(id[i][j], id[i + 1][j]);\n            }\n            // right\n            if ((m & 4) && j + 1 < N && board[i][j + 1] != '0') {\n                int m2 = hex2int(board[i][j + 1]);\n                if (m2 & 1) addEdge(id[i][j], id[i][j + 1]);\n            }\n        }\n    }\n\n    vector<char> seen(V, 0);\n    int best = 0;\n    for (int v = 0; v < V; ++v) if (!seen[v]) {\n        int verts = 0, edges2 = 0;\n        stack<int> st;\n        st.push(v);\n        seen[v] = 1;\n        while (!st.empty()) {\n            int cur = st.top(); st.pop();\n            ++verts;\n            edges2 += (int)adj[cur].size();\n            for (int nb : adj[cur])\n                if (!seen[nb]) {\n                    seen[nb] = 1;\n                    st.push(nb);\n                }\n        }\n        int edges = edges2 / 2;\n        if (edges == verts - 1)               // tree\n            best = max(best, verts);\n    }\n    return best;\n}\n\n/* --------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N; long long T;\n    if (!(cin >> N >> T)) return 0;\n    vector<string> original(N);\n    for (int i = 0; i < N; ++i) cin >> original[i];\n\n    /* locate the original empty cell */\n    int origEx = -1, origEy = -1;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (original[i][j] == '0') { origEx = i; origEy = j; }\n\n    const char dirChar[4] = {'U', 'D', 'L', 'R'};\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    int bestScore = -1;\n    string bestAns;\n\n    const double TIME_LIMIT = 2.8;                 // seconds\n    auto start = chrono::steady_clock::now();\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        /* start a fresh greedy walk */\n        vector<string> board = original;\n        int ex = origEx, ey = origEy;\n        string curAns;\n        curAns.reserve(T);\n\n        for (long long step = 0; step < T; ++step) {\n            // collect all legal directions\n            vector<int> legal;\n            for (int d = 0; d < 4; ++d) {\n                int nx = ex + dx[d];\n                int ny = ey + dy[d];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N)\n                    legal.push_back(d);\n            }\n\n            // evaluate every legal move\n            int bestStepScore = -1;\n            vector<int> bestDirs;\n            for (int d : legal) {\n                int nx = ex + dx[d];\n                int ny = ey + dy[d];\n                swap(board[ex][ey], board[nx][ny]);          // temporary\n                int curScore = largestTree(board, N);\n                swap(board[ex][ey], board[nx][ny]);          // revert\n\n                if (curScore > bestStepScore) {\n                    bestStepScore = curScore;\n                    bestDirs.clear();\n                    bestDirs.push_back(d);\n                } else if (curScore == bestStepScore) {\n                    bestDirs.push_back(d);\n                }\n            }\n\n            // choose randomly among the best directions\n            int d = bestDirs[uniform_int_distribution<int>(0,\n                        (int)bestDirs.size() - 1)(rng)];\n            int nx = ex + dx[d];\n            int ny = ey + dy[d];\n            swap(board[ex][ey], board[nx][ny]);              // make it permanent\n            ex = nx; ey = ny;\n            curAns.push_back(dirChar[d]);\n        }\n\n        int curScore = largestTree(board, N);\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestAns   = curAns;\n        }\n    }\n\n    cout << bestAns << '\\n';\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing int64 = long long;\n\n/*---------------------------------------------------------------*/\n/*  Reduce (dx,dy) to a canonical primitive vector.\n    The first non\u2011zero component is forced positive.               */\nstatic pair<int64,int64> norm_dir(int64 dx, int64 dy){\n    int64 g = std::gcd(std::abs(dx), std::abs(dy));\n    dx /= g; dy /= g;\n    if (dx < 0 || (dx == 0 && dy < 0)){\n        dx = -dx; dy = -dy;\n    }\n    return {dx, dy};\n}\n\n/*---------------------------------------------------------------*/\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    long long N;                     // total strawberries (not used)\n    int K;                           // K = 100 in every test\n    if(!(cin >> N >> K)) return 0;\n    for(int i=0;i<10;i++){ long long a; cin >> a; }\n    for(long long i=0;i<N;i++){ long long x,y; cin >> x >> y; }\n\n    const int MAX_CUTS = 100;\n    const int64 LIM   = 1'000'000'000LL;   // allowed coordinate range\n    const int64 R    = 10'000LL;           // cake radius\n    const int64 R2   = R * R;\n    const int64 SCALE = 20'000LL;          // length multiplier for Q\n    \n    /*---------- 1) enumerate primitive direction vectors ----------*/\n    const int BOUND = 1500;                // |dx|,|dy| \u2264 BOUND\n    vector<pair<int64,int64>> cand;\n    cand.reserve( (2*BOUND+1)*(2*BOUND+1) );\n    for(int dx=-BOUND; dx<=BOUND; ++dx){\n        for(int dy=-BOUND; dy<=BOUND; ++dy){\n            if(dx==0 && dy==0) continue;\n            if(std::gcd(std::abs(dx), std::abs(dy)) != 1) continue; // primitive only\n            cand.emplace_back(dx, dy);\n        }\n    }\n    // sort by angle\n    vector<double> ang(cand.size());\n    for(size_t i=0;i<cand.size();++i){\n        ang[i] = atan2((double)cand[i].second, (double)cand[i].first);\n    }\n    vector<size_t> idx(cand.size());\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(),\n         [&](size_t a, size_t b){ return ang[a] < ang[b]; });\n    \n    /*---------- 2) pick 100 uniformly spaced directions -----------*/\n    vector<pair<int64,int64>> dirs;\n    dirs.reserve(MAX_CUTS);\n    size_t total = idx.size();\n    size_t step = total / MAX_CUTS;\n    if(step==0) step = 1;\n    for(size_t i=0;i<MAX_CUTS;i++){\n        size_t pos = i * step;\n        if(pos >= total) pos = total-1;\n        dirs.push_back(cand[idx[pos]]);\n    }\n    \n    /*---------- 3) generate the 100 lines ------------------------*/\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int64> dist_inside(-R, R);   // interior point\n    \n    vector<array<int64,4>> lines;\n    lines.reserve(MAX_CUTS);\n    for(const auto& d : dirs){\n        int64 dx = d.first;\n        int64 dy = d.second;\n        // interior point (strictly inside the circle)\n        int64 px, py;\n        do{\n            px = dist_inside(rng);\n            py = dist_inside(rng);\n        }while(px*px + py*py >= R2);\n        // second point far away along the direction\n        int64 qx = px + dx * SCALE;\n        int64 qy = py + dy * SCALE;\n        // clamp to allowed range\n        qx = max(min(qx, LIM), -LIM);\n        qy = max(min(qy, LIM), -LIM);\n        lines.push_back({px, py, qx, qy});\n    }\n    \n    /*---------- 4) output ---------------------------------------*/\n    cout << lines.size() << '\\n';\n    for(const auto &ln : lines){\n        cout << ln[0] << ' ' << ln[1] << ' '\n             << ln[2] << ' ' << ln[3] << '\\n';\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int x1, y1, x2, y2, x3, y3, x4, y4;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n\n    /* ---------- dots ---------- */\n    vector<vector<char>> has(N, vector<char>(N, 0));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        has[x][y] = 1;\n    }\n\n    /* ---------- used unit edges ---------- */\n    vector<vector<char>> hori(N - 1, vector<char>(N, 0));   // (x,y)-(x+1,y)\n    vector<vector<char>> vert(N, vector<char>(N - 1, 0));   // (x,y)-(x,y+1)\n\n    vector<Op> ops;\n\n    auto add_unit_square = [&](int x, int y, int miss) -> bool {\n        const int cx[4] = {x, x + 1, x + 1, x};\n        const int cy[4] = {y, y,     y + 1, y + 1};\n\n        // three corners already present, one missing (miss)\n        // check that all four unit edges are free\n        for (int xx = cx[0]; xx < cx[1]; ++xx)\n            if (hori[xx][cy[0]]) return false;\n        for (int yy = cy[1]; yy < cy[2]; ++yy)\n            if (vert[cx[1]][yy]) return false;\n        for (int xx = cx[2]; xx > cx[3]; --xx)\n            if (hori[xx - 1][cy[2]]) return false;\n        for (int yy = cy[3]; yy > cy[0]; --yy)\n            if (vert[cx[3]][yy - 1]) return false;\n\n        // place the missing dot\n        int mx = cx[miss], my = cy[miss];\n        has[mx][my] = 1;\n\n        // mark edges as used\n        for (int xx = cx[0]; xx < cx[1]; ++xx) hori[xx][cy[0]] = 1;\n        for (int yy = cy[1]; yy < cy[2]; ++yy) vert[cx[1]][yy] = 1;\n        for (int xx = cx[2]; xx > cx[3]; --xx) hori[xx - 1][cy[2]] = 1;\n        for (int yy = cy[3]; yy > cy[0]; --yy) vert[cx[3]][yy - 1] = 1;\n\n        // output operation (missing corner first, then clockwise)\n        Op op;\n        op.x1 = mx; op.y1 = my;\n        int idx = 0;\n        for (int k = 1; k <= 3; ++k) {\n            int cur = (miss + k) % 4;\n            if (idx == 0) { op.x2 = cx[cur]; op.y2 = cy[cur]; }\n            else if (idx == 1) { op.x3 = cx[cur]; op.y3 = cy[cur]; }\n            else { op.x4 = cx[cur]; op.y4 = cy[cur]; }\n            ++idx;\n        }\n        ops.push_back(op);\n        return true;\n    };\n\n    auto try_large_rectangle = [&](int x, int y) -> bool {\n        // list of x2 sorted by distance from x (largest first)\n        vector<int> xs(N);\n        iota(xs.begin(), xs.end(), 0);\n        sort(xs.begin(), xs.end(),\n             [&](int a, int b){ return abs(a - x) > abs(b - x); });\n\n        vector<int> ys(N);\n        iota(ys.begin(), ys.end(), 0);\n        sort(ys.begin(), ys.end(),\n             [&](int a, int b){ return abs(a - y) > abs(b - y); });\n\n        for (int x2 : xs) if (x2 != x) {\n            for (int y2 : ys) if (y2 != y) {\n                // three existing corners must be present\n                if (!has[x2][y] || !has[x][y2] || !has[x2][y2]) continue;\n\n                int lx = min(x, x2), rx = max(x, x2);\n                int ly = min(y, y2), ry = max(y, y2);\n\n                // ---- condition 3 : edges must be free ----\n                bool ok = true;\n                for (int xx = lx; ok && xx < rx; ++xx)\n                    if (hori[xx][ly]) ok = false;\n                for (int yy = ly; ok && yy < ry; ++yy)\n                    if (vert[rx][yy]) ok = false;\n                for (int xx = lx; ok && xx < rx; ++xx)\n                    if (hori[xx][ry]) ok = false;\n                for (int yy = ly; ok && yy < ry; ++yy)\n                    if (vert[lx][yy]) ok = false;\n                if (!ok) continue;\n\n                // ---- condition 2 : no extra dots on the sides ----\n                for (int xx = lx + 1; ok && xx < rx; ++xx) {\n                    if (has[xx][ly]) ok = false;\n                    if (has[xx][ry]) ok = false;\n                }\n                for (int yy = ly + 1; ok && yy < ry; ++yy) {\n                    if (has[lx][yy]) ok = false;\n                    if (has[rx][yy]) ok = false;\n                }\n                if (!ok) continue;\n\n                // ----- accept -----\n                has[x][y] = 1;               // new dot\n\n                // mark edges\n                for (int xx = lx; xx < rx; ++xx) hori[xx][ly] = 1;\n                for (int yy = ly; yy < ry; ++yy) vert[rx][yy] = 1;\n                for (int xx = lx; xx < rx; ++xx) hori[xx][ry] = 1;\n                for (int yy = ly; yy < ry; ++yy) vert[lx][yy] = 1;\n\n                // output clockwise order, starting from (x,y)\n                Op op;\n                op.x1 = x;  op.y1 = y;\n                if (x == lx && y == ly) {               // lower\u2011left missing\n                    op.x2 = rx; op.y2 = ly;\n                    op.x3 = rx; op.y3 = ry;\n                    op.x4 = lx; op.y4 = ry;\n                } else if (x == rx && y == ly) {        // lower\u2011right missing\n                    op.x2 = rx; op.y2 = ry;\n                    op.x3 = lx; op.y3 = ry;\n                    op.x4 = lx; op.y4 = ly;\n                } else if (x == rx && y == ry) {        // upper\u2011right missing\n                    op.x2 = lx; op.y2 = ry;\n                    op.x3 = lx; op.y3 = ly;\n                    op.x4 = rx; op.y4 = ly;\n                } else {                                // upper\u2011left missing\n                    op.x2 = lx; op.y2 = ly;\n                    op.x3 = rx; op.y3 = ly;\n                    op.x4 = rx; op.y4 = ry;\n                }\n                ops.push_back(op);\n                return true;          // one rectangle added for this cell\n            }\n        }\n        return false;\n    };\n\n    bool any_change = true;\n    while (any_change) {\n        any_change = false;\n\n        /* ---- step 1 : try large rectangles ---- */\n        // collect all empty cells and sort them by distance from centre (farther first)\n        vector<pair<int,int>> empties;\n        for (int x = 0; x < N; ++x)\n            for (int y = 0; y < N; ++y)\n                if (!has[x][y]) empties.emplace_back(x, y);\n\n        const int c = (N - 1) / 2;\n        sort(empties.begin(), empties.end(),\n             [&](auto a, auto b) {\n                 long da = 1LL * (a.first - c) * (a.first - c) +\n                           1LL * (a.second - c) * (a.second - c);\n                 long db = 1LL * (b.first - c) * (b.first - c) +\n                           1LL * (b.second - c) * (b.second - c);\n                 return da > db;               // farthest first\n             });\n\n        for (auto [x, y] : empties) {\n            if (has[x][y]) continue;            // might have been filled earlier\n            if (try_large_rectangle(x, y)) {\n                any_change = true;\n                // after adding one rectangle we can continue with the next empty cell\n                // (the newly added dot will be considered in the next outer iteration)\n            }\n        }\n\n        /* ---- step 2 : fill unit squares (parity trick) ---- */\n        bool changed = true;\n        while (changed) {\n            changed = false;\n            for (int x = 0; x + 1 < N; ++x) {\n                for (int y = 0; y + 1 < N; ++y) {\n                    if ((x + y) & 1) continue;          // only one colour\n                    const int cx[4] = {x, x + 1, x + 1, x};\n                    const int cy[4] = {y, y,     y + 1, y + 1};\n\n                    int cnt = 0, miss = -1;\n                    for (int k = 0; k < 4; ++k) {\n                        if (has[cx[k]][cy[k]]) ++cnt;\n                        else miss = k;\n                    }\n                    if (cnt != 3) continue;\n                    if (add_unit_square(x, y, miss)) changed = true;\n                }\n            }\n        }\n    }\n\n    /* ---------- output ---------- */\n    cout << ops.size() << '\\n';\n    for (const auto &op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' '\n             << op.x2 << ' ' << op.y2 << ' '\n             << op.x3 << ' ' << op.y3 << ' '\n             << op.x4 << ' ' << op.y4 << '\\n';\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 10;\nusing Board = array<array<int, N>, N>;\n\nstruct Pos { int r, c; };\n\n/* slide all candies toward dir:\n   0 = forward (up), 1 = backward (down), 2 = left, 3 = right */\nBoard tilt(const Board &src, int dir) {\n    Board dst = src;\n    if (dir == 0) {                     // up\n        for (int c = 0; c < N; ++c) {\n            int w = 0;\n            for (int r = 0; r < N; ++r) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[w][c] = v;\n                ++w;\n            }\n        }\n    } else if (dir == 1) {              // down\n        for (int c = 0; c < N; ++c) {\n            int w = N - 1;\n            for (int r = N - 1; r >= 0; --r) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[w][c] = v;\n                --w;\n            }\n        }\n    } else if (dir == 2) {              // left\n        for (int r = 0; r < N; ++r) {\n            int w = 0;\n            for (int c = 0; c < N; ++c) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[r][w] = v;\n                ++w;\n            }\n        }\n    } else {                            // right\n        for (int r = 0; r < N; ++r) {\n            int w = N - 1;\n            for (int c = N - 1; c >= 0; --c) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[r][w] = v;\n                --w;\n            }\n        }\n    }\n    return dst;\n}\n\n/* place flavour into the p\u2011th empty cell (p is 1\u2011based) */\nvoid place(Board &b, int p, int flavour) {\n    int cnt = 0;\n    for (int r = 0; r < N; ++r)\n        for (int c = 0; c < N; ++c)\n            if (b[r][c] == 0) {\n                ++cnt;\n                if (cnt == p) {\n                    b[r][c] = flavour;\n                    return;\n                }\n            }\n}\n\n/* BFS -> component id and size vector */\nvoid bfs_components(const Board &b,\n                    array<array<int, N>, N> &compId,\n                    vector<int> &compSize) {\n    compId.fill({});\n    for (auto &row : compId) row.fill(-1);\n    compSize.clear();\n\n    static const int dr[4] = {-1, 1, 0, 0};\n    static const int dc[4] = {0, 0, -1, 1};\n\n    int curId = 0;\n    for (int r = 0; r < N; ++r) for (int c = 0; c < N; ++c) {\n        if (b[r][c] == 0 || compId[r][c] != -1) continue;\n        int col = b[r][c];\n        queue<Pos> q;\n        q.push({r, c});\n        compId[r][c] = curId;\n        int sz = 0;\n        while (!q.empty()) {\n            Pos cur = q.front(); q.pop();\n            ++sz;\n            for (int d = 0; d < 4; ++d) {\n                int nr = cur.r + dr[d];\n                int nc = cur.c + dc[d];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                if (b[nr][nc] == col && compId[nr][nc] == -1) {\n                    compId[nr][nc] = curId;\n                    q.push({nr, nc});\n                }\n            }\n        }\n        compSize.push_back(sz);\n        ++curId;\n    }\n}\n\n/* sum of size^2 of all components */\nlong long totalComponentScore(const vector<int> &compSize) {\n    long long sum = 0;\n    for (int s : compSize) sum += 1LL * s * s;\n    return sum;\n}\n\n/* expected total component score after the next random placement */\ndouble expectedScoreAfterNext(const Board &b,\n                             const array<array<int, N>, N> &compId,\n                             const vector<int> &compSize,\n                             int nextFlavour) {\n    long long curScore = totalComponentScore(compSize);\n    int emptyCnt = 0;\n    long long totalDelta = 0;\n\n    static const int dr[4] = {-1, 1, 0, 0};\n    static const int dc[4] = {0, 0, -1, 1};\n\n    for (int r = 0; r < N; ++r) for (int c = 0; c < N; ++c) {\n        if (b[r][c] != 0) continue;\n        ++emptyCnt;\n        // collect distinct neighbour component ids of flavour nextFlavour\n        int ids[4];\n        int idCnt = 0;\n        for (int d = 0; d < 4; ++d) {\n            int nr = r + dr[d];\n            int nc = c + dc[d];\n            if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n            if (b[nr][nc] != nextFlavour) continue;\n            int id = compId[nr][nc];\n            bool found = false;\n            for (int i = 0; i < idCnt; ++i) if (ids[i] == id) { found = true; break; }\n            if (!found) ids[idCnt++] = id;\n        }\n        long long oldSum = 0, newSum = 0;\n        for (int i = 0; i < idCnt; ++i) {\n            long long sz = compSize[ids[i]];\n            oldSum += sz * sz;\n            newSum += sz;\n        }\n        long long newSize = 1 + newSum;\n        long long delta = newSize * newSize - oldSum;\n        totalDelta += delta;\n    }\n\n    if (emptyCnt == 0) return curScore;          // should not happen before final step\n    return curScore + static_cast<double>(totalDelta) / emptyCnt;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    vector<int> flavour(100);\n    for (int i = 0; i < 100; ++i) cin >> flavour[i];\n\n    Board board{};\n    const char dirChar[4] = {'F', 'B', 'L', 'R'};\n\n    for (int step = 0; step < 100; ++step) {\n        int p;                     // position of the newly placed candy\n        cin >> p;\n        place(board, p, flavour[step]);\n\n        double bestExp = -1e300;\n        int bestDir = 0;\n\n        for (int d = 0; d < 4; ++d) {\n            Board nb = tilt(board, d);\n\n            // component data for nb\n            array<array<int, N>, N> compId;\n            vector<int> compSize;\n            bfs_components(nb, compId, compSize);\n            long long curScore = totalComponentScore(compSize);\n\n            double expScore;\n            if (step < 99) {\n                expScore = expectedScoreAfterNext(nb, compId, compSize,\n                                                 flavour[step + 1]);\n            } else {\n                expScore = curScore;            // last step, no future placement\n            }\n\n            if (expScore > bestExp) {\n                bestExp = expScore;\n                bestDir = d;\n            }\n        }\n\n        cout << dirChar[bestDir] << '\\n';\n        cout.flush();\n\n        board = tilt(board, bestDir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n\n    const int N = 20;                         // fixed vertex count\n    const int L = N * (N - 1) / 2;            // length of each graph string\n\n    cout << N << \"\\n\";\n    for (int k = 0; k < M; ++k) {\n        string s(k, '1');                     // k ones\n        s.append(L - k, '0');                 // remaining zeros\n        cout << s << \"\\n\";\n    }\n    cout.flush();\n\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;                             // length L\n        int cnt = 0;\n        for (char c : H) if (c == '1') ++cnt;\n\n        int t = min(cnt, M - 1);               // nearest index (0 \u2026 M\u20111)\n        cout << t << \"\\n\";\n        cout.flush();\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct AdjEdge {\n    int to;\n    int w;\n    int idx;          // original edge index\n};\n\nstruct DayInfo {\n    double sum;       // total importance already assigned\n    int id;           // 1\u2011based day number\n    bool operator<(DayInfo const& o) const {\n        // reverse for min\u2011heap\n        if (sum != o.sum) return sum > o.sum;\n        return id > o.id;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n\n    vector<int> U(M), V(M), W(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> U[i] >> V[i] >> W[i];\n        --U[i]; --V[i];\n    }\n\n    // coordinates are irrelevant for the schedule\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    /* ---------- adjacency list ---------- */\n    vector<vector<AdjEdge>> g(N);\n    for (int i = 0; i < M; ++i) {\n        g[U[i]].push_back({V[i], W[i], i});\n        g[V[i]].push_back({U[i], W[i], i});\n    }\n\n    /* ---------- compute exact edge importance ----------\n       importance[e] = total number of all\u2011pairs shortest\u2011paths that use e   */\n    vector<double> importance(M, 0.0);\n    const long long INF = (1LL << 60);\n\n    // containers reused for each source\n    vector<long long> dist(N);\n    vector<double> cnt(N);\n    using PQNode = pair<long long,int>;\n\n    for (int s = 0; s < N; ++s) {\n        // Dijkstra from s\n        fill(dist.begin(), dist.end(), INF);\n        fill(cnt.begin(), cnt.end(), 0.0);\n        dist[s] = 0;\n        cnt[s] = 1.0;\n        priority_queue<PQNode, vector<PQNode>, greater<PQNode>> pq;\n        pq.emplace(0LL, s);\n\n        while (!pq.empty()) {\n            auto [d, v] = pq.top(); pq.pop();\n            if (d != dist[v]) continue;\n            for (const auto &e : g[v]) {\n                long long nd = d + e.w;\n                if (nd < dist[e.to]) {\n                    dist[e.to] = nd;\n                    cnt[e.to] = cnt[v];\n                    pq.emplace(nd, e.to);\n                } else if (nd == dist[e.to]) {\n                    cnt[e.to] += cnt[v];\n                }\n            }\n        }\n\n        // add contributions to edges\n        for (int i = 0; i < M; ++i) {\n            int a = U[i], b = V[i], w = W[i];\n            if (dist[a] + w == dist[b]) importance[i] += cnt[a];\n            if (dist[b] + w == dist[a]) importance[i] += cnt[b];\n        }\n    }\n\n    /* ---------- sort edges by decreasing importance ---------- */\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int x, int y) {\n             if (importance[x] != importance[y])\n                 return importance[x] > importance[y];\n             return W[x] > W[y];          // tie\u2011breaker\n         });\n\n    /* ---------- greedy balanced assignment ---------- */\n    vector<int> cntDay(D + 1, 0);\n    vector<double> sumDay(D + 1, 0.0);\n    priority_queue<DayInfo> heap;\n    for (int d = 1; d <= D; ++d) heap.push({0.0, d});\n\n    vector<int> answer(M, 1);\n    for (int idx : order) {\n        DayInfo cur = heap.top(); heap.pop();   // day with smallest sum\n        int d = cur.id;\n        answer[idx] = d;\n\n        ++cntDay[d];\n        sumDay[d] += importance[idx];\n        cur.sum = sumDay[d];\n        if (cntDay[d] < K) heap.push(cur);     // keep day while capacity remains\n    }\n\n    /* ---------- output ---------- */\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << answer[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos { int x, y, z; };\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int D;\n    if (!(cin >> D)) return 0;\n\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) cin >> f[i][z];\n        for (int z = 0; z < D; ++z) cin >> r[i][z];\n    }\n\n    const long long SZ = 1LL * D * D * D;\n    auto idx = [&](int x, int y, int z) -> long long {\n        return 1LL * x * D * D + 1LL * y * D + z;\n    };\n\n    /* -------------------------------------------------------------\n       masks: in1, in2, U, A, B\n       ------------------------------------------------------------- */\n    vector<char> in1(SZ, 0), in2(SZ, 0);\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 a = (f[0][z][x] == '1' && r[0][z][y] == '1');\n                bool b = (f[1][z][x] == '1' && r[1][z][y] == '1');\n                long long p = idx(x, y, z);\n                if (a) in1[p] = 1;\n                if (b) in2[p] = 1;\n            }\n\n    vector<char> maskU(SZ, 0), maskA(SZ, 0), maskB(SZ, 0);\n    for (long long p = 0; p < SZ; ++p) {\n        maskU[p] = (in1[p] && in2[p]);\n        maskA[p] = (in1[p] && !in2[p]);\n        maskB[p] = (in2[p] && !in1[p]);\n    }\n\n    const int dx[6] = {1,-1,0,0,0,0};\n    const int dy[6] = {0,0,1,-1,0,0};\n    const int dz[6] = {0,0,0,0,1,-1};\n\n    /* -------------------------------------------------------------\n       BFS that returns all components of a mask\n       ------------------------------------------------------------- */\n    auto bfs_components = [&](const vector<char>& mask) {\n        vector<char> visited(SZ, 0);\n        vector<vector<Pos>> comps;\n        queue<Pos> q;\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                    long long p = idx(x, y, z);\n                    if (!mask[p] || visited[p]) continue;\n                    comps.emplace_back();\n                    q = {};\n                    q.push({x, y, z});\n                    visited[p] = 1;\n                    while (!q.empty()) {\n                        Pos cur = q.front(); q.pop();\n                        comps.back().push_back(cur);\n                        for (int d = 0; d < 6; ++d) {\n                            int nx = cur.x + dx[d];\n                            int ny = cur.y + dy[d];\n                            int nz = cur.z + dz[d];\n                            if (nx < 0 || nx >= D || ny < 0 || ny >= D ||\n                                nz < 0 || nz >= D) continue;\n                            long long np = idx(nx, ny, nz);\n                            if (!mask[np] || visited[np]) continue;\n                            visited[np] = 1;\n                            q.push({nx, ny, nz});\n                        }\n                    }\n                }\n        return comps;\n    };\n\n    vector<vector<Pos>> compsU = bfs_components(maskU);\n    vector<vector<Pos>> compsA = bfs_components(maskA);\n    vector<vector<Pos>> compsB = bfs_components(maskB);\n\n    /* -------------------------------------------------------------\n       24 rotation matrices (determinant +1)\n       ------------------------------------------------------------- */\n    vector<array<array<int,3>,3>> rots;\n    vector<array<int,3>> perms = {{0,1,2},{0,2,1},{1,0,2},{1,2,0},{2,0,1},{2,1,0}};\n    for (auto p : perms) {\n        for (int sx : {1,-1})\n        for (int sy : {1,-1})\n        for (int sz : {1,-1}) {\n            if (sx*sy*sz != 1) continue;          // keep orientation\n            array<array<int,3>,3> m{};\n            m[0] = {0,0,0};\n            m[1] = {0,0,0};\n            m[2] = {0,0,0};\n            m[0][p[0]] = sx;\n            m[1][p[1]] = sy;\n            m[2][p[2]] = sz;\n            rots.push_back(m);\n        }\n    }\n    assert(rots.size() == 24);\n\n    /* -------------------------------------------------------------\n       canonical representation of a component (shape only)\n       ------------------------------------------------------------- */\n    auto canonical = [&](const vector<Pos>& cells) -> string {\n        string best;\n        bool first = true;\n        vector<Pos> tmp(cells.size());\n\n        for (const auto& R : rots) {\n            // rotate\n            for (size_t i = 0; i < cells.size(); ++i) {\n                const Pos& p = cells[i];\n                int nx = R[0][0]*p.x + R[0][1]*p.y + R[0][2]*p.z;\n                int ny = R[1][0]*p.x + R[1][1]*p.y + R[1][2]*p.z;\n                int nz = R[2][0]*p.x + R[2][1]*p.y + R[2][2]*p.z;\n                tmp[i] = {nx, ny, nz};\n            }\n            // translate to origin\n            int minx = INT_MAX, miny = INT_MAX, minz = INT_MAX;\n            for (auto &p : tmp) {\n                minx = min(minx, p.x);\n                miny = min(miny, p.y);\n                minz = min(minz, p.z);\n            }\n            for (auto &p : tmp) {\n                p.x -= minx; p.y -= miny; p.z -= minz;\n            }\n            sort(tmp.begin(), tmp.end(),\n                 [](const Pos& a, const Pos& b){\n                     if (a.x != b.x) return a.x < b.x;\n                     if (a.y != b.y) return a.y < b.y;\n                     return a.z < b.z;\n                 });\n            // serialize\n            string s;\n            s.reserve(tmp.size()*6);\n            for (auto &p : tmp) {\n                s += to_string(p.x); s += ',';\n                s += to_string(p.y); s += ',';\n                s += to_string(p.z); s += ';';\n            }\n            if (first || s < best) {\n                best = std::move(s);\n                first = false;\n            }\n        }\n        return best;\n    };\n\n    /* -------------------------------------------------------------\n       Build maps for A and B components by shape\n       ------------------------------------------------------------- */\n    unordered_map<string, vector<int>> mapA, mapB;\n    vector<string> shapeA(compsA.size()), shapeB(compsB.size());\n\n    for (int i = 0; i < (int)compsA.size(); ++i) {\n        shapeA[i] = canonical(compsA[i]);\n        mapA[shapeA[i]].push_back(i);\n    }\n    for (int i = 0; i < (int)compsB.size(); ++i) {\n        shapeB[i] = canonical(compsB[i]);\n        mapB[shapeB[i]].push_back(i);\n    }\n\n    vector<int> out1(SZ, 0), out2(SZ, 0);\n    long long curId = 0;\n\n    auto write_component = [&](const vector<Pos>& comp, bool to1, bool to2) {\n        ++curId;\n        for (const auto& p : comp) {\n            long long id = idx(p.x, p.y, p.z);\n            if (to1) out1[id] = (int)curId;\n            if (to2) out2[id] = (int)curId;\n        }\n    };\n\n    /* ------------ 4. match components of A and B by shape ------------ */\n    vector<char> usedA(compsA.size(), 0), usedB(compsB.size(), 0);\n    for (auto &kv : mapA) {\n        const string& key = kv.first;\n        auto itB = mapB.find(key);\n        if (itB == mapB.end()) continue;\n        vector<int>& vecA = kv.second;\n        vector<int>& vecB = itB->second;\n        int k = min((int)vecA.size(), (int)vecB.size());\n        for (int t = 0; t < k; ++t) {\n            int aIdx = vecA[t];\n            int bIdx = vecB[t];\n            usedA[aIdx] = usedB[bIdx] = 1;\n            ++curId;\n            for (const auto& p : compsA[aIdx]) out1[idx(p.x,p.y,p.z)] = (int)curId;\n            for (const auto& p : compsB[bIdx]) out2[idx(p.x,p.y,p.z)] = (int)curId;\n        }\n    }\n\n    /* ------------ 5. remaining exclusive components ------------------ */\n    for (int i = 0; i < (int)compsA.size(); ++i)\n        if (!usedA[i]) write_component(compsA[i], true, false);\n    for (int i = 0; i < (int)compsB.size(); ++i)\n        if (!usedB[i]) write_component(compsB[i], false, true);\n\n    /* ------------ 6. shared components U ----------------------------- */\n    for (const auto& comp : compsU) write_component(comp, true, true);\n\n    /* ------------------------ output -------------------------------- */\n    cout << curId << '\\n';\n    for (size_t i = 0; i < out1.size(); ++i) {\n        if (i) cout << ' ';\n        cout << out1[i];\n    }\n    cout << '\\n';\n    for (size_t i = 0; i < out2.size(); ++i) {\n        if (i) cout << ' ';\n        cout << out2[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) { p.resize(n); r.assign(n, 0); iota(p.begin(), p.end(), 0); }\n    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;\n\n    vector<long long> x(N + 1), y(N + 1);\n    for (int i = 1; i <= N; ++i) cin >> x[i] >> y[i];\n\n    struct Edge {int u, v; long long w;};\n    vector<Edge> edges(M + 1);\n    const long long INF = (1LL << 60);\n    vector<vector<long long>> sp(N + 1, vector<long long>(N + 1, INF));\n    vector<vector<int>> nxt(N + 1, vector<int>(N + 1, -1));\n    map<pair<int,int>, int> pairToIdx;\n\n    for (int j = 1; j <= M; ++j) {\n        int u, v; long long w;\n        cin >> u >> v >> w;\n        edges[j] = {u, v, w};\n        if (w < sp[u][v]) {\n            sp[u][v] = sp[v][u] = w;\n            nxt[u][v] = v;\n            nxt[v][u] = u;\n        }\n        pairToIdx[{min(u, v), max(u, v)}] = j;\n    }\n    for (int i = 1; i <= N; ++i) {\n        sp[i][i] = 0;\n        nxt[i][i] = i;\n    }\n\n    // Floyd\u2011Warshall\n    for (int k = 1; k <= N; ++k)\n        for (int i = 1; i <= N; ++i) if (sp[i][k] != INF)\n            for (int j = 1; j <= N; ++j) if (sp[k][j] != INF) {\n                long long nd = sp[i][k] + sp[k][j];\n                if (nd < sp[i][j]) {\n                    sp[i][j] = nd;\n                    nxt[i][j] = nxt[i][k];\n                }\n            }\n\n    // residents\n    struct Resident { long long a, b; };\n    vector<Resident> residents(K);\n    for (int i = 0; i < K; ++i) cin >> residents[i].a >> residents[i].b;\n\n    // distance resident -> vertex\n    vector<vector<double>> dRes(K, vector<double>(N + 1));\n    for (int r = 0; r < K; ++r) {\n        for (int v = 1; v <= N; ++v) {\n            long double dx = (long double)x[v] - (long double)residents[r].a;\n            long double dy = (long double)y[v] - (long double)residents[r].b;\n            dRes[r][v] = sqrt(dx*dx + dy*dy);\n        }\n    }\n\n    // ----------  iterative reduction ----------\n    vector<char> active(N + 1, 1);         // all vertices start as possible\n    active[1] = 1;                        // source must stay active (may have P=0)\n\n    bool changed = true;\n    while (changed) {\n        changed = false;\n        // assignment to nearest active vertex\n        vector<int> assign(K, -1);\n        vector<double> assignDist(K, 1e100);\n        for (int r = 0; r < K; ++r) {\n            double best = 1e100;\n            int bestv = -1;\n            for (int v = 1; v <= N; ++v) if (active[v]) {\n                if (dRes[r][v] < best) {\n                    best = dRes[r][v];\n                    bestv = v;\n                }\n            }\n            assign[r] = bestv;\n            assignDist[r] = best;\n        }\n\n        // compute required powers\n        vector<int> P(N + 1, 0);\n        vector<double> maxDist(N + 1, -1.0);\n        for (int r = 0; r < K; ++r) {\n            int v = assign[r];\n            if (v == -1) continue;\n            if (assignDist[r] > maxDist[v]) maxDist[v] = assignDist[r];\n        }\n        for (int v = 1; v <= N; ++v) if (active[v] && maxDist[v] >= 0) {\n            int pi = (int)ceil(maxDist[v] - 1e-12);\n            if (pi > 5000) pi = 5000;\n            P[v] = pi;\n        }\n\n        // find removable vertices (except source)\n        vector<char> removable(N + 1, 0);\n        for (int v = 1; v <= N; ++v) {\n            if (!active[v] || v == 1) continue;\n            bool canRemove = true;\n            // if no resident assigned -> removable\n            bool hasResident = false;\n            for (int r = 0; r < K; ++r) if (assign[r] == v) {\n                hasResident = true;\n                // is this resident already covered by another active vertex?\n                bool covered = false;\n                for (int u = 1; u <= N; ++u) if (u != v && active[u]) {\n                    if (P[u] > 0 && dRes[r][u] <= P[u] + 1e-9) {\n                        covered = true; break;\n                    }\n                }\n                if (!covered) { canRemove = false; break; }\n            }\n            if (!hasResident) canRemove = true;\n            if (canRemove) removable[v] = 1;\n        }\n\n        // apply removals\n        for (int v = 1; v <= N; ++v) if (removable[v]) {\n            active[v] = 0;\n            changed = true;\n        }\n    }\n\n    // ---------- final assignment & powers ----------\n    // assign again (now active set is final)\n    vector<int> finalAssign(K, -1);\n    for (int r = 0; r < K; ++r) {\n        double best = 1e100;\n        int bestv = -1;\n        for (int v = 1; v <= N; ++v) if (active[v]) {\n            if (dRes[r][v] < best) {\n                best = dRes[r][v];\n                bestv = v;\n            }\n        }\n        finalAssign[r] = bestv;\n    }\n    vector<int> P(N + 1, 0);\n    vector<double> maxDist(N + 1, -1.0);\n    for (int r = 0; r < K; ++r) {\n        int v = finalAssign[r];\n        if (v == -1) continue;\n        if (dRes[r][v] > maxDist[v]) maxDist[v] = dRes[r][v];\n    }\n    for (int v = 1; v <= N; ++v) if (active[v] && maxDist[v] >= 0) {\n        int pi = (int)ceil(maxDist[v] - 1e-12);\n        if (pi > 5000) pi = 5000;\n        P[v] = pi;\n    }\n    // source must be present in the connectivity set even if P[1]==0\n    active[1] = 1;\n\n    // ---------- build metric MST ----------\n    vector<int> actList;\n    for (int v = 1; v <= N; ++v) if (active[v]) actList.push_back(v);\n    struct EdgeM { long long w; int u, v; };\n    vector<EdgeM> metricEdges;\n    int A = actList.size();\n    for (int i = 0; i < A; ++i) {\n        for (int j = i + 1; j < A; ++j) {\n            int u = actList[i], v = actList[j];\n            metricEdges.push_back({sp[u][v], u, v});\n        }\n    }\n    sort(metricEdges.begin(), metricEdges.end(),\n         [](const EdgeM& a, const EdgeM& b){ return a.w < b.w; });\n\n    DSU dsu(N + 1);\n    vector<pair<int,int>> mstPairs;\n    for (auto &e : metricEdges) {\n        if (dsu.unite(e.u, e.v)) {\n            mstPairs.emplace_back(e.u, e.v);\n            if ((int)mstPairs.size() == A - 1) break;\n        }\n    }\n\n    // ---------- mark original edges used ----------\n    vector<char> usedEdge(M + 1, 0);\n    auto addPath = [&](int s, int t){\n        int cur = s;\n        while (cur != t) {\n            int nx = nxt[cur][t];\n            int a = min(cur, nx), b = max(cur, nx);\n            int idx = pairToIdx[{a, b}];\n            usedEdge[idx] = 1;\n            cur = nx;\n        }\n    };\n    for (auto [u, v] : mstPairs) addPath(u, v);\n\n    // ---------- output ----------\n    for (int i = 1; i <= N; ++i) {\n        if (i > 1) cout << ' ';\n        cout << P[i];\n    }\n    cout << '\\n';\n    for (int j = 1; j <= M; ++j) {\n        if (j > 1) cout << ' ';\n        cout << (int)usedEdge[j];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Swap {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 30;\n    const int M = N * (N + 1) / 2;          // 465\n\n    // read the pyramid\n    vector<vector<int>> a(N);\n    for (int x = 0; x < N; ++x) {\n        a[x].resize(x + 1);\n        for (int y = 0; y <= x; ++y) {\n            cin >> a[x][y];\n        }\n    }\n\n    vector<Swap> ops;\n    ops.reserve(10000);\n\n    // bottom\u2011up heapify\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            int cx = x, cy = y;\n            while (cx + 1 < N) {\n                int leftX = cx + 1, leftY = cy;\n                int rightX = cx + 1, rightY = cy + 1;\n\n                // choose the smaller child\n                int childX, childY;\n                if (a[leftX][leftY] <= a[rightX][rightY]) {\n                    childX = leftX; childY = leftY;\n                } else {\n                    childX = rightX; childY = rightY;\n                }\n\n                if (a[childX][childY] < a[cx][cy]) {\n                    // perform the swap\n                    swap(a[cx][cy], a[childX][childY]);\n                    ops.push_back({cx, cy, childX, childY});\n                    if ((int)ops.size() >= 10000) break; // safety\n                    // continue from child's position\n                    cx = childX; cy = childY;\n                } else {\n                    break; // heap property satisfied at this node\n                }\n            }\n            if ((int)ops.size() >= 10000) break;\n        }\n        if ((int)ops.size() >= 10000) break;\n    }\n\n    // output\n    cout << ops.size() << '\\n';\n    for (auto &s : ops) {\n        cout << s.x1 << ' ' << s.y1 << ' '\n             << s.x2 << ' ' << s.y2 << '\\n';\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int D_input, N;\n    if (!(cin >> D_input >> N)) return 0;   // D = 9\n    const int D = D_input;\n    const int entrance_i = 0, entrance_j = (D - 1) / 2;\n    const int entrance_id = entrance_i * D + entrance_j;\n\n    vector<vector<int>> blocked(D, vector<int>(D, 0));\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        blocked[ri][rj] = 1;\n    }\n\n    auto inside = [&](int i, int j) {\n        return 0 <= i && i < D && 0 <= j && j < D;\n    };\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n\n    const int V = D * D;\n    vector<vector<int>> adj(V);\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            if (blocked[i][j]) continue;\n            int v = i * D + j;\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d], nj = j + dj[d];\n                if (!inside(ni, nj)) continue;\n                if (blocked[ni][nj]) continue;\n                int nb = ni * D + nj;\n                adj[v].push_back(nb);\n            }\n        }\n    }\n\n    /* BFS distances from the entrance */\n    vector<int> dist(V, -1);\n    queue<int> q;\n    dist[entrance_id] = 0;\n    q.push(entrance_id);\n    while (!q.empty()) {\n        int v = q.front(); q.pop();\n        for (int nb : adj[v]) {\n            if (dist[nb] == -1) {\n                dist[nb] = dist[v] + 1;\n                q.push(nb);\n            }\n        }\n    }\n\n    /* list of all usable cells (except entrance) sorted by distance decreasing */\n    vector<int> orderDesc;\n    for (int v = 0; v < V; ++v) {\n        if (blocked[v / D][v % D]) continue;\n        if (v == entrance_id) continue;\n        orderDesc.push_back(v);\n    }\n    sort(orderDesc.begin(), orderDesc.end(),\n         [&](int a, int b) { return dist[a] > dist[b]; });\n\n    vector<int> container(V, -1);               // -1 = empty\n    const int M = D * D - 1 - N;                 // number of containers\n    size_t ptr = 0;                             // first still empty cell in orderDesc\n\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;                               // label of the arriving container\n\n        while (ptr < orderDesc.size() && container[orderDesc[ptr]] != -1) ++ptr;\n        int v = orderDesc[ptr];                 // farthest still empty cell\n        ++ptr;\n\n        cout << v / D << ' ' << v % D << '\\n' << flush;\n        container[v] = t;\n    }\n\n    /* ----- taking\u2011out order ----- */\n    int maxDist = 0;\n    for (int v = 0; v < V; ++v) {\n        if (blocked[v / D][v % D]) continue;\n        maxDist = max(maxDist, dist[v]);\n    }\n\n    for (int d = 1; d <= maxDist; ++d) {\n        vector<int> layer;\n        for (int v = 0; v < V; ++v) {\n            if (blocked[v / D][v % D]) continue;\n            if (dist[v] == d) layer.push_back(v);\n        }\n        sort(layer.begin(), layer.end(),\n             [&](int a, int b) { return container[a] < container[b]; });\n        for (int v : layer) {\n            cout << v / D << ' ' << v % D << '\\n';\n        }\n    }\n    cout << flush;\n    return 0;\n}","ahc024":"#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    if (!(cin >> n >> m)) return 0;\n    vector<vector<int>> a(n, vector<int>(n));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (j) cout << ' ';\n            cout << a[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n\n    // No need to read weights \u2013 they are unknown.\n    // -------------------------------------------------\n    // 1) Perform the required Q queries.\n    // -------------------------------------------------\n    for (int q = 0; q < Q; ++q) {\n        // left set = {0}, right set = {1} (both non\u2011empty, disjoint)\n        cout << \"1 1 0 1\\n\" << flush;   // flush after each query\n        string ans;\n        cin >> ans;                     // read the judge's reply and ignore it\n    }\n\n    // -------------------------------------------------\n    // 2) Output a trivial division (round\u2011robin).\n    // -------------------------------------------------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << (i % D);\n    }\n    cout << '\\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    if (!(cin >> n >> m)) return 0;            // n = 200, m = 10\n    const int per = n / m;                     // 20\n    vector<vector<int>> st(m);                 // bottom -> top\n    for (int i = 0; i < m; ++i) {\n        st[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x; cin >> x;\n            st[i].push_back(x);\n        }\n    }\n\n    vector<pair<int,int>> ops;\n    ops.reserve(5000);\n\n    const int INF = n + 1;                     // larger than any label\n\n    for (int target = 1; target <= n; ++target) {\n        while (true) {\n            // locate stack s and position pos of the current target\n            int s = -1, pos = -1;\n            for (int i = 0; i < m; ++i) {\n                const auto &vec = st[i];\n                for (int j = 0; j < (int)vec.size(); ++j) {\n                    if (vec[j] == target) {\n                        s = i;\n                        pos = j;\n                        break;\n                    }\n                }\n                if (s != -1) break;\n            }\n\n            int topIdx = (int)st[s].size() - 1;\n            if (pos == topIdx) {                         // target already on top\n                ops.emplace_back(target, 0);              // pop\n                st[s].pop_back();\n                break;                                    // go to next target\n            }\n\n            // ----- block that hides target -----\n            int start = pos + 1;                         // first index of block\n            vector<int> block(st[s].begin() + start, st[s].end());\n            int maxBlock = *max_element(block.begin(), block.end());\n\n            // ----- choose destination -----\n            int dest = -1;\n            int bestTop = INF;\n            int bestSize = INT_MAX;\n\n            // first try to find a safe stack (top > maxBlock) with minimal top\n            for (int i = 0; i < m; ++i) {\n                if (i == s) continue;\n                int topVal = st[i].empty() ? INF : st[i].back();\n                if (topVal > maxBlock) {\n                    if (topVal < bestTop ||\n                        (topVal == bestTop && (int)st[i].size() < bestSize)) {\n                        bestTop = topVal;\n                        bestSize = (int)st[i].size();\n                        dest = i;\n                    }\n                }\n            }\n\n            // if no safe stack exists, pick the stack with smallest height\n            if (dest == -1) {\n                bestSize = INT_MAX;\n                for (int i = 0; i < m; ++i) {\n                    if (i == s) continue;\n                    if ((int)st[i].size() < bestSize) {\n                        bestSize = (int)st[i].size();\n                        dest = i;\n                    }\n                }\n            }\n\n            // ----- perform the move (type 1) -----\n            int v = block.front();                       // bottom of the block\n            ops.emplace_back(v, dest + 1);\n\n            // erase block from source stack\n            st[s].erase(st[s].begin() + start, st[s].end());\n            // append block to destination stack, preserving order\n            st[dest].insert(st[dest].end(), block.begin(), block.end());\n            // after this, target is on top; loop again to pop it\n        }\n    }\n\n    for (auto [v, i] : ops) {\n        cout << v << ' ' << i << '\\n';\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n\n    vector<string> h(N - 1);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    vector<string> v(N);\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    // d is read but not used\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            long long tmp;\n            cin >> tmp;\n        }\n    }\n\n    const int di[4] = {0, 1, 0, -1};\n    const int dj[4] = {1, 0, -1, 0};\n    const char moveChar[4] = {'R', 'D', 'L', 'U'};\n    const char backChar[4] = {'L', 'U', 'R', 'D'};\n\n    vector<vector<char>> visited(N, vector<char>(N, 0));\n    string answer;\n\n    function<void(int,int)> dfs = [&](int i, int j) {\n        visited[i][j] = 1;\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + di[dir];\n            int nj = j + dj[dir];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (visited[ni][nj]) continue;\n            // check wall\n            bool blocked = false;\n            if (dir == 0) { // right\n                blocked = (v[i][j] == '1');\n            } else if (dir == 2) { // left\n                blocked = (v[i][j-1] == '1');\n            } else if (dir == 1) { // down\n                blocked = (h[i][j] == '1');\n            } else { // up\n                blocked = (h[i-1][j] == '1');\n            }\n            if (blocked) continue;\n\n            answer.push_back(moveChar[dir]);\n            dfs(ni, nj);\n            answer.push_back(backChar[dir]);\n        }\n    };\n\n    dfs(0, 0);\n    cout << answer << '\\n';\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing pii = pair<int,int>;\n\nint manhattan(const pii& a, const pii& b){\n    return abs(a.first - b.first) + abs(a.second - b.second);\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N, M;\n    if(!(cin >> N >> M)) return 0;          // N = 15, M = 200 (fixed)\n    int si, sj;\n    cin >> si >> sj;\n    \n    vector<string> board(N);\n    for(int i=0;i<N;i++) cin >> board[i];\n    \n    // positions of each letter\n    vector<pii> pos[26];\n    for(int i=0;i<N;i++)\n        for(int j=0;j<N;j++)\n            pos[ board[i][j] - 'A' ].push_back({i,j});\n    \n    vector<string> words(M);\n    for(int k=0;k<M;k++) cin >> words[k];\n    \n    // ---------- compute optimal internal path for each word ----------\n    struct WordInfo{\n        vector<pii> path;   // 5 coordinates\n        pii start, finish;\n    };\n    vector<WordInfo> info(M);\n    \n    for(int idx=0; idx<M; ++idx){\n        const string& w = words[idx];\n        // lists of positions for each character\n        array<vector<pii>*,5> lst;\n        for(int p=0;p<5;p++) lst[p] = &pos[w[p]-'A'];\n        int sz[5];\n        for(int p=0;p<5;p++) sz[p] = (int)lst[p]->size();\n        \n        // dp[i][k] : minimal cost after processing character i and being at k-th position of lst[i]\n        vector<vector<int>> dp(5);\n        vector<vector<int>> pre(5);   // store previous index\n        for(int i=0;i<5;i++){\n            dp[i].assign(sz[i], INT_MAX);\n            pre[i].assign(sz[i], -1);\n        }\n        // first character: only press cost = 1\n        for(int k=0;k<sz[0];k++) dp[0][k] = 1;\n        \n        // transition\n        for(int i=1;i<5;i++){\n            for(int k=0;k<sz[i];k++){\n                const pii& cur = (*lst[i])[k];\n                int best = INT_MAX, bestPrev = -1;\n                for(int q=0;q<sz[i-1];q++){\n                    const pii& prev = (*lst[i-1])[q];\n                    int cand = dp[i-1][q] + manhattan(prev,cur) + 1;\n                    if(cand < best){\n                        best = cand;\n                        bestPrev = q;\n                    }\n                }\n                dp[i][k] = best;\n                pre[i][k] = bestPrev;\n            }\n        }\n        // find minimal end\n        int bestEnd = 0;\n        for(int k=1;k<sz[4];k++) if(dp[4][k] < dp[4][bestEnd]) bestEnd = k;\n        // reconstruct path (indices)\n        array<int,5> idxs;\n        idxs[4] = bestEnd;\n        for(int i=4;i>=1;i--){\n            idxs[i-1] = pre[i][ idxs[i] ];\n        }\n        // store coordinates\n        info[idx].path.resize(5);\n        for(int i=0;i<5;i++){\n            info[idx].path[i] = (*lst[i])[ idxs[i] ];\n        }\n        info[idx].start = info[idx].path.front();\n        info[idx].finish = info[idx].path.back();\n    }\n    \n    // ---------- greedy ordering ----------\n    vector<int> remaining(M);\n    iota(remaining.begin(), remaining.end(), 0);\n    vector<char> used(M, 0);\n    pii cur = {si, sj};\n    vector<pii> answer;\n    answer.reserve(5*M + 10);\n    \n    int left = M;\n    while(left){\n        int bestIdx = -1;\n        int bestDist = INT_MAX;\n        for(int id : remaining){\n            if(used[id]) continue;\n            int d = manhattan(cur, info[id].start);\n            if(d < bestDist){\n                bestDist = d;\n                bestIdx = id;\n            }\n        }\n        // move to start (the movement cost is automatically counted when we type)\n        // we just output the whole path\n        for(const pii& p : info[bestIdx].path){\n            answer.push_back(p);\n        }\n        cur = info[bestIdx].finish;\n        used[bestIdx] = 1;\n        --left;\n    }\n    \n    // ---------- output ----------\n    for(const auto& p : answer){\n        cout << p.first << ' ' << p.second << '\\n';\n    }\n    return 0;\n}","ahc030":"#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    double eps;\n    if (!(cin >> N >> M >> eps)) return 0;\n\n    // ---- read shapes (ignored later) ----\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        for (int t = 0; t < d; ++t) {\n            int a, b;\n            cin >> a >> b;\n        }\n    }\n\n    // ---- read positions of each field (unused) ----\n    for (int k = 0; k < M; ++k) {\n        int di, dj;\n        cin >> di >> dj;\n        (void)di; (void)dj;\n    }\n\n    // ---- read the whole v matrix ----\n    vector<vector<int>> v(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> v[i][j];\n\n    // ---- discard the remaining numbers (up to 2*N^2) ----\n    // The exact amount is not needed; just read until EOF.\n    double dummy;\n    while (cin >> dummy) { /* discard */ }\n\n    // ---- collect cells with v > 0 ----\n    vector<pair<int,int>> ans;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (v[i][j] > 0) ans.emplace_back(i, j);\n\n    // ---- output in the required format ----\n    cout << \"a \" << ans.size();\n    for (auto [i, j] : ans) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << \"\\n\";\n    cout.flush();\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    if (!(cin >> W >> D >> N)) return 0;\n    // read and ignore the desired areas\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            long long a;\n            cin >> a;\n            (void)a;\n        }\n    }\n\n    // output the simple vertical strips\n    for (int d = 0; d < D; ++d) {\n        for (int k = 0; k < N; ++k) {\n            int i0 = k;\n            int j0 = 0;\n            int i1 = k + 1;\n            int j1 = W;\n            cout << i0 << ' ' << j0 << ' ' << i1 << ' ' << j1 << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing int64 = long long;\nconst int64 MOD = 998244353LL;\n\nstruct Op {\n    int m, p, q;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;          // N = 9, M = 20, K = 81\n\n    vector<vector<int64>> init(N, vector<int64>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> init[i][j];\n\n    // stamps[m][i][j]\n    vector<array<array<int64, 3>, 3>> stamp(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 >> stamp[m][i][j];\n\n    // ---------- Greedy construction ----------\n    vector<Op> best_ops;\n    best_ops.reserve(K);\n    vector<vector<int64>> board = init;   // current board\n\n    for (int step = 0; step < K; ++step) {\n        int best_m = -1, best_p = -1, best_q = -1;\n        int64 best_gain = 0;   // we only accept strictly positive gain\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    int64 gain = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            int64 oldv = board[p + i][q + j];\n                            int64 oldr = oldv % MOD;\n                            int64 newr = (oldv + stamp[m][i][j]) % MOD;\n                            gain += newr - oldr;\n                        }\n                    }\n                    if (gain > best_gain) {\n                        best_gain = gain;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_gain <= 0) break;   // no improving press exists\n\n        // apply the chosen press\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                board[best_p + i][best_q + j] += stamp[best_m][i][j];\n\n        best_ops.push_back({best_m, best_p, best_q});\n    }\n\n    // ---------- Local\u2011search improvement ----------\n    // random generator\n    std::mt19937 rng(static_cast<unsigned>(chrono::steady_clock::now().time_since_epoch().count()));\n    uniform_int_distribution<int> dist_m(0, M - 1);\n    uniform_int_distribution<int> dist_pos(0, N - 3);\n    uniform_int_distribution<int> dist_bool(0, 1);\n    uniform_int_distribution<int> dist_idx;   // will be set later when needed\n\n    // helper to compute total score of a given operation list\n    auto compute_score = [&](const vector<Op>& ops) -> int64 {\n        vector<vector<int64>> cur = init;\n        for (const Op& op : ops) {\n            for (int i = 0; i < 3; ++i)\n                for (int j = 0; j < 3; ++j)\n                    cur[op.p + i][op.q + j] += stamp[op.m][i][j];\n        }\n        int64 sum = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                sum += cur[i][j] % MOD;\n        return sum;\n    };\n\n    int64 best_score = compute_score(best_ops);\n    const double TIME_LIMIT = 1.70;   // seconds\n    auto start_time = chrono::steady_clock::now();\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        vector<Op> cur_ops = best_ops;\n\n        if (!cur_ops.empty()) {\n            dist_idx = uniform_int_distribution<int>(0, (int)cur_ops.size() - 1);\n            int replace_idx = dist_idx(rng);\n            cur_ops[replace_idx] = {dist_m(rng), dist_pos(rng), dist_pos(rng)};\n        }\n\n        // occasionally try to add one more operation (if we still have quota)\n        if ((int)cur_ops.size() < K && dist_bool(rng) == 0) {\n            cur_ops.push_back({dist_m(rng), dist_pos(rng), dist_pos(rng)});\n        }\n\n        int64 cur_score = compute_score(cur_ops);\n        if (cur_score > best_score) {\n            best_score = cur_score;\n            best_ops.swap(cur_ops);\n        }\n    }\n\n    // ---------- Output ----------\n    cout << best_ops.size() << '\\n';\n    for (const Op& op : best_ops) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 5;\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    /* ----- small cranes: bomb immediately ----- */\n    vector<string> out(N);\n    size_t maxLen = 0;\n    for (int i = 1; i < N; ++i) {\n        out[i] = \"B\";\n        maxLen = max(maxLen, out[i].size());\n    }\n\n    /* ----- collect all containers for the large crane ----- */\n    struct Item { int src, dst; };\n    vector<Item> items;\n    for (int src = 0; src < N; ++src) {\n        for (int j = 0; j < N; ++j) {\n            int num = A[src][j];\n            int dst = num / N;\n            items.push_back({src, dst});\n        }\n    }\n\n    sort(items.begin(), items.end(),\n         [](const Item& a, const Item& b) {\n             if (a.src != b.src) return a.src < b.src;\n             return a.dst < b.dst;\n         });\n\n    /* ----- build large crane actions ----- */\n    string s0(maxLen, '.');          // wait until small cranes are gone\n    int curRow = 0, curCol = 0;      // start at (0,0)\n\n    for (const auto &it : items) {\n        int src = it.src;\n        int dst = it.dst;\n\n        // if we are at column 4, go back to column 0\n        if (curCol == 4) {\n            s0.append(4, 'L');\n            curCol = 0;\n        }\n\n        // vertical move to source row (empty crane)\n        while (curRow < src) { s0.push_back('D'); ++curRow; }\n        while (curRow > src) { s0.push_back('U'); --curRow; }\n\n        // pick\n        s0.push_back('P');\n\n        // vertical move to destination row while carrying (large crane allowed)\n        while (curRow < dst) { s0.push_back('D'); ++curRow; }\n        while (curRow > dst) { s0.push_back('U'); --curRow; }\n\n        // go right to dispatch gate\n        s0.append(4, 'R');\n        curCol = 4;\n\n        // drop (dispatch)\n        s0.push_back('Q');\n    }\n\n    out[0] = s0;\n    maxLen = max(maxLen, s0.size());\n\n    /* ----- pad all strings with '.' ----- */\n    for (auto &t : out) {\n        if (t.size() < maxLen) t.append(maxLen - t.size(), '.');\n        cout << t << '\\n';\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int r, c;\n    int amt;          // for positives: amount to load; for negatives: amount to receive\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> h[i][j];\n    \n    vector<Cell> pos, neg;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (h[i][j] > 0) pos.push_back({i, j, h[i][j]});\n            else if (h[i][j] < 0) neg.push_back({i, j, -h[i][j]});\n        }\n    \n    int curR = 0, curC = 0;          // current truck position\n    long long load = 0;              // soil currently on the truck\n    \n    auto move_to = [&](int tr, int tc) {\n        while (curR < tr) { cout << \"D\\n\"; ++curR; }\n        while (curR > tr) { cout << \"U\\n\"; --curR; }\n        while (curC < tc) { cout << \"R\\n\"; ++curC; }\n        while (curC > tc) { cout << \"L\\n\"; --curC; }\n    };\n    \n    while (!pos.empty() || !neg.empty()) {\n        if (load == 0) {\n            // find nearest positive cell\n            int best = -1, bestDist = INT_MAX;\n            for (int i = 0; i < (int)pos.size(); ++i) {\n                int d = abs(pos[i].r - curR) + abs(pos[i].c - curC);\n                if (d < bestDist) {\n                    bestDist = d;\n                    best = i;\n                }\n            }\n            // move there and load\n            move_to(pos[best].r, pos[best].c);\n            load = pos[best].amt;\n            cout << \"+\" << load << \"\\n\";\n            // remove this cell\n            pos[best] = pos.back();\n            pos.pop_back();\n        } else {\n            // we have load, go to nearest negative cell\n            int best = -1, bestDist = INT_MAX;\n            for (int i = 0; i < (int)neg.size(); ++i) {\n                int d = abs(neg[i].r - curR) + abs(neg[i].c - curC);\n                if (d < bestDist) {\n                    bestDist = d;\n                    best = i;\n                }\n            }\n            // move there\n            move_to(neg[best].r, neg[best].c);\n            int need = neg[best].amt;\n            int d = (int)min<long long>(load, need);\n            cout << \"-\" << d << \"\\n\";\n            load -= d;\n            need -= d;\n            if (need == 0) {\n                // finished this negative cell\n                neg[best] = neg.back();\n                neg.pop_back();\n            } else {\n                neg[best].amt = need;   // still needs more soil\n            }\n        }\n    }\n    // At this point load == 0 and all heights are zero.\n    return 0;\n}","ahc035":"#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, T;\n    if (!(cin >> N >> M >> T)) return 0;\n    const int SEED_CNT = 2 * N * (N - 1);   // 60 (N = 6)\n    const int BOARD = N * N;               // 36\n\n    // current seed vectors\n    vector<vector<int>> seed(SEED_CNT, vector<int>(M));\n\n    // read initial seeds\n    for (int i = 0; i < SEED_CNT; ++i)\n        for (int j = 0; j < M; ++j)\n            cin >> seed[i][j];\n\n    // adjacency of cells (0 \u2026 BOARD-1) on a 6\u00d76 grid\n    vector<vector<int>> neigh(BOARD);\n    auto id = [&](int r, int c) { return r * N + c; };\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            int v = id(r, c);\n            if (c + 1 < N) neigh[v].push_back(id(r, c + 1));\n            if (c - 1 >= 0) neigh[v].push_back(id(r, c - 1));\n            if (r + 1 < N) neigh[v].push_back(id(r + 1, c));\n            if (r - 1 >= 0) neigh[v].push_back(id(r - 1, c));\n        }\n    }\n\n    mt19937 rng(123456789);           // deterministic RNG, change seed if desired\n    uniform_int_distribution<int> cellDist(0, BOARD - 1);\n    uniform_int_distribution<int> seedDist(0, SEED_CNT - 1);\n\n    for (int turn = 0; turn < T; ++turn) {\n        /* ------------------------------------------------------------\n           1) per\u2011dimension maxima X[l]\n        ------------------------------------------------------------ */\n        vector<int> X(M, 0);\n        for (int i = 0; i < SEED_CNT; ++i)\n            for (int l = 0; l < M; ++l)\n                X[l] = max(X[l], seed[i][l]);\n\n        /* ------------------------------------------------------------\n           2) normalized scores\n        ------------------------------------------------------------ */\n        vector<double> score(SEED_CNT, 0.0);\n        for (int i = 0; i < SEED_CNT; ++i) {\n            double s = 0.0;\n            for (int l = 0; l < M; ++l) {\n                if (X[l] > 0) s += static_cast<double>(seed[i][l]) / X[l];\n            }\n            score[i] = s;\n        }\n\n        /* ------------------------------------------------------------\n           3) initial selection: one best per dimension + best scores\n        ------------------------------------------------------------ */\n        vector<int> chosen;                 // size will become BOARD\n        vector<char> inSet(SEED_CNT, 0);\n\n        // best seed for each dimension\n        for (int l = 0; l < M; ++l) {\n            int best = 0;\n            for (int i = 1; i < SEED_CNT; ++i)\n                if (seed[i][l] > seed[best][l]) best = i;\n            if (!inSet[best]) {\n                inSet[best] = 1;\n                chosen.push_back(best);\n            }\n        }\n\n        // fill remaining slots with highest normalized score\n        vector<int> order(SEED_CNT);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) { return score[a] > score[b]; });\n\n        for (int idd : order) {\n            if ((int)chosen.size() >= BOARD) break;\n            if (inSet[idd]) continue;\n            inSet[idd] = 1;\n            chosen.push_back(idd);\n        }\n\n        /* ------------------------------------------------------------\n           4) hill\u2011climbing to improve edge score\n        ------------------------------------------------------------ */\n        // placement: cell -> seed id\n        vector<int> placed(BOARD);\n        for (int c = 0; c < BOARD; ++c) placed[c] = chosen[c];\n\n        // compute current edge score\n        auto edgeScore = [&](const vector<int>& placement) -> long long {\n            long long total = 0;\n            for (int u = 0; u < BOARD; ++u) {\n                for (int v : neigh[u]) {\n                    if (v < u) continue;               // each edge once\n                    for (int l = 0; l < M; ++l)\n                        total += max(seed[placement[u]][l],\n                                    seed[placement[v]][l]);\n                }\n            }\n            return total;\n        };\n\n        long long curScore = edgeScore(placed);\n\n        const int MAX_ITER = 12000;   // enough for 2\u202fsec total\n        for (int it = 0; it < MAX_ITER; ++it) {\n            // pick a random placed cell and a random outside seed\n            int cell = cellDist(rng);\n            int outSeed = seedDist(rng);\n            if (inSet[outSeed]) continue;          // already placed\n\n            int oldSeed = placed[cell];\n            // compute delta only on edges incident to 'cell'\n            long long delta = 0;\n            for (int nb : neigh[cell]) {\n                // edge (cell, nb) before swap\n                for (int l = 0; l < M; ++l)\n                    delta -= max(seed[oldSeed][l], seed[placed[nb]][l]);\n                // after swap\n                for (int l = 0; l < M; ++l)\n                    delta += max(seed[outSeed][l], seed[placed[nb]][l]);\n            }\n\n            // accept if not worse\n            if (curScore + delta >= curScore) {\n                // update structures\n                curScore += delta;\n                placed[cell] = outSeed;\n                inSet[oldSeed] = 0;\n                inSet[outSeed] = 1;\n            }\n        }\n\n        /* ------------------------------------------------------------\n           5) output placement in row\u2011major order\n        ------------------------------------------------------------ */\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (c) cout << ' ';\n                cout << placed[id(r, c)];\n            }\n            cout << '\\n';\n        }\n        cout.flush();\n\n        /* ------------------------------------------------------------\n           6) read next generation of seeds\n        ------------------------------------------------------------ */\n        for (int i = 0; i < SEED_CNT; ++i)\n            for (int j = 0; j < M; ++j)\n                cin >> seed[i][j];\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- Hungarian algorithm (minimum assignment) ---------- */\nconst long long INF = (1LL << 60);\n\nvector<int> hungarian(const vector<vector<long long>>& a) {\n    int n = (int)a.size();\n    vector<long long> u(n + 1), v(n + 1);\n    vector<int> p(n + 1), way(n + 1);\n    for (int i = 1; i <= n; ++i) {\n        p[0] = i;\n        long long j0 = 0;\n        vector<long long> minv(n + 1, INF);\n        vector<char> used(n + 1, false);\n        do {\n            used[j0] = true;\n            int i0 = p[j0];\n            long long delta = INF;\n            long long j1 = 0;\n            for (int j = 1; j <= n; ++j) if (!used[j]) {\n                long long cur = a[i0 - 1][j - 1] - u[i0] - v[j];\n                if (cur < minv[j]) { minv[j] = cur; way[j] = (int)j0; }\n                if (minv[j] < delta) { delta = minv[j]; j1 = j; }\n            }\n            for (int j = 0; j <= n; ++j) {\n                if (used[j]) { u[p[j]] += delta; v[j] -= delta; }\n                else          minv[j] -= delta;\n            }\n            j0 = j1;\n        } while (p[j0] != 0);\n        // augmenting\n        do {\n            int j1 = way[j0];\n            p[j0] = p[j1];\n            j0 = j1;\n        } while (j0);\n    }\n    vector<int> ans(n);\n    for (int j = 1; j <= n; ++j) ans[p[j] - 1] = j - 1;\n    return ans;          // row i -> column ans[i]\n}\n\n/* ------------------------------------------------------------- */\n\nstruct Job {\n    int sx, sy, dx, dy;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, V;\n    if (!(cin >> N >> M >> V)) return 0;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) cin >> s[i];\n    for (int i = 0; i < N; ++i) cin >> t[i];\n\n    /* ----- collect cells, discard already\u2011correct ones ----- */\n    using P = pair<int,int>;\n    vector<P> src, dst;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            bool has = (s[i][j] == '1');\n            bool need = (t[i][j] == '1');\n            if (has && need) continue;          // already correct\n            if (has) src.emplace_back(i, j);\n            if (need) dst.emplace_back(i, j);\n        }\n\n    int K = (int)src.size();\n    if (K == 0) {\n        // nothing to move \u2013 still have to output a valid arm\n        cout << 2 << \"\\n\";\n        cout << 0 << ' ' << 1 << \"\\n\";\n        cout << 0 << ' ' << 0 << \"\\n\";\n        return 0;\n    }\n\n    /* ----- cost matrix (Manhattan distances) ----- */\n    vector<vector<long long>> cost(K, vector<long long>(K));\n    for (int i = 0; i < K; ++i)\n        for (int j = 0; j < K; ++j)\n            cost[i][j] = llabs(src[i].first - dst[j].first) +\n                         llabs(src[i].second - dst[j].second);\n\n    /* ----- optimal matching ----- */\n    vector<int> match = hungarian(cost);          // src i -> dst[match[i]]\n\n    /* ----- build job list ----- */\n    vector<Job> jobs;\n    jobs.reserve(K);\n    for (int i = 0; i < K; ++i)\n        jobs.push_back({src[i].first, src[i].second,\n                        dst[match[i]].first, dst[match[i]].second});\n\n    /* ----- greedy nearest\u2011neighbour ordering ----- */\n    vector<Job> ordered;\n    ordered.reserve(K);\n    int cur_rx = 0, cur_ry = 0;   // current root position (used only for ordering)\n    vector<char> taken(K, 0);\n    for (int step = 0; step < K; ++step) {\n        long long best = (1LL << 60);\n        int bestIdx = -1;\n        for (int i = 0; i < K; ++i) if (!taken[i]) {\n            long long d = llabs(jobs[i].sx - cur_rx) + llabs(jobs[i].sy - cur_ry);\n            if (d < best) { best = d; bestIdx = i; }\n        }\n        taken[bestIdx] = 1;\n        ordered.push_back(jobs[bestIdx]);\n        // approximate next root position by the destination of this job\n        cur_rx = ordered.back().dx;\n        cur_ry = ordered.back().dy;\n    }\n\n    /* ----- robot state ----- */\n    const int DX[4] = {0, 1, 0, -1};   // U D L R   (x downwards)\n    const int DY[4] = {1, 0, -1, 0};\n\n    int root_x = 0, root_y = 0;   // initial root (chosen arbitrarily inside grid)\n    int cur_dir = 0;             // initial orientation is to the right\n\n    auto output_turn = [&](char mv, char rot,\n                           char act_root = '.', char act_leaf = '.') {\n        string S;\n        S.reserve(4);\n        S.push_back(mv);\n        S.push_back(rot);\n        S.push_back(act_root);\n        S.push_back(act_leaf);\n        cout << S << \"\\n\";\n    };\n\n    auto move_root_to = [&](int tx, int ty) {\n        while (root_x != tx || root_y != ty) {\n            char mv = '.';\n            if (root_x < tx) { ++root_x; mv = 'D'; }\n            else if (root_x > tx) { --root_x; mv = 'U'; }\n            else if (root_y < ty) { ++root_y; mv = 'R'; }\n            else if (root_y > ty) { --root_y; mv = 'L'; }\n            output_turn(mv, '.');\n        }\n    };\n\n    /* rotate from cur_dir to target_dir using the minimal number of 90\u00b0 turns */\n    auto rotate_to = [&](int target_dir) {\n        int diff = (target_dir - cur_dir + 4) % 4;\n        if (diff == 0) return;\n        if (diff == 1) {                 // one clockwise\n            output_turn('.', 'R');\n            cur_dir = (cur_dir + 1) & 3;\n        } else if (diff == 3) {          // one counter\u2011clockwise\n            output_turn('.', 'L');\n            cur_dir = (cur_dir + 3) & 3;\n        } else {                         // diff == 2\n            output_turn('.', 'R');\n            cur_dir = (cur_dir + 1) & 3;\n            output_turn('.', 'R');\n            cur_dir = (cur_dir + 1) & 3;\n        }\n    };\n\n    /* move robot so that the fingertip ends on (cx,cy) */\n    auto go_to_cell = [&](int cx, int cy) {\n        int chosen_dir = -1, rx = 0, ry = 0;\n        for (int d = 0; d < 4; ++d) {\n            int nx = cx - DX[d];\n            int ny = cy - DY[d];\n            if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                chosen_dir = d;\n                rx = nx; ry = ny;\n                break;\n            }\n        }\n        move_root_to(rx, ry);\n        rotate_to(chosen_dir);\n    };\n\n    /* ----- output robot arm description (root at (0,0)) ----- */\n    cout << 2 << \"\\n\";\n    cout << 0 << ' ' << 1 << \"\\n\";\n    cout << root_x << ' ' << root_y << \"\\n\";\n\n    /* ----- execute all jobs ----- */\n    for (const Job& jb : ordered) {\n        // pick\n        go_to_cell(jb.sx, jb.sy);\n        output_turn('.', '.', '.', 'P');\n        // drop\n        go_to_cell(jb.dx, jb.dy);\n        output_turn('.', '.', '.', 'P');\n    }\n\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point { int x, y; };\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<Point> mackerel(N), sardine(N);\n    for (int i = 0; i < N; ++i) cin >> mackerel[i].x >> mackerel[i].y;\n    for (int i = 0; i < N; ++i) cin >> sardine[i].x >> sardine[i].y;\n\n    /* ------------------------------------------------------------\n       1. fine grid\n    */\n    const int G = 1200;                           // grid size\n    const int cell = (100000 + G) / G;            // 84\n    vector<vector<int>> grid(G, vector<int>(G, 0));\n\n    auto add = [&](const Point& p, int w) {\n        int gx = p.x / cell;\n        int gy = p.y / cell;\n        if (gx >= G) gx = G - 1;\n        if (gy >= G) gy = G - 1;\n        grid[gx][gy] += w;\n    };\n    for (auto &p : mackerel) add(p, +1);\n    for (auto &p : sardine)  add(p, -1);\n\n    /* ------------------------------------------------------------\n       2. 2\u2011D prefix sum\n    */\n    vector<vector<long long>> pref(G + 1, vector<long long>(G + 1, 0));\n    for (int i = 0; i < G; ++i)\n        for (int j = 0; j < G; ++j)\n            pref[i + 1][j + 1] = pref[i][j + 1] + pref[i + 1][j] -\n                                 pref[i][j] + grid[i][j];\n\n    auto rectSum = [&](int x1, int x2, int y1, int y2) -> long long {\n        // inclusive indices, assume x1\u2264x2 , y1\u2264y2\n        return pref[x2 + 1][y2 + 1] - pref[x1][y2 + 1] -\n               pref[x2 + 1][y1] + pref[x1][y1];\n    };\n\n    /* ------------------------------------------------------------\n       3. stochastic search\n    */\n    std::mt19937 rng(\n        (unsigned)chrono::high_resolution_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> distG(0, G - 1);\n    const double TIME_LIMIT = 1.90;               // seconds\n    auto start = chrono::high_resolution_clock::now();\n\n    long long bestW = LLONG_MIN;\n    int bx1 = 0, bx2 = 0, by1 = 0, by2 = 0;\n\n    auto consider = [&](int xa, int xb, int ya, int yb) {\n        if (xa > xb) swap(xa, xb);\n        if (ya > yb) swap(ya, yb);\n        long long w = rectSum(xa, xb, ya, yb);\n        if (w > bestW) {\n            bestW = w;\n            bx1 = xa; bx2 = xb;\n            by1 = ya; by2 = yb;\n        }\n    };\n\n    // pure random rectangles\n    const int RAND_ITER = 500000;\n    for (int i = 0; i < RAND_ITER; ++i) {\n        if (chrono::duration<double>(chrono::high_resolution_clock::now() - start).count()\n                > TIME_LIMIT) break;\n        int x1 = distG(rng), x2 = distG(rng);\n        int y1 = distG(rng), y2 = distG(rng);\n        consider(x1, x2, y1, y2);\n    }\n\n    // rectangles based on random fish cells\n    vector<pair<int,int>> mkIdx, sdIdx;\n    mkIdx.reserve(N); sdIdx.reserve(N);\n    for (auto &p : mackerel) {\n        int gx = min(p.x / cell, G - 1);\n        int gy = min(p.y / cell, G - 1);\n        mkIdx.emplace_back(gx, gy);\n    }\n    for (auto &p : sardine) {\n        int gx = min(p.x / cell, G - 1);\n        int gy = min(p.y / cell, G - 1);\n        sdIdx.emplace_back(gx, gy);\n    }\n    std::uniform_int_distribution<int> distMk(0, (int)mkIdx.size() - 1);\n    std::uniform_int_distribution<int> distSd(0, (int)sdIdx.size() - 1);\n\n    const int POINT_ITER = 300000;\n    for (int i = 0; i < POINT_ITER; ++i) {\n        if (chrono::duration<double>(chrono::high_resolution_clock::now() - start).count()\n                > TIME_LIMIT) break;\n        int xa, xb, ya, yb;\n        int typ = rng() & 3;\n        if (typ == 0) {                          // two mackerels\n            auto a = mkIdx[distMk(rng)];\n            auto b = mkIdx[distMk(rng)];\n            xa = a.first; xb = b.first;\n            ya = a.second; yb = b.second;\n        } else if (typ == 1) {                   // two sardines\n            auto a = sdIdx[distSd(rng)];\n            auto b = sdIdx[distSd(rng)];\n            xa = a.first; xb = b.first;\n            ya = a.second; yb = b.second;\n        } else if (typ == 2) {                   // one of each\n            auto a = mkIdx[distMk(rng)];\n            auto b = sdIdx[distSd(rng)];\n            xa = a.first; xb = b.first;\n            ya = a.second; yb = b.second;\n        } else {                                 // single cell + small margin\n            auto a = mkIdx[distMk(rng)];\n            xa = xb = a.first;\n            ya = yb = a.second;\n            xb = min(G - 1, xb + (int)(rng() % 3));\n            yb = min(G - 1, yb + (int)(rng() % 3));\n        }\n        consider(xa, xb, ya, yb);\n    }\n\n    /* ------------------------------------------------------------\n       4. local optimisation (outward + inward moves)\n    */\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        // outward moves\n        if (bx1 > 0) {\n            long long w = rectSum(bx1 - 1, bx2, by1, by2);\n            if (w > bestW) { bestW = w; --bx1; improved = true; }\n        }\n        if (bx2 + 1 < G) {\n            long long w = rectSum(bx1, bx2 + 1, by1, by2);\n            if (w > bestW) { bestW = w; ++bx2; improved = true; }\n        }\n        if (by1 > 0) {\n            long long w = rectSum(bx1, bx2, by1 - 1, by2);\n            if (w > bestW) { bestW = w; --by1; improved = true; }\n        }\n        if (by2 + 1 < G) {\n            long long w = rectSum(bx1, bx2, by1, by2 + 1);\n            if (w > bestW) { bestW = w; ++by2; improved = true; }\n        }\n        // inward moves (must keep width/height \u2265 1)\n        if (bx2 - bx1 >= 1) {\n            long long w = rectSum(bx1 + 1, bx2, by1, by2);\n            if (w > bestW) { bestW = w; ++bx1; improved = true; }\n        }\n        if (bx2 - bx1 >= 1) {\n            long long w = rectSum(bx1, bx2 - 1, by1, by2);\n            if (w > bestW) { bestW = w; --bx2; improved = true; }\n        }\n        if (by2 - by1 >= 1) {\n            long long w = rectSum(bx1, bx2, by1 + 1, by2);\n            if (w > bestW) { bestW = w; ++by1; improved = true; }\n        }\n        if (by2 - by1 >= 1) {\n            long long w = rectSum(bx1, bx2, by1, by2 - 1);\n            if (w > bestW) { bestW = w; --by2; improved = true; }\n        }\n    }\n\n    /* ------------------------------------------------------------\n       5. output\n    */\n    if (bestW <= 0) {                     // fallback empty rectangle\n        cout << 4 << '\\n';\n        cout << 0 << ' ' << 0 << '\\n';\n        cout << 1 << ' ' << 0 << '\\n';\n        cout << 1 << ' ' << 1 << '\\n';\n        cout << 0 << ' ' << 1 << '\\n';\n        return 0;\n    }\n\n    int xmin = bx1 * cell;\n    int xmax = min(100000, (bx2 + 1) * cell);\n    int ymin = by1 * cell;\n    int ymax = min(100000, (by2 + 1) * cell);\n\n    if (xmin == xmax) { ++xmax; if (xmax > 100000) xmax = 100000; }\n    if (ymin == ymax) { ++ymax; if (ymax > 100000) ymax = 100000; }\n\n    cout << 4 << '\\n';\n    cout << xmin << ' ' << ymin << '\\n';\n    cout << xmax << ' ' << ymin << '\\n';\n    cout << xmax << ' ' << ymax << '\\n';\n    cout << xmin << ' ' << ymax << '\\n';\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Placed {\n    long long x, y;   // bottom\u2011left corner\n    long long w, h;   // width, height after rotation\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    long long sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n\n    vector<long long> w_obs(N), h_obs(N);\n    for (int i = 0; i < N; ++i) cin >> w_obs[i] >> h_obs[i];\n\n    /* ------------------------------------------------------------\n       1. Greedy placement, allowing both directions U and L\n       ------------------------------------------------------------ */\n    vector<int>     chosen_rot(N);   // 0 = keep, 1 = rotate\n    vector<char>    chosen_dir(N);   // 'U' or 'L'\n    vector<int>     chosen_ref(N);   // -1 or previous index\n    vector<Placed>  placed(N);\n\n    long long curW = 0, curH = 0;   // current bounding box\n\n    for (int i = 0; i < N; ++i) {\n        long long bestScore = LLONG_MAX;\n        int      bestRot   = 0;\n        char     bestDir   = 'U';\n        int      bestRef   = -1;\n        long long bestX    = 0, bestY = 0, bestW = 0, bestH = 0;\n\n        for (int rot = 0; rot <= 1; ++rot) {\n            long long rw = (rot == 0 ? w_obs[i] : h_obs[i]);\n            long long rh = (rot == 0 ? h_obs[i] : w_obs[i]);\n\n            for (char dir : {'U', 'L'}) {\n                for (int ref = -1; ref < i; ++ref) {\n                    long long x, y;\n\n                    if (dir == 'U') {               // move upward\n                        x = (ref == -1 ? 0LL : placed[ref].x + placed[ref].w);\n                        y = 0;\n                        for (int j = 0; j < i; ++j) {\n                            // horizontal overlap ?\n                            long long l1 = x, r1 = x + rw;\n                            long long l2 = placed[j].x, r2 = placed[j].x + placed[j].w;\n                            if (r1 <= l2 || r2 <= l1) continue;\n                            y = max(y, placed[j].y + placed[j].h);\n                        }\n                    } else {                         // dir == 'L', move leftward\n                        y = (ref == -1 ? 0LL : placed[ref].y + placed[ref].h);\n                        x = 0;\n                        for (int j = 0; j < i; ++j) {\n                            // vertical overlap ?\n                            long long b1 = y, t1 = y + rh;\n                            long long b2 = placed[j].y, t2 = placed[j].y + placed[j].h;\n                            if (t1 <= b2 || t2 <= b1) continue;\n                            x = max(x, placed[j].x + placed[j].w);\n                        }\n                    }\n\n                    long long newW = max(curW, x + rw);\n                    long long newH = max(curH, y + rh);\n                    long long score = newW + newH;\n\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestRot   = rot;\n                        bestDir   = dir;\n                        bestRef   = ref;\n                        bestX     = x;\n                        bestY     = y;\n                        bestW     = rw;\n                        bestH     = rh;\n                    }\n                } // ref\n            } // dir\n        } // rot\n\n        // store the choice\n        chosen_rot[i] = bestRot;\n        chosen_dir[i] = bestDir;\n        chosen_ref[i] = bestRef;\n        placed[i] = {bestX, bestY, bestW, bestH};\n\n        curW = max(curW, bestX + bestW);\n        curH = max(curH, bestY + bestH);\n    }\n\n    /* ------------------------------------------------------------\n       2. Output the same placement for every turn\n       ------------------------------------------------------------ */\n    for (int turn = 0; turn < T; ++turn) {\n        cout << N << '\\n';\n        for (int i = 0; i < N; ++i) {\n            cout << i << ' ' << chosen_rot[i] << ' ' << chosen_dir[i] << ' '\n                 << chosen_ref[i] << '\\n';\n        }\n        cout.flush();\n\n        long long Wp, Hp;\n        if (!(cin >> Wp >> Hp)) return 0;\n        (void)Wp; (void)Hp;   // values are not needed\n    }\n    return 0;\n}","ahc041":"#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, H;\n    if (!(cin >> N >> M >> H)) return 0;\n\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n\n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n\n    // coordinates are irrelevant \u2013 just read them\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        (void)x; (void)y;\n    }\n\n    /* -------------------------------------------------------------\n       1. Greedy construction: single root + beauty\u2011ordered frontier\n       ------------------------------------------------------------- */\n    vector<int> parent(N, -1);\n    vector<int> depth(N, -1);\n    vector<char> assigned(N, 0);\n\n    using P = pair<int,int>;                     // (beauty , vertex)\n\n    priority_queue<P, vector<P>, greater<P>> freeHeap;\n    for (int v = 0; v < N; ++v) freeHeap.emplace(A[v], v);\n\n    while (!freeHeap.empty()) {\n        int root = -1;\n        while (!freeHeap.empty()) {\n            auto [val, v] = freeHeap.top(); freeHeap.pop();\n            if (!assigned[v]) { root = v; break; }\n        }\n        if (root == -1) break;   // all vertices assigned\n\n        parent[root] = -1;\n        depth[root]  = 0;\n        assigned[root] = 1;\n\n        priority_queue<P, vector<P>, greater<P>> frontier;\n        frontier.emplace(A[root], root);\n\n        while (!frontier.empty()) {\n            auto [_, u] = frontier.top(); frontier.pop();\n            if (depth[u] == H) continue;          // cannot go deeper\n            for (int nb : adj[u]) {\n                if (assigned[nb]) continue;\n                parent[nb] = u;\n                depth[nb]  = depth[u] + 1;\n                assigned[nb] = 1;\n                frontier.emplace(A[nb], nb);\n            }\n        }\n    }\n\n    /* -------------------------------------------------------------\n       2. Build children list (needed for subtree updates)\n       ------------------------------------------------------------- */\n    vector<vector<int>> children(N);\n    for (int v = 0; v < N; ++v) {\n        if (parent[v] != -1) children[parent[v]].push_back(v);\n    }\n\n    /* -------------------------------------------------------------\n       3. Helper: max depth inside the subtree rooted at `v`\n       ------------------------------------------------------------- */\n    auto subtree_max_depth = [&](int v) -> int {\n        int mx = depth[v];\n        queue<int> q;\n        q.push(v);\n        while (!q.empty()) {\n            int x = q.front(); q.pop();\n            mx = max(mx, depth[x]);\n            for (int ch : children[x]) q.push(ch);\n        }\n        return mx;\n    };\n\n    /* -------------------------------------------------------------\n       4. Local improvement \u2013 deepen high\u2011beauty vertices safely\n       ------------------------------------------------------------- */\n    const int ITER = 4;                     // number of improvement passes\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int a, int b){ return A[a] > A[b]; });   // descending beauty\n\n    for (int it = 0; it < ITER; ++it) {\n        for (int v : order) {\n            int curDepth = depth[v];\n            for (int nb : adj[v]) {\n                // candidate new depth\n                if (depth[nb] + 1 <= curDepth) continue;     // not deeper\n                if (depth[nb] + 1 > H) continue;            // would exceed limit\n\n                // avoid creating a cycle: nb must not be a descendant of v\n                bool cycle = false;\n                int cur = nb;\n                while (cur != -1) {\n                    if (cur == v) { cycle = true; break; }\n                    cur = parent[cur];\n                }\n                if (cycle) continue;\n\n                int newDepth = depth[nb] + 1;\n                int delta    = newDepth - curDepth;          // > 0\n                // safety check: every node of the subtree must stay \u2264 H\n                int maxInSub = subtree_max_depth(v);\n                if (maxInSub + delta > H) continue;          // would violate H\n\n                /* ----- perform the re\u2011attachment ----- */\n                // remove v from old parent's child list\n                if (parent[v] != -1) {\n                    auto &vec = children[parent[v]];\n                    vec.erase(remove(vec.begin(), vec.end(), v), vec.end());\n                }\n                // set new parent\n                parent[v] = nb;\n                children[nb].push_back(v);\n\n                // update depths of the whole subtree rooted at v\n                queue<int> q;\n                q.push(v);\n                while (!q.empty()) {\n                    int x = q.front(); q.pop();\n                    depth[x] += delta;\n                    for (int ch : children[x]) q.push(ch);\n                }\n                break;   // after a successful move stop trying other neighbours\n            }\n        }\n    }\n\n    /* -------------------------------------------------------------\n       5. Output\n       ------------------------------------------------------------- */\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << parent[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 20;\n    vector<string> g(N);\n    for (int i = 0; i < N; ++i) cin >> g[i];\n\n    struct Op { char d; int p; };\n    vector<Op> ans;\n\n    // collect all Oni positions\n    vector<pair<int,int>> oni;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (g[i][j] == 'x') oni.emplace_back(i, j);\n\n    for (auto [i, j] : oni) {\n        // check freedom in four directions\n        bool freeU = true, freeD = true, freeL = true, freeR = true;\n        for (int ii = 0; ii < i; ++ii) if (g[ii][j] == 'o') freeU = false;\n        for (int ii = i+1; ii < N; ++ii) if (g[ii][j] == 'o') freeD = false;\n        for (int jj = 0; jj < j; ++jj) if (g[i][jj] == 'o') freeL = false;\n        for (int jj = j+1; jj < N; ++jj) if (g[i][jj] == 'o') freeR = false;\n\n        // distances to the corresponding edge\n        int du = i + 1;\n        int dd = N - i;\n        int dl = j + 1;\n        int dr = N - j;\n\n        // choose the free direction with minimal distance\n        int bestDist = INT_MAX;\n        char dir = '?';\n        if (freeU && du < bestDist) { bestDist = du; dir = 'U'; }\n        if (freeD && dd < bestDist) { bestDist = dd; dir = 'D'; }\n        if (freeL && dl < bestDist) { bestDist = dl; dir = 'L'; }\n        if (freeR && dr < bestDist) { bestDist = dr; dir = 'R'; }\n\n        // apply the two opposite shifts\n        if (dir == 'U') {\n            for (int k = 0; k < du; ++k) ans.push_back({'U', j});\n            for (int k = 0; k < du; ++k) ans.push_back({'D', j});\n        } else if (dir == 'D') {\n            for (int k = 0; k < dd; ++k) ans.push_back({'D', j});\n            for (int k = 0; k < dd; ++k) ans.push_back({'U', j});\n        } else if (dir == 'L') {\n            for (int k = 0; k < dl; ++k) ans.push_back({'L', i});\n            for (int k = 0; k < dl; ++k) ans.push_back({'R', i});\n        } else if (dir == 'R') {\n            for (int k = 0; k < dr; ++k) ans.push_back({'R', i});\n            for (int k = 0; k < dr; ++k) ans.push_back({'L', i});\n        }\n        // after this Oni is considered removed; we do not modify g\n    }\n\n    for (auto [c, p] : ans) {\n        cout << c << ' ' << p << '\\n';\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = double;\n\n/* ---------- global data ---------- */\nstatic const int N = 100;          // fixed by the problem\nstatic const ll L = 500000;       // fixed\nstatic vector<int> T;             // target frequencies\nstatic vector<ll> pref;           // prefix sums of T\n\n/* ---------- weighted sampler (probability proportional to T[i]) ---------- */\nint weighted_sample(mt19937 &rng) {\n    uniform_int_distribution<ll> dist(0, L - 1);\n    ll r = dist(rng);\n    int lo = 0, hi = N - 1;\n    while (lo < hi) {\n        int mid = (lo + hi) >> 1;\n        if (pref[mid] > r) hi = mid;\n        else lo = mid + 1;\n    }\n    return lo;                    // 0 <= lo < N\n}\n\n/* ---------- fast evaluation using power iteration ---------- */\nld evaluate(const array<array<int, N>, N> &ab) {\n    // build transition matrix prob[i][j] (double)\n    static ld prob[N][N];\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            prob[i][j] = 0.0;\n\n    for (int i = 0; i < N; ++i) {\n        prob[i][ab[i][0]] += 0.5;   // a[i]\n        prob[i][ab[i][1]] += 0.5;   // b[i]\n    }\n\n    // power iteration\n    static ld v[N], v2[N];\n    for (int i = 0; i < N; ++i) v[i] = 1.0 / N;   // uniform start\n\n    const int ITER = 500;        // enough for convergence (N=100)\n    for (int it = 0; it < ITER; ++it) {\n        for (int j = 0; j < N; ++j) v2[j] = 0.0;\n        for (int i = 0; i < N; ++i) {\n            if (v[i] == 0.0) continue;\n            for (int j = 0; j < N; ++j) {\n                if (prob[i][j] != 0.0) v2[j] += v[i] * prob[i][j];\n            }\n        }\n        for (int i = 0; i < N; ++i) v[i] = v2[i];\n    }\n\n    // compute error \u03a3 |v[i]*L - T[i]|\n    ld err = 0.0;\n    for (int i = 0; i < N; ++i) {\n        ld expected = v[i] * (ld)L;\n        err += fabs(expected - (ld)T[i]);\n    }\n    return err;\n}\n\n/* ---------- main ---------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // input (N and L are fixed, but we read them for completeness)\n    int readN; ll readL;\n    if (!(cin >> readN >> readL)) return 0;\n    T.assign(N, 0);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n\n    // prefix sums for weighted sampling\n    pref.assign(N, 0);\n    ll acc = 0;\n    for (int i = 0; i < N; ++i) {\n        acc += T[i];\n        pref[i] = acc;\n    }\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    // initial candidate (both edges drawn proportionally to T)\n    array<array<int, N>, N> cur;          // cur[i][0]=a[i], cur[i][1]=b[i]\n    for (int i = 0; i < N; ++i) {\n        cur[i][0] = weighted_sample(rng);\n        cur[i][1] = weighted_sample(rng);\n    }\n\n    ld bestErr = evaluate(cur);\n    auto best = cur;\n\n    // time\u2011controlled hill climbing\n    const double TIME_BUDGET = 1.90;       // seconds\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_BUDGET) break;\n\n        // propose a small mutation\n        array<array<int, N>, N> cand = best;\n        int i = rng() % N;\n        bool changeA = (rng() & 1);\n        if (changeA) cand[i][0] = weighted_sample(rng);\n        else        cand[i][1] = weighted_sample(rng);\n\n        ld curErr = evaluate(cand);\n        if (curErr < bestErr) {\n            bestErr = curErr;\n            best = cand;\n        }\n    }\n\n    // output the best plan found\n    for (int i = 0; i < N; ++i) {\n        cout << best[i][0] << ' ' << best[i][1] << '\\n';\n    }\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing int64 = long long;\nusing u64   = unsigned long long;\n\n/* -------------------------------------------------------------\n   Hilbert order (grid 2^14 > 10000)\n   ------------------------------------------------------------- */\nstatic inline void rot(int n, int &x, int &y, int rx, int ry) {\n    if (ry == 0) {\n        if (rx == 1) {\n            x = n - 1 - x;\n            y = n - 1 - y;\n        }\n        swap(x, y);\n    }\n}\nstatic inline u64 hilbertOrder(int x, int y) {\n    const int LOG = 14;\n    u64 d = 0;\n    int s = 1 << (LOG - 1);\n    for (int i = LOG; i > 0; --i) {\n        int rx = (x & s) > 0;\n        int ry = (y & s) > 0;\n        d <<= 2;\n        d |= (u64)(rx * 3 ^ ry);\n        rot(s, x, y, rx, ry);\n        s >>= 1;\n    }\n    return d;\n}\n\n/* -------------------------------------------------------------\n   Euclidean distance (floor) between centre points\n   ------------------------------------------------------------- */\ninline int distFloor(const vector<int>& cx,\n                     const vector<int>& cy,\n                     int a, int b) {\n    int64 dx = (int64)cx[a] - cx[b];\n    int64 dy = (int64)cy[a] - cy[b];\n    return (int)std::sqrt((double)(dx * dx + dy * dy));\n}\n\n/* -------------------------------------------------------------\n   Prim on a dense complete graph \u2013 returns edges and total length\n   ------------------------------------------------------------- */\nstatic pair<vector<pair<int,int>>, int64>\nprimDense(const vector<int>& verts,\n          const vector<int>& cx,\n          const vector<int>& cy) {\n    int s = (int)verts.size();\n    vector<char> in(s, 0);\n    vector<int64> bestDist(s, (int64)4e18);\n    vector<int> parent(s, -1);\n    vector<pair<int,int>> edges;\n    edges.reserve(s - 1);\n    int64 total = 0;\n\n    // start from vertex 0\n    in[0] = 1;\n    for (int i = 1; i < s; ++i) {\n        int d = distFloor(cx, cy, verts[0], verts[i]);\n        bestDist[i] = d;\n        parent[i] = 0;\n    }\n\n    for (int added = 1; added < s; ++added) {\n        int u = -1;\n        int64 best = (int64)4e18;\n        for (int i = 0; i < s; ++i) if (!in[i] && bestDist[i] < best) {\n            best = bestDist[i];\n            u = i;\n        }\n        edges.emplace_back(verts[u], verts[parent[u]]);\n        total += best;\n        in[u] = 1;\n\n        // relax neighbours\n        for (int i = 0; i < s; ++i) if (!in[i]) {\n            int d = distFloor(cx, cy, verts[u], verts[i]);\n            if (d < bestDist[i]) {\n                bestDist[i] = d;\n                parent[i] = u;\n            }\n        }\n    }\n    return {edges, total};\n}\n\n/* -------------------------------------------------------------\n   Main\n   ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    vector<int> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cx[i] = (lx + rx) / 2;\n        cy[i] = (ly + ry) / 2;\n    }\n\n    /* ---------- Hilbert ordering ---------- */\n    vector<u64> ord(N);\n    for (int i = 0; i < N; ++i) ord[i] = hilbertOrder(cx[i], cy[i]);\n\n    vector<int> ids(N);\n    iota(ids.begin(), ids.end(), 0);\n    sort(ids.begin(), ids.end(),\n         [&](int a, int b){ return ord[a] < ord[b]; });\n\n    /* ---------- partition ---------- */\n    vector<vector<int>> groups(M);\n    int pos = 0;\n    for (int k = 0; k < M; ++k) {\n        groups[k].assign(ids.begin() + pos, ids.begin() + pos + G[k]);\n        pos += G[k];\n    }\n\n    /* ---------- output ---------- */\n    cout << \"!\\n\";\n    for (int k = 0; k < M; ++k) {\n        const auto &g = groups[k];\n        for (size_t i = 0; i < g.size(); ++i) {\n            if (i) cout << ' ';\n            cout << g[i];\n        }\n        cout << '\\n';\n\n        auto res = primDense(g, cx, cy);\n        for (auto &e : res.first) {\n            cout << e.first << ' ' << e.second << '\\n';\n        }\n    }\n    return 0;\n}","ahc046":"#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    if (!(cin >> N >> M)) return 0;          // N = 20, M = 40 in the official tests\n\n    vector<pair<int,int>> p(M);\n    for (int i = 0; i < M; ++i) cin >> p[i].first >> p[i].second;\n\n    int cur_i = p[0].first;   // current row\n    int cur_j = p[0].second;  // current column\n\n    vector<string> ans;\n    auto add = [&](char act, char dir) {\n        ans.emplace_back(string(1, act) + \" \" + string(1, dir));\n    };\n\n    // ---------------------------------------------------------------\n    // move one coordinate (row or column) from cur to target\n    auto move_axis = [&](int &cur, int target, char dirPos, char dirNeg) {\n        int d = abs(target - cur);\n\n        int cost_direct = d;\n        int cost_to0    = 1 + target;               // slide to 0 then forward\n        int cost_toN    = 1 + (N - 1 - target);     // slide to N-1 then backward\n\n        int best = cost_direct;\n        int method = 0; // 0 = direct, 1 = slide to 0, 2 = slide to N-1\n        if (cost_to0 < best) { best = cost_to0; method = 1; }\n        if (cost_toN < best) { best = cost_toN; method = 2; }\n\n        if (method == 0) {                     // direct moves\n            char dir = (target > cur) ? dirPos : dirNeg;\n            int step = (target > cur) ? 1 : -1;\n            for (int k = 0; k < d; ++k) {\n                add('M', dir);\n                cur += step;\n            }\n        } else if (method == 1) {              // slide to 0 then forward\n            add('S', dirNeg);                   // slide towards the border 0\n            cur = 0;\n            for (int k = 0; k < target; ++k) {\n                add('M', dirPos);\n                ++cur;\n            }\n        } else {                               // method == 2, slide to N-1 then backward\n            add('S', dirPos);                   // slide towards the opposite border\n            cur = N - 1;\n            int back = (N - 1 - target);\n            for (int k = 0; k < back; ++k) {\n                add('M', dirNeg);\n                --cur;\n            }\n        }\n    };\n    // ---------------------------------------------------------------\n\n    for (int t = 1; t < M; ++t) {\n        // vertical movement (rows)\n        move_axis(cur_i, p[t].first, 'D', 'U');\n\n        // horizontal movement (columns)\n        move_axis(cur_j, p[t].second, 'R', 'L');\n    }\n\n    for (const string &s : ans) cout << s << '\\n';\n    return 0;\n}"},"16":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Company {\n    int x, y;\n    long long r;\n};\n\nstruct Rect {\n    int x0, y0, x1, y1;                 // half\u2011open [x0,x1) \u00d7 [y0,y1)\n};\n\nint n;\nvector<Company> comp;\nvector<Rect> ans;\n\n/*--------------------------------------------------------------*/\n/* Split information for guillotine recursion */\nstruct SplitInfo {\n    bool feasible = false;\n    bool isVertical = false;\n    long long error = LLONG_MAX;\n    int splitCoord = -1;\n    vector<int> leftIds, rightIds;\n};\n\n/*--------------------------------------------------------------*/\n/* Evaluate vertical splits */\nSplitInfo evaluateVertical(const vector<int>& ids, const Rect& cur) {\n    SplitInfo best;\n    if (cur.x1 - cur.x0 < 2) return best;\n    vector<int> order = ids;\n    sort(order.begin(), order.end(),\n         [&](int a, int b){ return comp[a].x < comp[b].x; });\n\n    int m = order.size();\n    vector<long long> pref(m);\n    pref[0] = comp[order[0]].r;\n    for (int i = 1; i < m; ++i) pref[i] = pref[i-1] + comp[order[i]].r;\n    long long total = pref.back();\n    int height = cur.y1 - cur.y0;\n\n    for (int k = 1; k < m; ++k) {\n        vector<int> left(order.begin(), order.begin() + k);\n        vector<int> right(order.begin() + k, order.end());\n\n        int maxX = -1, minX = 10000;\n        for (int i : left)  maxX = max(maxX, comp[i].x);\n        for (int i : right) minX = min(minX, comp[i].x);\n        if (maxX + 1 > minX) continue;\n\n        long long sumL = pref[k-1];\n        long long sumR = total - sumL;\n        long long ideal = cur.x0 + ( (__int128)sumL + height/2 ) / height;\n        int split = (int)min<long long>(max<long long>(ideal, maxX + 1), minX);\n        if (split <= cur.x0 || split >= cur.x1) continue;\n\n        long long areaL = 1LL * (split - cur.x0) * height;\n        long long areaR = 1LL * (cur.x1 - split) * height;\n        long long err = llabs(areaL - sumL) + llabs(areaR - sumR);\n\n        if (err < best.error) {\n            best.feasible = true;\n            best.isVertical = true;\n            best.error = err;\n            best.splitCoord = split;\n            best.leftIds = move(left);\n            best.rightIds = move(right);\n        }\n    }\n    return best;\n}\n\n/* Evaluate horizontal splits */\nSplitInfo evaluateHorizontal(const vector<int>& ids, const Rect& cur) {\n    SplitInfo best;\n    if (cur.y1 - cur.y0 < 2) return best;\n    vector<int> order = ids;\n    sort(order.begin(), order.end(),\n         [&](int a, int b){ return comp[a].y < comp[b].y; });\n\n    int m = order.size();\n    vector<long long> pref(m);\n    pref[0] = comp[order[0]].r;\n    for (int i = 1; i < m; ++i) pref[i] = pref[i-1] + comp[order[i]].r;\n    long long total = pref.back();\n    int width = cur.x1 - cur.x0;\n\n    for (int k = 1; k < m; ++k) {\n        vector<int> top(order.begin(), order.begin() + k);\n        vector<int> bottom(order.begin() + k, order.end());\n\n        int maxY = -1, minY = 10000;\n        for (int i : top)    maxY = max(maxY, comp[i].y);\n        for (int i : bottom) minY = min(minY, comp[i].y);\n        if (maxY + 1 > minY) continue;\n\n        long long sumT = pref[k-1];\n        long long sumB = total - sumT;\n        long long ideal = cur.y0 + ( (__int128)sumT + width/2 ) / width;\n        int split = (int)min<long long>(max<long long>(ideal, maxY + 1), minY);\n        if (split <= cur.y0 || split >= cur.y1) continue;\n\n        long long areaT = 1LL * (split - cur.y0) * width;\n        long long areaB = 1LL * (cur.y1 - split) * width;\n        long long err = llabs(areaT - sumT) + llabs(areaB - sumB);\n\n        if (err < best.error) {\n            best.feasible = true;\n            best.isVertical = false;\n            best.error = err;\n            best.splitCoord = split;\n            best.leftIds = move(top);\n            best.rightIds = move(bottom);\n        }\n    }\n    return best;\n}\n\n/*--------------------------------------------------------------*/\n/* Guillotine recursion \u2013 always legal */\nvoid guillotine(const vector<int>& ids, const Rect& cur) {\n    if (ids.size() == 1) { ans[ids[0]] = cur; return; }\n\n    SplitInfo vInfo = evaluateVertical(ids, cur);\n    SplitInfo hInfo = evaluateHorizontal(ids, cur);\n\n    SplitInfo best;\n    if (vInfo.feasible && (!hInfo.feasible || vInfo.error <= hInfo.error))\n        best = vInfo;\n    else if (hInfo.feasible)\n        best = hInfo;\n\n    if (best.feasible) {\n        if (best.isVertical) {\n            Rect leftR  {cur.x0, cur.y0, best.splitCoord, cur.y1};\n            Rect rightR {best.splitCoord, cur.y0, cur.x1, cur.y1};\n            guillotine(best.leftIds,  leftR);\n            guillotine(best.rightIds, rightR);\n        } else {\n            Rect topR    {cur.x0, cur.y0, cur.x1, best.splitCoord};\n            Rect bottomR {cur.x0, best.splitCoord, cur.x1, cur.y1};\n            guillotine(best.leftIds,  topR);\n            guillotine(best.rightIds, bottomR);\n        }\n        return;\n    }\n\n    // fallback \u2013 unit cells (always feasible)\n    for (int i : ids)\n        ans[i] = {comp[i].x, comp[i].y, comp[i].x + 1, comp[i].y + 1};\n}\n\n/*--------------------------------------------------------------*/\ninline bool overlapPositive(const Rect& a, const Rect& b) {\n    return (a.x0 < b.x1 && a.x1 > b.x0 && a.y0 < b.y1 && a.y1 > b.y0);\n}\ninline long long area(const Rect& r) {\n    return 1LL * (r.x1 - r.x0) * (r.y1 - r.y0);\n}\n\n/*--------------------------------------------------------------*/\n/* Aggressive safe border optimisation */\nvoid improveBorders(int passes = 40, int range = 30) {\n    vector<int> px(n), py(n);\n    for (int i = 0; i < n; ++i) { px[i] = comp[i].x; py[i] = comp[i].y; }\n\n    for (int it = 0; it < passes; ++it) {\n        bool anyChange = false;\n\n        // ----- vertical neighbours -----\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) if (i != j) {\n                if (ans[i].x1 != ans[j].x0) continue;\n                int y0 = max(ans[i].y0, ans[j].y0);\n                int y1 = min(ans[i].y1, ans[j].y1);\n                if (y0 >= y1) continue;\n\n                int border = ans[i].x1;\n                long long curErr = llabs(area(ans[i]) - comp[i].r) + llabs(area(ans[j]) - comp[j].r);\n                int bestDelta = 0;\n                long long bestErr = curErr;\n\n                for (int d = -range; d <= range; ++d) if (d != 0) {\n                    int nb = border + d;\n                    if (nb - ans[i].x0 <= 0) continue;\n                    if (ans[j].x1 - nb <= 0) continue;\n                    if (px[i] + 1 > nb) continue;\n                    if (px[j]     < nb) continue;\n\n                    Rect ti = ans[i]; ti.x1 = nb;\n                    Rect tj = ans[j]; tj.x0 = nb;\n\n                    bool ok = true;\n                    for (int k = 0; k < n; ++k) if (k != i && k != j) {\n                        if (overlapPositive(ti, ans[k]) || overlapPositive(tj, ans[k])) {\n                            ok = false; break;\n                        }\n                    }\n                    if (!ok) continue;\n\n                    long long newErr = llabs(area(ti) - comp[i].r) + llabs(area(tj) - comp[j].r);\n                    if (newErr < bestErr) { bestErr = newErr; bestDelta = d; }\n                }\n\n                if (bestDelta) {\n                    int nb = border + bestDelta;\n                    ans[i].x1 = nb;\n                    ans[j].x0 = nb;\n                    anyChange = true;\n                }\n            }\n\n        // ----- horizontal neighbours -----\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j) if (i != j) {\n                if (ans[i].y1 != ans[j].y0) continue;\n                int x0 = max(ans[i].x0, ans[j].x0);\n                int x1 = min(ans[i].x1, ans[j].x1);\n                if (x0 >= x1) continue;\n\n                int border = ans[i].y1;\n                long long curErr = llabs(area(ans[i]) - comp[i].r) + llabs(area(ans[j]) - comp[j].r);\n                int bestDelta = 0;\n                long long bestErr = curErr;\n\n                for (int d = -range; d <= range; ++d) if (d != 0) {\n                    int nb = border + d;\n                    if (nb - ans[i].y0 <= 0) continue;\n                    if (ans[j].y1 - nb <= 0) continue;\n                    if (py[i] + 1 > nb) continue;\n                    if (py[j]     < nb) continue;\n\n                    Rect ti = ans[i]; ti.y1 = nb;\n                    Rect tj = ans[j]; tj.y0 = nb;\n\n                    bool ok = true;\n                    for (int k = 0; k < n; ++k) if (k != i && k != j) {\n                        if (overlapPositive(ti, ans[k]) || overlapPositive(tj, ans[k])) {\n                            ok = false; break;\n                        }\n                    }\n                    if (!ok) continue;\n\n                    long long newErr = llabs(area(ti) - comp[i].r) + llabs(area(tj) - comp[j].r);\n                    if (newErr < bestErr) { bestErr = newErr; bestDelta = d; }\n                }\n\n                if (bestDelta) {\n                    int nb = border + bestDelta;\n                    ans[i].y1 = nb;\n                    ans[j].y0 = nb;\n                    anyChange = true;\n                }\n            }\n\n        if (!anyChange) break;\n    }\n}\n\n/*--------------------------------------------------------------*/\n/* Expansion\u2011only pass (unchanged) */\nvoid expandOnlyPass(int maxIter = 5) {\n    unordered_map<int, vector<pair<int,int>>> leftSide, rightSide, topSide, bottomSide;\n    for (int i = 0; i < n; ++i) {\n        leftSide[ans[i].x0].push_back({ans[i].y0, ans[i].y1});\n        rightSide[ans[i].x1].push_back({ans[i].y0, ans[i].y1});\n        bottomSide[ans[i].y0].push_back({ans[i].x0, ans[i].x1});\n        topSide[ans[i].y1].push_back({ans[i].x0, ans[i].x1});\n    }\n    auto merge = [&](vector<pair<int,int>>& v){\n        sort(v.begin(), v.end());\n        vector<pair<int,int>> tmp;\n        for (auto &p : v) {\n            if (tmp.empty() || p.first > tmp.back().second) tmp.push_back(p);\n            else tmp.back().second = max(tmp.back().second, p.second);\n        }\n        v.swap(tmp);\n    };\n    for (auto &kv : leftSide)   merge(kv.second);\n    for (auto &kv : rightSide)  merge(kv.second);\n    for (auto &kv : topSide)    merge(kv.second);\n    for (auto &kv : bottomSide) merge(kv.second);\n\n    for (int it = 0; it < maxIter; ++it) {\n        bool any = false;\n        for (int i = 0; i < n; ++i) {\n            long long curA = area(ans[i]);\n            long long target = comp[i].r;\n            if (curA >= target) continue;   // only enlarge\n\n            struct Cand { int dir; long long newErr; };\n            vector<Cand> cand;\n\n            // left\n            if (ans[i].x0 > 0) {\n                int x = ans[i].x0 - 1;\n                bool free = true;\n                auto it = rightSide.find(x + 1);\n                if (it != rightSide.end())\n                    for (auto &p : it->second)\n                        if (p.first < ans[i].y1 && p.second > ans[i].y0) { free = false; break; }\n                if (free && comp[i].x + 1 <= ans[i].x0) {\n                    long long newA = curA + (ans[i].y1 - ans[i].y0);\n                    cand.push_back({0, llabs(newA - target)});\n                }\n            }\n            // right\n            if (ans[i].x1 < 10000) {\n                int x = ans[i].x1;\n                bool free = true;\n                auto it = leftSide.find(x);\n                if (it != leftSide.end())\n                    for (auto &p : it->second)\n                        if (p.first < ans[i].y1 && p.second > ans[i].y0) { free = false; break; }\n                if (free && comp[i].x >= ans[i].x1) {\n                    long long newA = curA + (ans[i].y1 - ans[i].y0);\n                    cand.push_back({1, llabs(newA - target)});\n                }\n            }\n            // down\n            if (ans[i].y0 > 0) {\n                int y = ans[i].y0 - 1;\n                bool free = true;\n                auto it = topSide.find(y + 1);\n                if (it != topSide.end())\n                    for (auto &p : it->second)\n                        if (p.first < ans[i].x1 && p.second > ans[i].x0) { free = false; break; }\n                if (free && comp[i].y + 1 <= ans[i].y0) {\n                    long long newA = curA + (ans[i].x1 - ans[i].x0);\n                    cand.push_back({2, llabs(newA - target)});\n                }\n            }\n            // up\n            if (ans[i].y1 < 10000) {\n                int y = ans[i].y1;\n                bool free = true;\n                auto it = bottomSide.find(y);\n                if (it != bottomSide.end())\n                    for (auto &p : it->second)\n                        if (p.first < ans[i].x1 && p.second > ans[i].x0) { free = false; break; }\n                if (free && comp[i].y >= ans[i].y1) {\n                    long long newA = curA + (ans[i].x1 - ans[i].x0);\n                    cand.push_back({3, llabs(newA - target)});\n                }\n            }\n\n            if (cand.empty()) continue;\n            auto best = min_element(cand.begin(), cand.end(),\n                                    [](const Cand& a, const Cand& b){ return a.newErr < b.newErr; });\n\n            // apply\n            if (best->dir == 0) { ans[i].x0--; leftSide[ans[i].x0].push_back({ans[i].y0, ans[i].y1}); }\n            else if (best->dir == 1) { ans[i].x1++; rightSide[ans[i].x1].push_back({ans[i].y0, ans[i].y1}); }\n            else if (best->dir == 2) { ans[i].y0--; bottomSide[ans[i].y0].push_back({ans[i].x0, ans[i].x1}); }\n            else { ans[i].y1++; topSide[ans[i].y1].push_back({ans[i].x0, ans[i].x1}); }\n\n            any = true;\n        }\n        if (!any) break;\n        for (auto &kv : leftSide)   merge(kv.second);\n        for (auto &kv : rightSide)  merge(kv.second);\n        for (auto &kv : topSide)    merge(kv.second);\n        for (auto &kv : bottomSide) merge(kv.second);\n    }\n}\n\n/*--------------------------------------------------------------*/\n/* Cheap outer\u2011border shrinking pass */\nvoid shrinkOuterBorders(int passes = 5) {\n    for (int it = 0; it < passes; ++it) {\n        bool any = false;\n        for (int i = 0; i < n; ++i) {\n            long long curA = area(ans[i]);\n            long long target = comp[i].r;\n            if (curA <= target) continue;   // only shrink if too large\n\n            // left side against board edge\n            if (ans[i].x0 == 0) {\n                // can move right while point stays inside\n                if (comp[i].x + 1 <= ans[i].x1 - 1) {\n                    long long newA = curA - (ans[i].y1 - ans[i].y0);\n                    if (llabs(newA - target) < llabs(curA - target)) {\n                        ans[i].x0++;\n                        any = true;\n                    }\n                }\n            }\n            // right side against board edge\n            if (ans[i].x1 == 10000) {\n                if (comp[i].x >= ans[i].x0 + 1) {\n                    long long newA = curA - (ans[i].y1 - ans[i].y0);\n                    if (llabs(newA - target) < llabs(curA - target)) {\n                        ans[i].x1--;\n                        any = true;\n                    }\n                }\n            }\n            // bottom side against board edge\n            if (ans[i].y0 == 0) {\n                if (comp[i].y + 1 <= ans[i].y1 - 1) {\n                    long long newA = curA - (ans[i].x1 - ans[i].x0);\n                    if (llabs(newA - target) < llabs(curA - target)) {\n                        ans[i].y0++;\n                        any = true;\n                    }\n                }\n            }\n            // top side against board edge\n            if (ans[i].y1 == 10000) {\n                if (comp[i].y >= ans[i].y0 + 1) {\n                    long long newA = curA - (ans[i].x1 - ans[i].x0);\n                    if (llabs(newA - target) < llabs(curA - target)) {\n                        ans[i].y1--;\n                        any = true;\n                    }\n                }\n            }\n        }\n        if (!any) break;\n    }\n}\n\n/*--------------------------------------------------------------*/\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    if (!(cin >> n)) return 0;\n    comp.resize(n);\n    for (int i = 0; i < n; ++i) cin >> comp[i].x >> comp[i].y >> comp[i].r;\n\n    ans.assign(n, {0,0,0,0});\n    vector<int> allIds(n);\n    iota(allIds.begin(), allIds.end(), 0);\n    Rect whole{0,0,10000,10000};\n\n    guillotine(allIds, whole);          // initial guillotine tiling\n    improveBorders(40, 30);              // aggressive safe border moves\n    expandOnlyPass(5);                   // cheap expansion of undersized rects\n    shrinkOuterBorders(5);               // modest shrinking of outer borders\n\n    for (int i = 0; i < n; ++i) {\n        const Rect &r = ans[i];\n        cout << r.x0 << ' ' << r.y0 << ' ' << r.x1 << ' ' << r.y1 << '\\n';\n    }\n    return 0;\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- state used by the beam search ---------- */\nstruct BeamState {\n    int i, j;                   // current cell\n    long long score;            // accumulated score\n    string path;                // moves taken\n    vector<char> used;          // used[tile] ?\n    int curTile;                // tile id of (i,j)\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 50;\n    int si, sj;\n    if (!(cin >> si >> sj)) return 0;\n\n    /* ---------- read tile ids ---------- */\n    int tile[N][N];\n    int maxTid = -1;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            cin >> tile[i][j];\n            maxTid = max(maxTid, tile[i][j]);\n        }\n\n    /* ---------- read cell values ---------- */\n    int cell[N][N];\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) cin >> cell[i][j];\n\n    int M = maxTid + 1;                     // number of tiles\n    vector<int> tileScore(M, 0);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            tileScore[tile[i][j]] += cell[i][j];\n\n    /* ---------- adjacency between tiles ---------- */\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    vector<vector<int>> adj(M);\n    set<pair<int,int>> edgeSeen;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            int a = tile[i][j];\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d];\n                int nj = j + dj[d];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int b = tile[ni][nj];\n                if (a == b) continue;\n                auto e = make_pair(min(a,b), max(a,b));\n                if (edgeSeen.insert(e).second) {\n                    adj[a].push_back(b);\n                    adj[b].push_back(a);\n                }\n            }\n        }\n    }\n\n    /* ---------- random generator ---------- */\n    std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count());\n    std::uniform_real_distribution<double> uni01(0.0, 1.0);\n    std::uniform_real_distribution<double> tiny(0.0, 1e-6);\n\n    const double A = 0.30;   // weight for best future neighbour\n    const double B = 0.10;   // weight for degree\n    const double D = 0.05;   // weight for two\u2011step look\u2011ahead (used only in random walk)\n    const int TIME_LIMIT_MS = 1900;   // use almost the full 2\u202fs\n    const int MAX_ITER = 200000;      // upper bound; actual limited by time\n\n    string bestPath;\n    long long bestScore = -1;\n\n    auto startClock = chrono::high_resolution_clock::now();\n\n    vector<char> baseUsed(M, 0);   // reused each iteration\n\n    for (int iter = 0; iter < MAX_ITER; ++iter) {\n        // time guard\n        if (chrono::duration_cast<chrono::milliseconds>(\n                chrono::high_resolution_clock::now() - startClock).count()\n            > TIME_LIMIT_MS) break;\n\n        bool useBeam = (iter % 30 == 0);   // beam every 30th iteration\n\n        if (!useBeam) {\n            /* ----------------- cheap weighted random walk ----------------- */\n            vector<char> used = baseUsed;\n            int ci = si, cj = sj;\n            int curTile = tile[ci][cj];\n            used[curTile] = 1;\n            long long curScore = tileScore[curTile];\n            string curPath;\n\n            while (true) {\n                struct Cand {\n                    int tid;\n                    int ni, nj;\n                    double weight;\n                    char dir;\n                };\n                vector<Cand> cand;\n\n                for (int d = 0; d < 4; ++d) {\n                    int ni = ci + di[d];\n                    int nj = cj + dj[d];\n                    if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                    int nid = tile[ni][nj];\n                    if (used[nid]) continue;\n\n                    // bestFuture and degree for nid\n                    int bestFuture = 0, degree = 0;\n                    for (int nb : adj[nid]) {\n                        if (!used[nb]) {\n                            ++degree;\n                            bestFuture = max(bestFuture, tileScore[nb]);\n                        }\n                    }\n\n                    // two\u2011step look\u2011ahead (secondFuture)\n                    double secondFuture = 0.0;\n                    for (int nb : adj[nid]) {\n                        if (used[nb]) continue;\n                        int bf_nb = 0;\n                        for (int nb2 : adj[nb]) {\n                            if (used[nb2]) continue;\n                            bf_nb = max(bf_nb, tileScore[nb2]);\n                        }\n                        // tileScore[nb] is int, A*bf_nb is double\n                        secondFuture = max(secondFuture,\n                                           tileScore[nb] + A * bf_nb);\n                    }\n\n                    double w = tileScore[nid]\n                             + A * bestFuture\n                             + B * degree\n                             + D * secondFuture\n                             + tiny(rng);\n                    char dir = (d == 0 ? 'U' : d == 1 ? 'D' : d == 2 ? 'L' : 'R');\n                    cand.push_back({nid, ni, nj, w, dir});\n                }\n\n                if (cand.empty()) break;   // dead end\n\n                // weighted random selection\n                double totalW = 0.0;\n                for (auto &c : cand) totalW += c.weight;\n                double r = uni01(rng) * totalW;\n                double acc = 0.0;\n                int chosen = 0;\n                for (int i = 0; i < (int)cand.size(); ++i) {\n                    acc += cand[i].weight;\n                    if (r <= acc) { chosen = i; break; }\n                }\n                const auto &c = cand[chosen];\n                curPath.push_back(c.dir);\n                ci = c.ni;  cj = c.nj;\n                used[c.tid] = 1;\n                curScore += tileScore[c.tid];\n            }\n\n            /* ------------------- deterministic greedy tail ------------------- */\n            while (true) {\n                struct Cand2 { int tid, ni, nj, val; char dir; };\n                vector<Cand2> cand2;\n                for (int d = 0; d < 4; ++d) {\n                    int ni = ci + di[d];\n                    int nj = cj + dj[d];\n                    if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                    int nid = tile[ni][nj];\n                    if (used[nid]) continue;\n                    cand2.push_back({nid, ni, nj, tileScore[nid],\n                                     (d == 0 ? 'U' : d == 1 ? 'D' : d == 2 ? 'L' : 'R')});\n                }\n                if (cand2.empty()) break;\n                auto it = max_element(cand2.begin(), cand2.end(),\n                                      [](const Cand2& a, const Cand2& b){ return a.val < b.val; });\n                ci = it->ni;  cj = it->nj;\n                used[it->tid] = 1;\n                curScore += it->val;\n                curPath.push_back(it->dir);\n            }\n\n            if (curScore > bestScore) {\n                bestScore = curScore;\n                bestPath = curPath;\n            }\n        } else {\n            /* -------------------- beam search (width 3) -------------------- */\n            BeamState start;\n            start.i = si; start.j = sj;\n            start.curTile = tile[si][sj];\n            start.used = baseUsed;\n            start.used[start.curTile] = 1;\n            start.score = tileScore[start.curTile];\n            start.path.clear();\n\n            vector<BeamState> beam{start};\n\n            while (!beam.empty()) {\n                vector<tuple<double, BeamState>> next;\n                for (const BeamState &st : beam) {\n                    for (int d = 0; d < 4; ++d) {\n                        int ni = st.i + di[d];\n                        int nj = st.j + dj[d];\n                        if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                        int nid = tile[ni][nj];\n                        if (st.used[nid]) continue;\n\n                        int bestFuture = 0, degree = 0;\n                        for (int nb : adj[nid]) {\n                            if (!st.used[nb]) {\n                                ++degree;\n                                bestFuture = max(bestFuture, tileScore[nb]);\n                            }\n                        }\n                        double w = tileScore[nid]\n                                 + A * bestFuture\n                                 + B * degree\n                                 + tiny(rng);\n\n                        BeamState nxt = st;               // copy\n                        nxt.i = ni; nxt.j = nj;\n                        nxt.curTile = nid;\n                        nxt.used[nid] = 1;\n                        nxt.score += tileScore[nid];\n                        nxt.path.push_back(d == 0 ? 'U' : d == 1 ? 'D' : d == 2 ? 'L' : 'R');\n\n                        next.emplace_back(w, std::move(nxt));\n                    }\n                }\n                if (next.empty()) break;\n\n                int keep = min(3, (int)next.size());\n                nth_element(next.begin(),\n                            next.begin() + keep - 1,\n                            next.end(),\n                            [](const auto& a, const auto& b){ return get<0>(a) > get<0>(b); });\n                vector<BeamState> newBeam;\n                newBeam.reserve(keep);\n                for (int i = 0; i < keep; ++i) newBeam.push_back(std::move(get<1>(next[i])));\n                beam.swap(newBeam);\n            }\n\n            // greedy tail for each final beam state\n            for (BeamState &st : beam) {\n                while (true) {\n                    struct Cand2 { int tid, ni, nj, val; char dir; };\n                    vector<Cand2> cand2;\n                    for (int d = 0; d < 4; ++d) {\n                        int ni = st.i + di[d];\n                        int nj = st.j + dj[d];\n                        if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                        int nid = tile[ni][nj];\n                        if (st.used[nid]) continue;\n                        cand2.push_back({nid, ni, nj, tileScore[nid],\n                                         (d == 0 ? 'U' : d == 1 ? 'D' : d == 2 ? 'L' : 'R')});\n                    }\n                    if (cand2.empty()) break;\n                    auto it = max_element(cand2.begin(), cand2.end(),\n                                          [](const Cand2& a, const Cand2& b){ return a.val < b.val; });\n                    st.i = it->ni;  st.j = it->nj;\n                    st.used[it->tid] = 1;\n                    st.score += it->val;\n                    st.path.push_back(it->dir);\n                }\n\n                if (st.score > bestScore) {\n                    bestScore = st.score;\n                    bestPath = st.path;\n                }\n            }\n\n            // handle case where beam died immediately\n            if (beam.empty()) {\n                long long sc = tileScore[tile[si][sj]];\n                if (sc > bestScore) {\n                    bestScore = sc;\n                    bestPath.clear();\n                }\n            }\n        }\n    }\n\n    cout << bestPath << '\\n';\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Edge {\n    int to;   // neighbour vertex id\n    int id;   // unique undirected edge id\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int H = 30, W = 30;\n    const int V = H * W;\n    const int E = (H * (W - 1)) + ((H - 1) * W);   // total undirected edges\n\n    /* ---------- graph ---------- */\n    vector<vector<Edge>> g(V);\n    auto vid = [&](int i, int j) { return i * W + j; };\n    int eid = 0;\n\n    // horizontal edges (row i, col j)   0 \u2264 j < W\u20111\n    for (int i = 0; i < H; ++i)\n        for (int j = 0; j < W - 1; ++j) {\n            int a = vid(i, j), b = vid(i, j + 1);\n            g[a].push_back({b, eid});\n            g[b].push_back({a, eid});\n            ++eid;\n        }\n    // vertical edges (row i, col j)     0 \u2264 i < H\u20111\n    for (int i = 0; i < H - 1; ++i)\n        for (int j = 0; j < W; ++j) {\n            int a = vid(i, j), b = vid(i + 1, j);\n            g[a].push_back({b, eid});\n            g[b].push_back({a, eid});\n            ++eid;\n        }\n    assert(eid == E);\n\n    /* ---------- learning data ---------- */\n    vector<long double> total(E, 0.0L);\n    vector<int>        cnt(E, 0);\n    vector<long double> raw(E, 1.0L);   // per\u2011edge average (total / cnt)\n\n    // row/column averages (initially 1.0)\n    vector<long double> horRow(H, 1.0L);\n    vector<long double> verCol(W, 1.0L);\n\n    const int Q   = 1000;\n    const int K   = 30;   // first K queries: random\u2011shuffled Manhattan\n    const int TH  = 10;   // after TH observations we trust the edge itself\n    const int LAMBDA = 10; // blending constant for poorly\u2011observed edges\n\n    std::mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    for (int q = 0; q < Q; ++q) {\n        int si, sj, ti, tj;\n        if (!(cin >> si >> sj >> ti >> tj)) break;\n        int s = vid(si, sj);\n        int t = vid(ti, tj);\n\n        string path;\n        vector<int> used_edges;   // ids of edges traversed in this query\n\n        if (q < K) {   // ---------- exploration: shuffled Manhattan ----------\n            int dv = ti - si;           // vertical displacement\n            int dh = tj - sj;           // horizontal displacement\n\n            vector<char> moves;\n            moves.reserve(abs(dv) + abs(dh));\n\n            char vdir = (dv > 0) ? 'D' : 'U';\n            for (int i = 0; i < abs(dv); ++i) moves.push_back(vdir);\n            char hdir = (dh > 0) ? 'R' : 'L';\n            for (int i = 0; i < abs(dh); ++i) moves.push_back(hdir);\n\n            shuffle(moves.begin(), moves.end(), rng);\n            path.assign(moves.begin(), moves.end());\n\n            // collect edge ids\n            int curi = si, curj = sj;\n            for (char c : path) {\n                int ni = curi, nj = curj;\n                if (c == 'U') --ni;\n                else if (c == 'D') ++ni;\n                else if (c == 'L') --nj;\n                else ++nj;                // 'R'\n                int a = vid(curi, curj);\n                int b = vid(ni, nj);\n                int edge_id = -1;\n                for (const auto &e : g[a]) if (e.to == b) { edge_id = e.id; break; }\n                used_edges.push_back(edge_id);\n                curi = ni; curj = nj;\n            }\n        } else {        // ---------- Dijkstra with blended weights ----------\n            const long double INF = 1e100L;\n            vector<long double> dist(V, INF);\n            vector<int>    prev_v(V, -1);\n            vector<char>   prev_dir(V, 0);\n\n            using State = pair<long double, int>;\n            priority_queue<State, vector<State>, greater<State>> pq;\n            dist[s] = 0;\n            pq.emplace(0.0L, s);\n\n            while (!pq.empty()) {\n                auto [d, v] = pq.top(); pq.pop();\n                if (d != dist[v]) continue;\n                if (v == t) break;\n                for (const auto &e : g[v]) {\n                    long double w;\n                    int vi = v / W, vj = v % W;\n                    int ti2 = e.to / W, tj2 = e.to % W;\n                    if (vi == ti2) {                         // horizontal edge\n                        if (cnt[e.id] >= TH) w = raw[e.id];\n                        else {\n                            long double avg = horRow[vi];\n                            w = (cnt[e.id] * raw[e.id] + LAMBDA * avg) /\n                                (cnt[e.id] + LAMBDA);\n                        }\n                    } else {                                 // vertical edge\n                        if (cnt[e.id] >= TH) w = raw[e.id];\n                        else {\n                            long double avg = verCol[vj];\n                            w = (cnt[e.id] * raw[e.id] + LAMBDA * avg) /\n                                (cnt[e.id] + LAMBDA);\n                        }\n                    }\n                    if (dist[e.to] > d + w) {\n                        dist[e.to] = d + w;\n                        prev_v[e.to] = v;\n                        char dir = '?';\n                        if (ti2 == vi - 1) dir = 'U';\n                        else if (ti2 == vi + 1) dir = 'D';\n                        else if (tj2 == vj - 1) dir = 'L';\n                        else if (tj2 == vj + 1) dir = 'R';\n                        prev_dir[e.to] = dir;\n                        pq.emplace(dist[e.to], e.to);\n                    }\n                }\n            }\n\n            // reconstruct path\n            int cur = t;\n            while (cur != s) {\n                int p = prev_v[cur];\n                path.push_back(prev_dir[cur]);\n                int edge_id = -1;\n                for (const auto &e : g[p]) if (e.to == cur) { edge_id = e.id; break; }\n                used_edges.push_back(edge_id);\n                cur = p;\n            }\n            reverse(path.begin(), path.end());\n            reverse(used_edges.begin(), used_edges.end());\n        }\n\n        // ---------- output ----------\n        cout << path << '\\n' << flush;\n\n        // ---------- read judge response ----------\n        long long reported;   // round(true_len * e_k)\n        cin >> reported;\n\n        // ---------- update per\u2011edge statistics ----------\n        int L = (int)used_edges.size();               // number of edges on this path\n        long double contrib = (long double)reported / (long double)L; // unbiased per\u2011edge contribution\n        for (int id : used_edges) {\n            total[id] += contrib;\n            ++cnt[id];\n            raw[id] = total[id] / (long double)cnt[id];\n        }\n\n        // ---------- recompute row / column averages ----------\n        // Horizontal edges (first H*(W-1) ids)\n        fill(horRow.begin(), horRow.end(), 0.0L);\n        vector<int> horCnt(H, 0);\n        for (int i = 0; i < H; ++i) {\n            for (int j = 0; j < W - 1; ++j) {\n                int id = i * (W - 1) + j;\n                horRow[i] += raw[id];\n                ++horCnt[i];\n            }\n        }\n        for (int i = 0; i < H; ++i) {\n            if (horCnt[i]) horRow[i] /= (long double)horCnt[i];\n            else horRow[i] = 1.0L;\n        }\n\n        // Vertical edges (ids start after all horizontals)\n        fill(verCol.begin(), verCol.end(), 0.0L);\n        vector<int> verCnt(W, 0);\n        int baseVert = H * (W - 1);\n        for (int i = 0; i < H - 1; ++i) {\n            for (int j = 0; j < W; ++j) {\n                int id = baseVert + i * W + j;\n                verCol[j] += raw[id];\n                ++verCnt[j];\n            }\n        }\n        for (int j = 0; j < W; ++j) {\n            if (verCnt[j]) verCol[j] /= (long double)verCnt[j];\n            else verCol[j] = 1.0L;\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 20;                     // board size (fixed)\n\n/*------------------------------------------------------------*/\n/*  Does string s appear as a horizontal or vertical subsequence */\n/*------------------------------------------------------------*/\nbool appears(const vector<string>& board, const string& s) {\n    int L = (int)s.size();\n\n    // horizontal\n    for (int r = 0; r < N; ++r) {\n        for (int start = 0; start < N; ++start) {\n            bool ok = true;\n            for (int p = 0; p < L; ++p) {\n                int c = (start + p) % N;\n                if (board[r][c] != s[p]) { ok = false; break; }\n            }\n            if (ok) return true;\n        }\n    }\n\n    // vertical\n    for (int c = 0; c < N; ++c) {\n        for (int start = 0; start < N; ++start) {\n            bool ok = true;\n            for (int p = 0; p < L; ++p) {\n                int r = (start + p) % N;\n                if (board[r][c] != s[p]) { ok = false; break; }\n            }\n            if (ok) return true;\n        }\n    }\n    return false;\n}\n\n/*------------------------------------------------------------*/\n/*  Greedy construction of a board for a given order          */\n/*------------------------------------------------------------*/\nvector<string> greedy_build(const vector<string>& strs,\n                            const vector<int>& order,\n                            mt19937& rng) {\n    vector<string> board(N, string(N, '.'));\n\n    uniform_int_distribution<int> dist_letter(0, 7);   // A..H\n\n    for (int idx : order) {\n        const string& s = strs[idx];\n        int L = (int)s.size();\n\n        struct Placement { bool horiz; int line; int start; };\n        vector<Placement> bestList;\n        int bestGain = -1;\n\n        for (int orient = 0; orient < 2; ++orient) {          // 0 = horiz, 1 = vert\n            bool horiz = (orient == 0);\n            for (int line = 0; line < N; ++line) {\n                for (int start = 0; start < N; ++start) {\n                    bool ok = true;\n                    int gain = 0;\n                    for (int p = 0; p < L; ++p) {\n                        int i = horiz ? line : (start + p) % N;\n                        int j = horiz ? (start + p) % N : line;\n                        char cur = board[i][j];\n                        if (cur != '.' && cur != s[p]) { ok = false; break; }\n                        if (cur == '.') ++gain;\n                    }\n                    if (!ok) continue;\n                    if (gain > bestGain) {\n                        bestGain = gain;\n                        bestList.clear();\n                        bestList.push_back({horiz, line, start});\n                    } else if (gain == bestGain) {\n                        bestList.push_back({horiz, line, start});\n                    }\n                }\n            }\n        }\n\n        if (bestList.empty()) continue;   // cannot place this string\n\n        uniform_int_distribution<int> die(0, (int)bestList.size() - 1);\n        Placement pl = bestList[die(rng)];\n\n        // write the string\n        for (int p = 0; p < L; ++p) {\n            int i = pl.horiz ? pl.line : (pl.start + p) % N;\n            int j = pl.horiz ? (pl.start + p) % N : pl.line;\n            board[i][j] = s[p];\n        }\n    }\n\n    // fill remaining '.' with random letters\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (board[i][j] == '.')\n                board[i][j] = char('A' + dist_letter(rng));\n\n    return board;\n}\n\n/*------------------------------------------------------------*/\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N_input, M;\n    if (!(cin >> N_input >> M)) return 0;   // N_input is always 20, ignored\n    vector<string> strs(M);\n    for (int i = 0; i < M; ++i) cin >> strs[i];\n\n    /*--- order strings by decreasing length (stable) ---*/\n    vector<int> baseOrder(M);\n    iota(baseOrder.begin(), baseOrder.end(), 0);\n    sort(baseOrder.begin(), baseOrder.end(),\n         [&](int a, int b) { return strs[a].size() > strs[b].size(); });\n\n    random_device rd;\n    mt19937 rng(rd());\n\n    vector<string> bestBoard;\n    int bestScore = -1;\n\n    const auto overall_deadline = chrono::steady_clock::now() + chrono::milliseconds(2800);\n    const auto greedy_deadline  = chrono::steady_clock::now() + chrono::milliseconds(1200);\n    const auto insert_deadline  = chrono::steady_clock::now() + chrono::milliseconds(2000);\n\n    /*------------------- greedy restarts -------------------*/\n    while (chrono::steady_clock::now() < greedy_deadline) {\n        // slight randomisation inside equal\u2011length groups\n        vector<int> order = baseOrder;\n        for (size_t i = 0; i + 1 < order.size(); ++i) {\n            if (strs[order[i]].size() == strs[order[i + 1]].size())\n                if (uniform_int_distribution<int>(0, 1)(rng))\n                    swap(order[i], order[i + 1]);\n        }\n\n        vector<string> board = greedy_build(strs, order, rng);\n\n        // evaluate score\n        int cnt = 0;\n        for (const string& s : strs) if (appears(board, s)) ++cnt;\n\n        if (cnt > bestScore) {\n            bestScore = cnt;\n            bestBoard = std::move(board);\n        }\n    }\n\n    /*--------------- insert still\u2011unmatched strings ---------------*/\n    if (!bestBoard.empty()) {\n        vector<string> board = bestBoard;\n        vector<char> matched(M, 0);\n        int curScore = bestScore;\n\n        for (int i = 0; i < M; ++i)\n            if (appears(board, strs[i])) matched[i] = 1;\n\n        while (chrono::steady_clock::now() < insert_deadline) {\n            bool anyPlaced = false;\n\n            // collect unmatched indices and shuffle\n            vector<int> undone;\n            undone.reserve(M);\n            for (int i = 0; i < M; ++i) if (!matched[i]) undone.push_back(i);\n            if (undone.empty()) break;\n            shuffle(undone.begin(), undone.end(), rng);\n\n            for (int idx : undone) {\n                const string& s = strs[idx];\n                int L = (int)s.size();\n\n                struct Placement { bool horiz; int line; int start; };\n                vector<Placement> cand;\n                int bestGain = -1;\n\n                for (int orient = 0; orient < 2; ++orient) {\n                    bool horiz = (orient == 0);\n                    for (int line = 0; line < N; ++line) {\n                        for (int start = 0; start < N; ++start) {\n                            bool ok = true;\n                            int gain = 0;\n                            for (int p = 0; p < L; ++p) {\n                                int i = horiz ? line : (start + p) % N;\n                                int j = horiz ? (start + p) % N : line;\n                                char cur = board[i][j];\n                                if (cur != '.' && cur != s[p]) { ok = false; break; }\n                                if (cur == '.') ++gain;\n                            }\n                            if (!ok) continue;\n                            if (gain > bestGain) {\n                                bestGain = gain;\n                                cand.clear();\n                                cand.push_back({horiz, line, start});\n                            } else if (gain == bestGain) {\n                                cand.push_back({horiz, line, start});\n                            }\n                        }\n                    }\n                }\n                if (cand.empty()) continue;           // cannot place now\n\n                uniform_int_distribution<int> die(0, (int)cand.size() - 1);\n                Placement pl = cand[die(rng)];\n\n                // write the string\n                for (int p = 0; p < L; ++p) {\n                    int i = pl.horiz ? pl.line : (pl.start + p) % N;\n                    int j = pl.horiz ? (pl.start + p) % N : pl.line;\n                    board[i][j] = s[p];\n                }\n                matched[idx] = 1;\n                ++curScore;\n                anyPlaced = true;\n            }\n            if (!anyPlaced) break;\n        }\n\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestBoard = std::move(board);\n        }\n    }\n\n    /*---------------------- hill\u2011climbing ----------------------*/\n    while (chrono::steady_clock::now() < overall_deadline) {\n        int i = uniform_int_distribution<int>(0, N - 1)(rng);\n        int j = uniform_int_distribution<int>(0, N - 1)(rng);\n        char old = bestBoard[i][j];\n        char nd = char('A' + uniform_int_distribution<int>(0, 7)(rng));\n        if (nd == old) continue;\n\n        bestBoard[i][j] = nd;\n\n        // recompute whole score\n        int newScore = 0;\n        for (const string& s : strs) if (appears(bestBoard, s)) ++newScore;\n\n        if (newScore >= bestScore) {\n            bestScore = newScore;\n        } else {\n            bestBoard[i][j] = old;   // revert\n        }\n    }\n\n    /*----------------------- output ------------------------*/\n    if (bestBoard.empty()) {            // fallback \u2013 completely random board\n        bestBoard.assign(N, string(N, '.'));\n        uniform_int_distribution<int> d(0, 7);\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                bestBoard[i][j] = char('A' + d(rng));\n    }\n\n    for (const string& row : bestBoard) cout << row << '\\n';\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell { int i, j; };\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, si, sj;\n    if (!(cin >> N >> si >> sj)) return 0;\n    vector<string> g(N);\n    for (int i = 0; i < N; ++i) cin >> g[i];\n\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n    const char mv[4] = {'U', 'D', 'L', 'R'};\n    const char rev[4] = {'D', 'U', 'R', 'L'};\n\n    /* ---------- enumerate road cells ---------- */\n    vector<vector<int>> idx(N, vector<int>(N, -1));\n    vector<Cell> cells;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (g[i][j] != '#') {\n                idx[i][j] = (int)cells.size();\n                cells.push_back({i, j});\n            }\n\n    int V = cells.size();\n    if (V == 0) { cout << \"\\n\"; return 0; }\n\n    /* ---------- adjacency with weights (cost of destination) ---------- */\n    struct Edge { int to; int w; int dir; };\n    vector<vector<Edge>> adj(V);\n    for (int v = 0; v < V; ++v) {\n        int i = cells[v].i, j = cells[v].j;\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + di[d], nj = j + dj[d];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (g[ni][nj] == '#') continue;\n            int u = idx[ni][nj];\n            int w = g[ni][nj] - '0';\n            adj[v].push_back({u, w, d});\n        }\n    }\n\n    int start = idx[si][sj];\n    vector<char> visited(V, 0);\n    int visitedCnt = 0;\n\n    auto expand = [&](int i, int j) {\n        // left\n        for (int y = j; y >= 0 && g[i][y] != '#'; --y) {\n            int v = idx[i][y];\n            if (!visited[v]) { visited[v] = 1; ++visitedCnt; }\n        }\n        // right\n        for (int y = j; y < N && g[i][y] != '#'; ++y) {\n            int v = idx[i][y];\n            if (!visited[v]) { visited[v] = 1; ++visitedCnt; }\n        }\n        // up\n        for (int x = i; x >= 0 && g[x][j] != '#'; --x) {\n            int v = idx[x][j];\n            if (!visited[v]) { visited[v] = 1; ++visitedCnt; }\n        }\n        // down\n        for (int x = i; x < N && g[x][j] != '#'; ++x) {\n            int v = idx[x][j];\n            if (!visited[v]) { visited[v] = 1; ++visitedCnt; }\n        }\n    };\n\n    visited[start] = 1;\n    ++visitedCnt;\n    expand(si, sj);\n\n    const int MAXW = 9;\n    const long long INF = (1LL << 60);\n    vector<long long> dist(V);\n    vector<int> pred(V);\n    vector<char> predDir(V);\n\n    /* ---------- Dial\u2019s algorithm (bucket Dijkstra) ---------- */\n    auto dial = [&](int src, bool stopAtUnvisited,\n                    int &targetIdx, long long &targetDist) {\n        int maxDist = MAXW * V;               // upper bound on any distance\n        vector<vector<int>> bucket(maxDist + 1);\n        fill(dist.begin(), dist.end(), INF);\n        fill(pred.begin(), pred.end(), -1);\n        fill(predDir.begin(), predDir.end(), -1);\n\n        dist[src] = 0;\n        bucket[0].push_back(src);\n        int curDist = 0;\n        targetIdx = -1;\n        targetDist = INF;\n\n        while (curDist <= maxDist) {\n            if (bucket[curDist].empty()) { ++curDist; continue; }\n            int v = bucket[curDist].back();\n            bucket[curDist].pop_back();\n            if (dist[v] != curDist) continue;          // outdated entry\n\n            if (stopAtUnvisited && !visited[v]) {\n                targetIdx = v;\n                targetDist = curDist;\n                break;\n            }\n\n            for (const auto &e : adj[v]) {\n                int to = e.to;\n                long long nd = curDist + e.w;\n                if (nd < dist[to]) {\n                    dist[to] = nd;\n                    pred[to] = v;\n                    predDir[to] = e.dir;\n                    bucket[nd].push_back(to);\n                }\n            }\n        }\n    };\n\n    string answer;\n    int cur = start;\n\n    while (visitedCnt < V) {\n        int target;\n        long long dummydist;\n        dial(cur, true, target, dummydist);   // stop at first unvisited\n\n        // reconstruct path from cur to target\n        string path;\n        int walk = target;\n        while (walk != cur) {\n            char d = predDir[walk];\n            path.push_back(mv[d]);\n            walk = pred[walk];\n        }\n        reverse(path.begin(), path.end());\n\n        answer += path;\n\n        // walk along the path, expanding visibility\n        int pi = cells[cur].i, pj = cells[cur].j;\n        for (char c : path) {\n            int d = (c == 'U') ? 0 : (c == 'D') ? 1 : (c == 'L') ? 2 : 3;\n            pi += di[d];\n            pj += dj[d];\n            int v = idx[pi][pj];\n            if (!visited[v]) { visited[v] = 1; ++visitedCnt; }\n            expand(pi, pj);\n        }\n        cur = target;\n    }\n\n    /* ---------- return to start ---------- */\n    if (cur != start) {\n        int dummy;\n        long long dummyDist;\n        dial(cur, false, dummy, dummyDist);   // full Dijkstra to start\n        // reconstruct path cur -> start\n        string backPath;\n        int walk = start;\n        while (walk != cur) {\n            char d = predDir[walk];\n            backPath.push_back(mv[d]);\n            walk = pred[walk];\n        }\n        reverse(backPath.begin(), backPath.end());\n        answer += backPath;\n    }\n\n    cout << answer << '\\n';\n    return 0;\n}","future-contest-2022-qual":"#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, K, R;\n    if (!(cin >> N >> M >> K >> R)) return 0;\n\n    /* ---------- read required\u2011skill vectors, compute need ---------- */\n    vector<int> need(N);\n    for (int i = 0; i < N; ++i) {\n        long long sum = 0;\n        for (int j = 0; j < K; ++j) {\n            int x; cin >> x;\n            sum += x;\n        }\n        need[i] = (int)sum;\n    }\n\n    /* --------------------------- DAG -------------------------------- */\n    vector<vector<int>> out(N);\n    vector<int> indeg(N, 0);\n    for (int i = 0; i < R; ++i) {\n        int u, v; cin >> u >> v;\n        --u; --v;\n        out[u].push_back(v);\n        ++indeg[v];\n    }\n\n    /* ---------------- weighted critical\u2011path rank ------------------- */\n    vector<int> rank(N);\n    for (int i = N - 1; i >= 0; --i) {\n        int best = 0;\n        for (int v : out[i]) best = max(best, rank[v]);\n        rank[i] = need[i] + best;\n    }\n\n    /* ---------------------- initial state --------------------------- */\n    vector<int> state(N, -1);               // -1 not started, 0 started, 1 finished\n    vector<int> ready;\n    for (int i = 0; i < N; ++i) if (indeg[i] == 0) ready.push_back(i);\n\n    vector<int> member_task(M, -1);          // -1 = idle, otherwise task id\n    vector<int> start_day(M, -1);\n\n    vector<double> total_est(M, 0.0);\n    vector<int>    cnt_est(M, 0);\n    vector<double> skill(M, -1.0);           // -1 = unknown\n\n    int day = 0;\n    while (true) {\n        ++day;\n\n        /* -------------------- idle members ------------------------ */\n        vector<int> idle;\n        for (int j = 0; j < M; ++j) if (member_task[j] == -1) idle.push_back(j);\n\n        sort(idle.begin(), idle.end(),\n            [&](int a, int b) {\n                double sa = (cnt_est[a] == 0 ? -1.0 : skill[a]);\n                double sb = (cnt_est[b] == 0 ? -1.0 : skill[b]);\n                if (sa < 0 && sb < 0) return a < b;\n                if (sa < 0) return false;   // unknown after known\n                if (sb < 0) return true;\n                return sa > sb;              // descending known skill\n            });\n\n        /* -------------------- ready tasks ------------------------ */\n        sort(ready.begin(), ready.end(),\n            [&](int a, int b) {\n                if (rank[a] != rank[b]) return rank[a] > rank[b];\n                return need[a] > need[b];\n            });\n\n        int assign_cnt = min<int>(idle.size(), ready.size());\n        vector<pair<int,int>> out_pairs;\n        out_pairs.reserve(assign_cnt);\n\n        for (int i = 0; i < assign_cnt; ++i) {\n            int mem = idle[i];\n            int tas = ready[i];\n            member_task[mem] = tas;\n            start_day[mem]   = day;\n            state[tas]        = 0;               // started\n            out_pairs.emplace_back(mem, tas);\n        }\n\n        // erase assigned tasks from ready\n        if (assign_cnt > 0) ready.erase(ready.begin(),\n                                        ready.begin() + assign_cnt);\n\n        /* ------------------------ output --------------------------- */\n        cout << out_pairs.size();\n        for (auto [mem, tas] : out_pairs)\n            cout << ' ' << mem + 1 << ' ' << tas + 1;\n        cout << '\\n';\n        cout.flush();\n\n        /* ------------------- read judge answer -------------------- */\n        string line;\n        if (!getline(cin, line)) break;\n        while (!line.empty() && (line.back() == '\\r' || line.back() == '\\n')) line.pop_back();\n        if (line.empty()) {                     // possible empty line after flush\n            if (!getline(cin, line)) break;\n            while (!line.empty() && (line.back() == '\\r' || line.back() == '\\n')) line.pop_back();\n        }\n        if (line == \"-1\") break;                // all finished or day limit\n\n        stringstream ss(line);\n        int cnt; ss >> cnt;\n        vector<int> fin(cnt);\n        for (int i = 0; i < cnt; ++i) {\n            ss >> fin[i];\n            --fin[i];                           // to 0\u2011based\n        }\n\n        /* ------------------- process completions ------------------- */\n        for (int mem : fin) {\n            int tas = member_task[mem];\n            if (tas == -1) continue;            // safety\n\n            member_task[mem] = -1;               // becomes idle\n            state[tas] = 1;                      // finished\n\n            // update skill estimate\n            int dur = day - start_day[mem] + 1;   // inclusive\n            double est = (double)need[tas] - (dur - 1);\n            if (est < 0) est = 0.0;\n            total_est[mem] += est;\n            ++cnt_est[mem];\n            skill[mem] = total_est[mem] / cnt_est[mem];\n\n            // unlock successors\n            for (int v : out[tas]) {\n                if (--indeg[v] == 0 && state[v] == -1) ready.push_back(v);\n            }\n        }\n    }\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Order {\n    int a, b, c, d;\n};\n\ninline int manhattan(int x1, int y1, int x2, int y2) {\n    return abs(x1 - x2) + abs(y1 - y2);\n}\n\n/* point inside the route */\nstruct Node {\n    int id;          // order index (0\u2011based)\n    bool pickup;     // true = restaurant, false = destination\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const pair<int,int> office = {400, 400};\n\n    /* ---------- read input ---------- */\n    vector<Order> orders(1000);\n    for (auto &o : orders) cin >> o.a >> o.b >> o.c >> o.d;\n\n    /* ---------- 1. select 50 orders with smallest round\u2011trip cost ---------- */\n    struct Cand { long long round; int idx; };\n    vector<Cand> cand(1000);\n    for (int i = 0; i < 1000; ++i) {\n        const Order &o = orders[i];\n        long long inner = manhattan(o.a, o.b, o.c, o.d);\n        long long round = manhattan(office.first, office.second, o.a, o.b)\n                        + inner\n                        + manhattan(o.c, o.d, office.first, office.second);\n        cand[i] = {round, i};\n    }\n    nth_element(cand.begin(), cand.begin() + 50, cand.end(),\n                [](const Cand& x, const Cand& y){ return x.round < y.round; });\n    vector<int> selected;\n    selected.reserve(50);\n    vector<char> isSelected(1000, 0);\n    for (int i = 0; i < 50; ++i) {\n        selected.push_back(cand[i].idx);\n        isSelected[cand[i].idx] = 1;\n    }\n\n    /* ---------- 2. greedy nearest\u2011neighbour (respecting precedence) ---------- */\n    vector<char> takenPickup(1000, 0);\n    vector<char> takenDelivery(1000, 0);\n    vector<Node> path;          // 100 points (pickup / delivery)\n    int curx = office.first, cury = office.second;\n\n    for (int step = 0; step < 100; ++step) {\n        int bestDist = INT_MAX;\n        int bestIdx  = -1;\n        bool bestIsPickup = true;\n\n        for (int id : selected) {\n            if (!takenPickup[id]) {\n                int d = manhattan(curx, cury, orders[id].a, orders[id].b);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx  = id;\n                    bestIsPickup = true;\n                }\n            } else if (!takenDelivery[id]) {\n                int d = manhattan(curx, cury, orders[id].c, orders[id].d);\n                if (d < bestDist) {\n                    bestDist = d;\n                    bestIdx  = id;\n                    bestIsPickup = false;\n                }\n            }\n        }\n\n        if (bestIsPickup) {\n            path.push_back({bestIdx, true});\n            takenPickup[bestIdx] = 1;\n            curx = orders[bestIdx].a;\n            cury = orders[bestIdx].b;\n        } else {\n            path.push_back({bestIdx, false});\n            takenDelivery[bestIdx] = 1;\n            curx = orders[bestIdx].c;\n            cury = orders[bestIdx].d;\n        }\n    }\n\n    /* ---------- helper: length of the whole tour ---------- */\n    auto tourLength = [&](const vector<Node>& seq)->long long {\n        long long tot = 0;\n        int x = office.first, y = office.second;\n        for (const auto &nd : seq) {\n            const Order &o = orders[nd.id];\n            if (nd.pickup) {\n                tot += manhattan(x, y, o.a, o.b);\n                x = o.a; y = o.b;\n            } else {\n                tot += manhattan(x, y, o.c, o.d);\n                x = o.c; y = o.d;\n            }\n        }\n        tot += manhattan(x, y, office.first, office.second);\n        return tot;\n    };\n\n    /* ---------- 3. 2\u2011opt local search (respect precedence) ---------- */\n    long long bestLen = tourLength(path);\n    mt19937 rng((unsigned)chrono::high_resolution_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> distPos(0, (int)path.size() - 1);\n    const double TIME_LIMIT = 1.8;                     // seconds\n    auto start = chrono::steady_clock::now();\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        int i = distPos(rng);\n        int j = distPos(rng);\n        if (i == j) continue;\n        if (i > j) swap(i, j);\n\n        // reverse segment [i , j]\n        reverse(path.begin() + i, path.begin() + j + 1);\n\n        // precedence check\n        bool ok = true;\n        static int posPickup[1000];\n        static int posDelivery[1000];\n        fill(begin(posPickup), end(posPickup), -1);\n        fill(begin(posDelivery), end(posDelivery), -1);\n        for (int p = 0; p < (int)path.size(); ++p) {\n            const Node &nd = path[p];\n            if (nd.pickup) posPickup[nd.id] = p;\n            else          posDelivery[nd.id] = p;\n        }\n        for (int id : selected) {\n            if (posPickup[id] == -1 || posDelivery[id] == -1 ||\n                posPickup[id] > posDelivery[id]) {\n                ok = false; break;\n            }\n        }\n\n        if (ok) {\n            long long curLen = tourLength(path);\n            if (curLen < bestLen) {\n                bestLen = curLen;               // keep improvement\n                continue;\n            }\n        }\n        // revert the reversal\n        reverse(path.begin() + i, path.begin() + j + 1);\n    }\n\n    /* ---------- 4. output ---------- */\n    cout << 50;\n    for (int id : selected) cout << ' ' << (id + 1);   // 1\u2011based\n    cout << '\\n';\n\n    // build the full coordinate list (office \u2192 points \u2192 office)\n    cout << ( (int)path.size() + 2 );\n    cout << ' ' << office.first << ' ' << office.second;\n    for (const auto &nd : path) {\n        const Order &o = orders[nd.id];\n        if (nd.pickup) cout << ' ' << o.a << ' ' << o.b;\n        else          cout << ' ' << o.c << ' ' << o.d;\n    }\n    cout << ' ' << office.first << ' ' << office.second;\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) {\n        p.resize(n);\n        r.assign(n, 0);\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    // ---- read coordinates ----\n    vector<int> x(N), y(N);\n    for (int i = 0; i < N; ++i) cin >> x[i] >> y[i];\n\n    // ---- read edges ----\n    vector<int> u(M), v(M);\n    for (int i = 0; i < M; ++i) cin >> u[i] >> v[i];\n\n    // ---- compute rounded distances d_i ----\n    vector<long long> d(M);\n    for (int i = 0; i < M; ++i) {\n        long long dx = (long long)x[u[i]] - x[v[i]];\n        long long dy = (long long)y[u[i]] - y[v[i]];\n        double eu = sqrt((double)dx * dx + (double)dy * dy);\n        d[i] = llround(eu);\n    }\n\n    // ---- offline MST on d_i (Kruskal) ----\n    vector<int> idx(M);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(),\n         [&](int a, int b) { return d[a] < d[b]; });\n\n    vector<char> inMST(M, 0);\n    DSU dsu_off(N);\n    int added = 0;\n    for (int id : idx) {\n        if (dsu_off.unite(u[id], v[id])) {\n            inMST[id] = 1;\n            ++added;\n            if (added == N - 1) break;\n        }\n    }\n\n    // ---- online phase ----\n    DSU dsu(N);\n    int comp = N;                     // current number of components\n\n    for (int i = 0; i < M; ++i) {\n        long long li;\n        cin >> li;                    // true length (not used)\n\n        if (dsu.find(u[i]) == dsu.find(v[i])) {\n            cout << \"0\\n\";\n            cout.flush();\n            continue;\n        }\n\n        int rem  = M - i - 1;          // edges still unseen\n        int need = comp - 1;           // bridges still required\n\n        bool take = false;\n        if (rem == need)               // forced acceptance\n            take = true;\n        else if (inMST[i])             // promising edge from the lower\u2011bound MST\n            take = true;\n\n        if (take) {\n            cout << \"1\\n\";\n            dsu.unite(u[i], v[i]);\n            --comp;\n        } else {\n            cout << \"0\\n\";\n        }\n        cout.flush();\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos { int x, y; };\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<Pos> petPos(N);\n    vector<int> petType(N);\n    for (int i = 0; i < N; ++i) cin >> petPos[i].x >> petPos[i].y >> petType[i];\n\n    int M;\n    cin >> M;\n    vector<Pos> humanPos(M);\n    for (int i = 0; i < M; ++i) cin >> humanPos[i].x >> humanPos[i].y;\n\n    const int H = 30, W = 30;\n    // 0 = free, 1 = wall\n    vector<vector<int>> wall(H + 2, vector<int>(W + 2, 0));\n    // borders are treated as walls (impassable)\n    for (int i = 0; i <= H + 1; ++i) {\n        wall[i][0] = wall[i][W + 1] = 1;\n    }\n    for (int j = 0; j <= W + 1; ++j) {\n        wall[0][j] = wall[H + 1][j] = 1;\n    }\n\n    // helper to check inside board\n    auto inside = [&](int x, int y) {\n        return 1 <= x && x <= H && 1 <= y && y <= W;\n    };\n\n    // directions: U,D,L,R with corresponding delta\n    const string dirs = \"UDLR\";\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n\n    // for fast pet lookup on the grid\n    vector<vector<int>> petCnt(H + 2, vector<int>(W + 2, 0));\n    for (auto &p : petPos) petCnt[p.x][p.y]++;\n\n    for (int turn = 0; turn < 300; ++turn) {\n        string actions(M, '.');\n\n        // decide actions for each human\n        for (int i = 0; i < M; ++i) {\n            int hx = humanPos[i].x;\n            int hy = humanPos[i].y;\n            bool placed = false;\n            for (int d = 0; d < 4; ++d) {\n                int nx = hx + dx[d];\n                int ny = hy + dy[d];\n                if (!inside(nx, ny)) continue;\n                if (wall[nx][ny]) continue;            // already wall\n                if (petCnt[nx][ny] > 0) continue;      // pet stands there now\n                // check that none of the four neighbours of (nx,ny) contain a pet\n                bool adjPet = false;\n                for (int k = 0; k < 4; ++k) {\n                    int ax = nx + dx[k];\n                    int ay = ny + dy[k];\n                    if (!inside(ax, ay)) continue;\n                    if (petCnt[ax][ay] > 0) { adjPet = true; break; }\n                }\n                if (adjPet) continue;\n                // also cannot wall a cell that currently holds a human\n                bool otherHuman = false;\n                for (int j = 0; j < M; ++j) {\n                    if (j == i) continue;\n                    if (humanPos[j].x == nx && humanPos[j].y == ny) {\n                        otherHuman = true; break;\n                    }\n                }\n                if (otherHuman) continue;\n\n                // all checks passed \u2192 build wall\n                actions[i] = tolower(dirs[d]); // u/d/l/r\n                wall[nx][ny] = 1;\n                placed = true;\n                break;\n            }\n            // if no safe neighbour, action stays '.'\n            (void)placed;\n        }\n\n        // output actions\n        cout << actions << \"\\n\";\n        cout.flush();\n\n        // read pet movement strings and update positions\n        for (int i = 0; i < N; ++i) {\n            string moveStr;\n            cin >> moveStr;\n            // erase old count\n            petCnt[petPos[i].x][petPos[i].y]--;\n            // apply each step\n            for (char c : moveStr) {\n                if (c == '.') continue;\n                int md = -1;\n                if (c == 'U') md = 0;\n                else if (c == 'D') md = 1;\n                else if (c == 'L') md = 2;\n                else if (c == 'R') md = 3;\n                if (md != -1) {\n                    petPos[i].x += dx[md];\n                    petPos[i].y += dy[md];\n                }\n            }\n            // add new count\n            petCnt[petPos[i].x][petPos[i].y]++;\n        }\n    }\n    return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Prev {\n    int pi, pj;\n    char mv;                 // move taken from predecessor to this cell\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj, ti, tj;\n    double p;\n    if (!(cin >> si >> sj >> ti >> tj >> p)) return 0;\n\n    const int N = 20;\n    vector<string> h(N);          // 20 strings, length 19\n    for (int i = 0; i < N; ++i) cin >> h[i];\n    vector<string> v(N - 1);      // 19 strings, length 20\n    for (int i = 0; i < N - 1; ++i) cin >> v[i];\n\n    // ---------- BFS ----------\n    vector<vector<int>> dist(N, vector<int>(N, -1));\n    vector<vector<Prev>> pre(N, vector<Prev>(N, {-1, -1, '?'}));\n    queue<pair<int,int>> q;\n    dist[si][sj] = 0;\n    q.emplace(si, sj);\n\n    while (!q.empty()) {\n        auto [i, j] = q.front(); q.pop();\n        if (i == ti && j == tj) break;\n\n        // Up\n        if (i > 0 && v[i-1][j] == '0' && dist[i-1][j] == -1) {\n            dist[i-1][j] = dist[i][j] + 1;\n            pre[i-1][j] = {i, j, 'U'};\n            q.emplace(i-1, j);\n        }\n        // Down\n        if (i + 1 < N && v[i][j] == '0' && dist[i+1][j] == -1) {\n            dist[i+1][j] = dist[i][j] + 1;\n            pre[i+1][j] = {i, j, 'D'};\n            q.emplace(i+1, j);\n        }\n        // Left\n        if (j > 0 && h[i][j-1] == '0' && dist[i][j-1] == -1) {\n            dist[i][j-1] = dist[i][j] + 1;\n            pre[i][j-1] = {i, j, 'L'};\n            q.emplace(i, j-1);\n        }\n        // Right\n        if (j + 1 < N && h[i][j] == '0' && dist[i][j+1] == -1) {\n            dist[i][j+1] = dist[i][j] + 1;\n            pre[i][j+1] = {i, j, 'R'};\n            q.emplace(i, j+1);\n        }\n    }\n\n    // ---------- reconstruct shortest path ----------\n    string path;\n    int ci = ti, cj = tj;\n    while (!(ci == si && cj == sj)) {\n        Prev pr = pre[ci][cj];\n        path.push_back(pr.mv);\n        ci = pr.pi;\n        cj = pr.pj;\n    }\n    reverse(path.begin(), path.end());\n\n    if (path.empty()) {               // should never happen (start != target)\n        cout << \"U\\n\";\n        return 0;\n    }\n\n    // ---------- repeat to increase robustness ----------\n    const int MAXLEN = 200;\n    int repeat = MAXLEN / static_cast<int>(path.size());\n    string answer;\n    answer.reserve(repeat * path.size());\n\n    for (int i = 0; i < repeat; ++i) answer += path;\n\n    // optional: fill the remaining characters (not required)\n    int remaining = MAXLEN - static_cast<int>(answer.size());\n    if (remaining > 0) answer.append(path.substr(0, remaining));\n\n    cout << answer << '\\n';\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 30;\nconst int DIR = 4;\nconst int di[DIR] = {0, -1, 0, 1};\nconst int dj[DIR] = {-1, 0, 1, 0};\n\nint to0[8][DIR] = {\n    { 1, 0, -1, -1},\n    { 3,-1, -1,  0},\n    {-1,-1,  3,  2},\n    {-1, 2,  1, -1},\n    { 1, 0,  3,  2},\n    { 3, 2,  1,  0},\n    { 2,-1,  0, -1},\n    {-1, 3, -1,  1},\n};\n\nint to_rot[8][4][DIR];               // [type][rot][enter] -> leave or -1\n\nvoid build_rot() {\n    for (int t = 0; t < 8; ++t)\n        for (int r = 0; r < 4; ++r)\n            for (int d = 0; d < DIR; ++d) {\n                int d0 = (d - r + 4) % 4;\n                int nd = to0[t][d0];\n                to_rot[t][r][d] = (nd == -1) ? -1 : (nd + r) % 4;\n            }\n}\n\n/* --------------------------------------------------------------- */\n/*  Score = L1 * L2 (0 if < 2 loops)                               */\n/*  No dynamic allocation \u2013 uses static buffers for speed.          */\n/* --------------------------------------------------------------- */\nint board_score(const vector<string>& tile,\n                const int rot[N][N]) {\n    static bool seen[N][N][DIR];\n    memset(seen, 0, sizeof(seen));\n\n    static int loops[4000];\n    int loop_cnt = 0;\n\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            for (int d = 0; d < DIR; ++d) {\n                if (seen[i][j][d]) continue;\n                int t = tile[i][j] - '0';\n                int r = rot[i][j];\n                if (to_rot[t][r][d] == -1) continue;\n\n                int ci = i, cj = j, cd = d;\n                int len = 0;\n                bool broken = false;\n                while (true) {\n                    int ct = tile[ci][cj] - '0';\n                    int cr = rot[ci][cj];\n                    int nd = to_rot[ct][cr][cd];\n                    if (nd == -1) { broken = true; break; }\n                    int ni = ci + di[nd];\n                    int nj = cj + dj[nd];\n                    if (ni < 0 || ni >= N || nj < 0 || nj >= N) { broken = true; break; }\n                    int nd_next = (nd + 2) % 4;\n                    seen[ci][cj][cd] = true;\n                    ++len;\n                    ci = ni; cj = nj; cd = nd_next;\n                    if (ci == i && cj == j && cd == d) break;   // closed loop\n                }\n                if (!broken && len > 0) loops[loop_cnt++] = len;\n            }\n\n    if (loop_cnt < 2) return 0;\n    // find two largest lengths (simple linear scan, loop_cnt is tiny)\n    int max1 = 0, max2 = 0;\n    for (int k = 0; k < loop_cnt; ++k) {\n        int v = loops[k];\n        if (v > max1) { max2 = max1; max1 = v; }\n        else if (v > max2) max2 = v;\n    }\n    return max1 * max2;\n}\n\n/* --------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    build_rot();\n\n    vector<string> tile(N);\n    for (int i = 0; i < N; ++i) cin >> tile[i];\n\n    std::mt19937 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> rot_dist(0, 3);\n    uniform_int_distribution<int> cell_dist(0, N - 1);\n    uniform_real_distribution<double> prob01(0.0, 1.0);\n\n    static int cur[N][N];\n    static int best[N][N];\n    int bestScore = 0;\n\n    // ---- one random start -------------------------------------------------\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cur[i][j] = rot_dist(rng);\n\n    int curScore = board_score(tile, cur);\n    if (curScore > bestScore) {\n        bestScore = curScore;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                best[i][j] = cur[i][j];\n    }\n\n    // ---- simulated annealing ---------------------------------------------\n    const int MAX_ITER = 30000;                // fits comfortably in 2\u202fs\n    const double T0 = 4000.0, T1 = 0.2;          // exponential cooling\n\n    for (int it = 0; it < MAX_ITER; ++it) {\n        double progress = (double)it / MAX_ITER;\n        double temp = T0 * pow(T1 / T0, progress);   // decreasing temperature\n\n        int i = cell_dist(rng);\n        int j = cell_dist(rng);\n        int oldR = cur[i][j];\n        int newR = rot_dist(rng);\n        if (newR == oldR) continue;\n        cur[i][j] = newR;\n\n        int newScore = board_score(tile, cur);\n        bool accept = false;\n        if (newScore >= curScore) accept = true;\n        else {\n            double p = exp((newScore - curScore) / temp);\n            if (prob01(rng) < p) accept = true;\n        }\n\n        if (accept) {\n            curScore = newScore;\n            if (curScore > bestScore) {\n                bestScore = curScore;\n                for (int x = 0; x < N; ++x)\n                    for (int y = 0; y < N; ++y)\n                        best[x][y] = cur[x][y];\n            }\n        } else {\n            cur[i][j] = oldR;            // revert\n        }\n    }\n\n    // ---- output the best board found --------------------------------------\n    string out;\n    out.reserve(N * N);\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            out.push_back(char('0' + best[i][j]));\n    cout << out << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* --------------------------------------------------------------- */\n/* hex character \u2192 integer mask (0 \u2026 15)                             */\nstatic inline int hex2int(char c) {\n    if ('0' <= c && c <= '9') return c - '0';\n    return c - 'a' + 10;\n}\n\n/* --------------------------------------------------------------- */\n/* size of the largest tree in the current board                    */\nint largestTree(const vector<string>& board, int N) {\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n\n    vector<vector<int>> id(N, vector<int>(N, -1));\n    int V = 0;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (board[i][j] != '0')\n                id[i][j] = V++;\n\n    vector<vector<int>> adj(V);\n    auto addEdge = [&](int a, int b) {\n        adj[a].push_back(b);\n        adj[b].push_back(a);\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            int m = hex2int(board[i][j]);\n\n            // vertical (down / up)\n            if ((m & 8) && i + 1 < N && board[i + 1][j] != '0') {\n                int m2 = hex2int(board[i + 1][j]);\n                if (m2 & 2) addEdge(id[i][j], id[i + 1][j]);\n            }\n            // horizontal (right / left)\n            if ((m & 4) && j + 1 < N && board[i][j + 1] != '0') {\n                int m2 = hex2int(board[i][j + 1]);\n                if (m2 & 1) addEdge(id[i][j], id[i][j + 1]);\n            }\n        }\n    }\n\n    vector<char> seen(V, 0);\n    int best = 0;\n    for (int v = 0; v < V; ++v) if (!seen[v]) {\n        int verts = 0, edges2 = 0;\n        stack<int> st;\n        st.push(v);\n        seen[v] = 1;\n        while (!st.empty()) {\n            int cur = st.top(); st.pop();\n            ++verts;\n            edges2 += (int)adj[cur].size();\n            for (int nb : adj[cur])\n                if (!seen[nb]) {\n                    seen[nb] = 1;\n                    st.push(nb);\n                }\n        }\n        int edges = edges2 / 2;\n        if (edges == verts - 1)               // tree\n            best = max(best, verts);\n    }\n    return best;\n}\n\n/* --------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N; long long T;\n    if (!(cin >> N >> T)) return 0;\n    vector<string> original(N);\n    for (int i = 0; i < N; ++i) cin >> original[i];\n\n    /* locate empty cell in the initial board */\n    int origEx = -1, origEy = -1;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (original[i][j] == '0') { origEx = i; origEy = j; }\n\n    const char dirChar[4] = {'U', 'D', 'L', 'R'};\n    const int dx[4] = {-1, 1, 0, 0};\n    const int dy[4] = {0, 0, -1, 1};\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    string bestAns;\n    int    bestScore = -1;\n\n    const double TIME_LIMIT = 2.85;          // seconds\n    auto start = chrono::steady_clock::now();\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        /* ----- one depth\u20112 greedy walk ----- */\n        vector<string> board = original;\n        int ex = origEx, ey = origEy;\n        string curAns;\n        curAns.reserve(T);\n\n        for (long long step = 0; step < T; ++step) {\n            /* first\u2011move candidates */\n            vector<int> legal1;\n            for (int d = 0; d < 4; ++d) {\n                int nx = ex + dx[d];\n                int ny = ey + dy[d];\n                if (0 <= nx && nx < N && 0 <= ny && ny < N)\n                    legal1.push_back(d);\n            }\n\n            int bestFirstScore = -1;\n            vector<int> bestFirstMoves;\n\n            for (int d1 : legal1) {\n                int nx1 = ex + dx[d1];\n                int ny1 = ey + dy[d1];\n                swap(board[ex][ey], board[nx1][ny1]);          // simulate d1\n\n                /* second\u2011move candidates after d1 */\n                vector<int> legal2;\n                for (int d = 0; d < 4; ++d) {\n                    int nx = nx1 + dx[d];\n                    int ny = ny1 + dy[d];\n                    if (0 <= nx && nx < N && 0 <= ny && ny < N)\n                        legal2.push_back(d);\n                }\n\n                int bestSecondScore = -1;\n                if (legal2.empty()) {\n                    bestSecondScore = largestTree(board, N);\n                } else {\n                    for (int d2 : legal2) {\n                        int nx2 = nx1 + dx[d2];\n                        int ny2 = ny1 + dy[d2];\n                        swap(board[nx1][ny1], board[nx2][ny2]);   // simulate d2\n                        int s = largestTree(board, N);\n                        bestSecondScore = max(bestSecondScore, s);\n                        swap(board[nx1][ny1], board[nx2][ny2]);   // undo d2\n                    }\n                }\n\n                swap(board[ex][ey], board[nx1][ny1]);          // undo d1\n\n                if (bestSecondScore > bestFirstScore) {\n                    bestFirstScore = bestSecondScore;\n                    bestFirstMoves.clear();\n                    bestFirstMoves.push_back(d1);\n                } else if (bestSecondScore == bestFirstScore) {\n                    bestFirstMoves.push_back(d1);\n                }\n            }\n\n            // tie\u2011break uniformly at random\n            int chosen = bestFirstMoves[uniform_int_distribution<int>(0,\n                             (int)bestFirstMoves.size() - 1)(rng)];\n            int nx = ex + dx[chosen];\n            int ny = ey + dy[chosen];\n            swap(board[ex][ey], board[nx][ny]);                // perform move\n            ex = nx; ey = ny;\n            curAns.push_back(dirChar[chosen]);\n        }\n\n        int curScore = largestTree(board, N);\n        if (curScore > bestScore) {\n            bestScore = curScore;\n            bestAns   = curAns;\n        }\n    }\n\n    cout << bestAns << '\\n';\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing int64 = long long;\n\n/*---------------------------------------------------------------*/\n/*  Reduce (dx,dy) to a canonical primitive vector.\n    The first non\u2011zero component is forced positive.               */\nstatic pair<int64,int64> norm_dir(int64 dx, int64 dy){\n    int64 g = std::gcd(std::abs(dx), std::abs(dy));\n    dx /= g; dy /= g;\n    if (dx < 0 || (dx == 0 && dy < 0)){\n        dx = -dx; dy = -dy;\n    }\n    return {dx, dy};\n}\n\n/*---------------------------------------------------------------*/\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    long long N;                     // total strawberries (not used for logic)\n    int K;                           // always 100\n    if(!(cin >> N >> K)) return 0;\n    for(int i=0;i<10;i++){ long long a; cin >> a; }\n    vector<pair<int64,int64>> st(N);\n    for(long long i=0;i<N;i++){\n        cin >> st[i].first >> st[i].second;\n    }\n\n    const int MAX_CUTS = 100;\n    const int64 LIM   = 1'000'000'000LL;   // allowed coordinate range\n    const int64 R    = 10'000LL;           // cake radius\n    const int64 R2   = R * R;\n    const int64 SCALE = 20'000LL;          // length for the second point\n    \n    /*---------- 1) enumerate primitive directions ----------------*/\n    const int BOUND = 1500;                // |dx|,|dy| \u2264 BOUND\n    vector<pair<int64,int64>> cand;\n    for(int dx=-BOUND; dx<=BOUND; ++dx){\n        for(int dy=-BOUND; dy<=BOUND; ++dy){\n            if(dx==0 && dy==0) continue;\n            if(std::gcd(std::abs(dx), std::abs(dy)) != 1) continue; // primitive only\n            cand.emplace_back(dx, dy);\n        }\n    }\n    // sort by polar angle\n    vector<double> ang(cand.size());\n    for(size_t i=0;i<cand.size();++i)\n        ang[i] = atan2((double)cand[i].second, (double)cand[i].first);\n    vector<size_t> order(cand.size());\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](size_t a, size_t b){ return ang[a] < ang[b]; });\n\n    /*---------- 2) pick 100 directions uniformly spaced ----------*/\n    vector<pair<int64,int64>> dirs;\n    dirs.reserve(MAX_CUTS);\n    size_t total = order.size();\n    size_t step = total / MAX_CUTS;\n    if(step==0) step = 1;\n    for(size_t i=0;i<MAX_CUTS;i++){\n        size_t pos = i * step;\n        if(pos >= total) pos = total-1;\n        dirs.push_back(cand[order[pos]]);\n    }\n\n    /*---------- 3) generate lines, avoiding strawberries ---------*/\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int64> dist_inside(-R, R);   // interior point\n    \n    vector<array<int64,4>> lines;\n    lines.reserve(MAX_CUTS);\n    \n    for(const auto& d : dirs){\n        int64 dx = d.first;\n        int64 dy = d.second;\n        int64 px, py;\n        bool ok = false;\n        while(!ok){\n            // pick interior point\n            do{\n                px = dist_inside(rng);\n                py = dist_inside(rng);\n            }while(px*px + py*py >= R2);\n            \n            // test whether any strawberry lies on the infinite line\n            ok = true;\n            for(const auto& s : st){\n                int64 sx = s.first, sy = s.second;\n                // cross product (dx,dy) x (sx-px, sy-py)\n                int64 cross = dx * (sy - py) - dy * (sx - px);\n                if(cross == 0){          // collinear -> unlucky line\n                    ok = false;\n                    break;\n                }\n            }\n        }\n        // second point far away along the direction\n        int64 qx = px + dx * SCALE;\n        int64 qy = py + dy * SCALE;\n        qx = max(min(qx, LIM), -LIM);\n        qy = max(min(qy, LIM), -LIM);\n        lines.push_back({px, py, qx, qy});\n    }\n    \n    /*---------- 4) output ----------------------------------------*/\n    cout << lines.size() << '\\n';\n    for(const auto &ln : lines){\n        cout << ln[0] << ' ' << ln[1] << ' '\n             << ln[2] << ' ' << ln[3] << '\\n';\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Op {\n    int x1, y1, x2, y2, x3, y3, x4, y4;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    if (!(cin >> N >> M)) return 0;\n\n    /* ---------- dot existence ---------- */\n    vector<vector<char>> has(N, vector<char>(N, 0));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        has[x][y] = 1;\n    }\n\n    /* ---------- used unit edges ---------- */\n    vector<vector<char>> hori(N - 1, vector<char>(N, 0));   // (x,y)-(x+1,y)\n    vector<vector<char>> vert(N, vector<char>(N - 1, 0));   // (x,y)-(x,y+1)\n    vector<vector<char>> diagPos(N - 1, vector<char>(N - 1, 0)); // (x,y)-(x+1,y+1)\n    vector<vector<char>> diagNeg(N - 1, vector<char>(N - 1, 0)); // (x,y+1)-(x+1,y)\n\n    vector<Op> ops;\n\n    /* -------------------------------------------------\n       Helper: add a unit square (size 1x1)\n       ------------------------------------------------- */\n    auto add_unit_square = [&](int x, int y, int miss) -> bool {\n        const int cx[4] = {x, x + 1, x + 1, x};\n        const int cy[4] = {y, y,     y + 1, y + 1};\n\n        // three corners must already have dots\n        for (int k = 0; k < 4; ++k)\n            if (k != miss && !has[cx[k]][cy[k]]) return false;\n\n        // four unit edges must be free\n        for (int xx = cx[0]; xx < cx[1]; ++xx)\n            if (hori[xx][cy[0]]) return false;\n        for (int yy = cy[1]; yy < cy[2]; ++yy)\n            if (vert[cx[1]][yy]) return false;\n        for (int xx = cx[2]; xx > cx[3]; --xx)\n            if (hori[xx - 1][cy[2]]) return false;\n        for (int yy = cy[3]; yy > cy[0]; --yy)\n            if (vert[cx[3]][yy - 1]) return false;\n\n        // place missing dot\n        int mx = cx[miss], my = cy[miss];\n        has[mx][my] = 1;\n\n        // mark edges\n        for (int xx = cx[0]; xx < cx[1]; ++xx) hori[xx][cy[0]] = 1;\n        for (int yy = cy[1]; yy < cy[2]; ++yy) vert[cx[1]][yy] = 1;\n        for (int xx = cx[2]; xx > cx[3]; --xx) hori[xx - 1][cy[2]] = 1;\n        for (int yy = cy[3]; yy > cy[0]; --yy) vert[cx[3]][yy - 1] = 1;\n\n        // output operation (missing first, then clockwise)\n        Op op;\n        op.x1 = mx; op.y1 = my;\n        int idx = 0;\n        for (int k = 1; k <= 3; ++k) {\n            int cur = (miss + k) % 4;\n            if (idx == 0) { op.x2 = cx[cur]; op.y2 = cy[cur]; }\n            else if (idx == 1) { op.x3 = cx[cur]; op.y3 = cy[cur]; }\n            else { op.x4 = cx[cur]; op.y4 = cy[cur]; }\n            ++idx;\n        }\n        ops.push_back(op);\n        return true;\n    };\n\n    /* -------------------------------------------------\n       Helper: try a large axis\u2011parallel rectangle\n       ------------------------------------------------- */\n    auto try_large_rectangle = [&](int x, int y) -> bool {\n        // order opposite corners by distance (large rectangle first)\n        vector<int> xs(N), ys(N);\n        iota(xs.begin(), xs.end(), 0);\n        iota(ys.begin(), ys.end(), 0);\n        sort(xs.begin(), xs.end(),\n             [&](int a, int b){ return abs(a - x) > abs(b - x); });\n        sort(ys.begin(), ys.end(),\n             [&](int a, int b){ return abs(a - y) > abs(b - y); });\n\n        for (int x2 : xs) if (x2 != x) {\n            for (int y2 : ys) if (y2 != y) {\n                if (!has[x2][y] || !has[x][y2] || !has[x2][y2]) continue;\n\n                int lx = min(x, x2), rx = max(x, x2);\n                int ly = min(y, y2), ry = max(y, y2);\n\n                // edges must be free\n                bool ok = true;\n                for (int xx = lx; ok && xx < rx; ++xx)\n                    if (hori[xx][ly]) ok = false;\n                for (int yy = ly; ok && yy < ry; ++yy)\n                    if (vert[rx][yy]) ok = false;\n                for (int xx = lx; ok && xx < rx; ++xx)\n                    if (hori[xx][ry]) ok = false;\n                for (int yy = ly; ok && yy < ry; ++yy)\n                    if (vert[lx][yy]) ok = false;\n                if (!ok) continue;\n\n                // no extra dots on sides\n                for (int xx = lx + 1; ok && xx < rx; ++xx)\n                    if (has[xx][ly] || has[xx][ry]) ok = false;\n                for (int yy = ly + 1; ok && yy < ry; ++yy)\n                    if (has[lx][yy] || has[rx][yy]) ok = false;\n                if (!ok) continue;\n\n                // accept\n                has[x][y] = 1;\n                for (int xx = lx; xx < rx; ++xx) hori[xx][ly] = 1;\n                for (int yy = ly; yy < ry; ++yy) vert[rx][yy] = 1;\n                for (int xx = lx; xx < rx; ++xx) hori[xx][ry] = 1;\n                for (int yy = ly; yy < ry; ++yy) vert[lx][yy] = 1;\n\n                Op op;\n                op.x1 = x; op.y1 = y;\n                if (x == lx && y == ly) {               // missing LL\n                    op.x2 = rx; op.y2 = ly;\n                    op.x3 = rx; op.y3 = ry;\n                    op.x4 = lx; op.y4 = ry;\n                } else if (x == rx && y == ly) {        // missing LR\n                    op.x2 = rx; op.y2 = ry;\n                    op.x3 = lx; op.y3 = ry;\n                    op.x4 = lx; op.y4 = ly;\n                } else if (x == rx && y == ry) {        // missing UR\n                    op.x2 = lx; op.y2 = ry;\n                    op.x3 = lx; op.y3 = ly;\n                    op.x4 = rx; op.y4 = ly;\n                } else {                                // missing UL\n                    op.x2 = lx; op.y2 = ly;\n                    op.x3 = rx; op.y3 = ly;\n                    op.x4 = rx; op.y4 = ry;\n                }\n                ops.push_back(op);\n                return true;          // one rectangle added for this cell\n            }\n        }\n        return false;\n    };\n\n    /* -------------------------------------------------\n       Helper: try a 45\u00b0\u2011inclined square\n       ------------------------------------------------- */\n    auto try_diag_square = [&](int cx, int cy, int d) -> bool {\n        // vertices\n        int Lx = cx - d, Ly = cy;\n        int Bx = cx,     By = cy - d;\n        int Rx = cx + d, Ry = cy;\n        int Tx = cx,     Ty = cy + d;\n\n        // which vertex is missing?\n        bool present[4];\n        present[0] = has[Lx][Ly];\n        present[1] = has[Bx][By];\n        present[2] = has[Rx][Ry];\n        present[3] = has[Tx][Ty];\n        int cnt = 0, miss = -1;\n        for (int i = 0; i < 4; ++i) {\n            if (present[i]) ++cnt;\n            else miss = i;\n        }\n        if (cnt != 3) return false;   // need exactly three corners\n\n        // ---- edge\u2011freedom and interior\u2011dot checks ----\n        // L \u2192 B (diagNeg)\n        for (int i = 1; i < d; ++i) {\n            int ix = Lx + i, iy = Ly - i;\n            if (has[ix][iy]) return false;\n        }\n        for (int i = 0; i < d; ++i) {\n            int ex = Lx + i, ey = Ly - i - 1;   // edge (ex,ey+1)-(ex+1,ey)\n            if (diagNeg[ex][ey]) return false;\n        }\n\n        // B \u2192 R (diagPos)\n        for (int i = 1; i < d; ++i) {\n            int ix = Bx + i, iy = By + i;\n            if (has[ix][iy]) return false;\n        }\n        for (int i = 0; i < d; ++i) {\n            int ex = Bx + i, ey = By + i;\n            if (diagPos[ex][ey]) return false;\n        }\n\n        // R \u2192 T (diagNeg, opposite direction)\n        for (int i = 1; i < d; ++i) {\n            int ix = Rx - i, iy = Ry + i;\n            if (has[ix][iy]) return false;\n        }\n        for (int i = 0; i < d; ++i) {\n            int ex = Rx - i - 1, ey = Ry + i;   // edge (ex,ey)-(ex+1,ey+1)\n            if (diagNeg[ex][ey]) return false;\n        }\n\n        // T \u2192 L (diagPos, opposite direction)\n        for (int i = 1; i < d; ++i) {\n            int ix = Tx - i, iy = Ty - i;\n            if (has[ix][iy]) return false;\n        }\n        for (int i = 0; i < d; ++i) {\n            int ex = Tx - i - 1, ey = Ty - i - 1;\n            if (diagPos[ex][ey]) return false;\n        }\n\n        // all checks passed \u2192 place the missing dot\n        int mx, my;\n        if (miss == 0) { mx = Lx; my = Ly; }\n        else if (miss == 1) { mx = Bx; my = By; }\n        else if (miss == 2) { mx = Rx; my = Ry; }\n        else { mx = Tx; my = Ty; }\n        has[mx][my] = 1;\n\n        // mark diagonal edges\n        for (int i = 0; i < d; ++i) {\n            diagNeg[Lx + i][Ly - i - 1] = 1;          // L\u2192B\n            diagPos[Bx + i][By + i] = 1;            // B\u2192R\n            diagNeg[Rx - i - 1][Ry + i] = 1;          // R\u2192T\n            diagPos[Tx - i - 1][Ty - i - 1] = 1;      // T\u2192L\n        }\n\n        // output operation \u2013 clockwise L\u2192B\u2192R\u2192T, starting with missing corner\n        Op op;\n        if (miss == 0) {               // missing L\n            op.x1 = mx; op.y1 = my;\n            op.x2 = Bx; op.y2 = By;\n            op.x3 = Rx; op.y3 = Ry;\n            op.x4 = Tx; op.y4 = Ty;\n        } else if (miss == 1) {        // missing B\n            op.x1 = mx; op.y1 = my;\n            op.x2 = Rx; op.y2 = Ry;\n            op.x3 = Tx; op.y3 = Ty;\n            op.x4 = Lx; op.y4 = Ly;\n        } else if (miss == 2) {        // missing R\n            op.x1 = mx; op.y1 = my;\n            op.x2 = Tx; op.y2 = Ty;\n            op.x3 = Lx; op.y3 = Ly;\n            op.x4 = Bx; op.y4 = By;\n        } else {                       // missing T\n            op.x1 = mx; op.y1 = my;\n            op.x2 = Lx; op.y2 = Ly;\n            op.x3 = Bx; op.y3 = By;\n            op.x4 = Rx; op.y4 = Ry;\n        }\n        ops.push_back(op);\n        return true;\n    };\n\n    /* -------------------------------------------------\n       Main iterative loop\n       ------------------------------------------------- */\n    bool any_change = true;\n    while (any_change) {\n        any_change = false;\n\n        /* ---- Phase 1 : large axis\u2011parallel rectangles ---- */\n        // collect empty cells, farthest from centre first\n        vector<pair<int,int>> empties;\n        for (int x = 0; x < N; ++x)\n            for (int y = 0; y < N; ++y)\n                if (!has[x][y]) empties.emplace_back(x, y);\n\n        const int c = (N - 1) / 2;\n        sort(empties.begin(), empties.end(),\n             [&](auto a, auto b) {\n                 long da = 1LL*(a.first - c)*(a.first - c) +\n                           1LL*(a.second - c)*(a.second - c);\n                 long db = 1LL*(b.first - c)*(b.first - c) +\n                           1LL*(b.second - c)*(b.second - c);\n                 return da > db;\n             });\n\n        for (auto [x, y] : empties) {\n            if (has[x][y]) continue;               // may have been filled already\n            if (try_large_rectangle(x, y)) any_change = true;\n        }\n\n        /* ---- Phase 2 : unit squares, colour 0 (parity) ---- */\n        bool changed = true;\n        while (changed) {\n            changed = false;\n            for (int x = 0; x + 1 < N; ++x) {\n                for (int y = 0; y + 1 < N; ++y) {\n                    if ((x + y) & 1) continue;      // parity filter\n                    const int cx[4] = {x, x + 1, x + 1, x};\n                    const int cy[4] = {y, y,     y + 1, y + 1};\n                    int cnt = 0, miss = -1;\n                    for (int k = 0; k < 4; ++k) {\n                        if (has[cx[k]][cy[k]]) ++cnt;\n                        else miss = k;\n                    }\n                    if (cnt == 3 && add_unit_square(x, y, miss))\n                        changed = true;\n                }\n            }\n        }\n\n        /* ---- Phase 3 : second pass \u2013 unit squares of any colour ---- */\n        changed = true;\n        while (changed) {\n            changed = false;\n            for (int x = 0; x + 1 < N; ++x) {\n                for (int y = 0; y + 1 < N; ++y) {\n                    const int cx[4] = {x, x + 1, x + 1, x};\n                    const int cy[4] = {y, y,     y + 1, y + 1};\n                    int cnt = 0, miss = -1;\n                    for (int k = 0; k < 4; ++k) {\n                        if (has[cx[k]][cy[k]]) ++cnt;\n                        else miss = k;\n                    }\n                    if (cnt == 3 && add_unit_square(x, y, miss))\n                        changed = true;\n                }\n            }\n        }\n\n        /* ---- Phase 4 : 45\u00b0 squares (large radius first) ---- */\n        for (int cx = 0; cx < N; ++cx) {\n            for (int cy = 0; cy < N; ++cy) {\n                int maxd = min({cx, cy, N - 1 - cx, N - 1 - cy});\n                for (int d = maxd; d >= 1; --d) {\n                    if (try_diag_square(cx, cy, d)) any_change = true;\n                }\n            }\n        }\n    }\n\n    /* -------------------------------------------------\n       Output\n       ------------------------------------------------- */\n    cout << ops.size() << '\\n';\n    for (const auto &op : ops) {\n        cout << op.x1 << ' ' << op.y1 << ' '\n             << op.x2 << ' ' << op.y2 << ' '\n             << op.x3 << ' ' << op.y3 << ' '\n             << op.x4 << ' ' << op.y4 << '\\n';\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 10;\nusing Board = array<array<int, N>, N>;\n\nstruct Pos { int r, c; };\n\n/* slide all candies toward dir:\n   0 = up, 1 = down, 2 = left, 3 = right */\nBoard tilt(const Board &src, int dir) {\n    Board dst = src;\n    if (dir == 0) {                     // up\n        for (int c = 0; c < N; ++c) {\n            int w = 0;\n            for (int r = 0; r < N; ++r) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[w][c] = v;\n                ++w;\n            }\n        }\n    } else if (dir == 1) {              // down\n        for (int c = 0; c < N; ++c) {\n            int w = N - 1;\n            for (int r = N - 1; r >= 0; --r) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[w][c] = v;\n                --w;\n            }\n        }\n    } else if (dir == 2) {              // left\n        for (int r = 0; r < N; ++r) {\n            int w = 0;\n            for (int c = 0; c < N; ++c) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[r][w] = v;\n                ++w;\n            }\n        }\n    } else {                            // right\n        for (int r = 0; r < N; ++r) {\n            int w = N - 1;\n            for (int c = N - 1; c >= 0; --c) if (dst[r][c]) {\n                int v = dst[r][c];\n                dst[r][c] = 0;\n                dst[r][w] = v;\n                --w;\n            }\n        }\n    }\n    return dst;\n}\n\n/* place flavour into the p\u2011th empty cell (p is 1\u2011based) */\nvoid place(Board &b, int p, int flavour) {\n    int cnt = 0;\n    for (int r = 0; r < N; ++r)\n        for (int c = 0; c < N; ++c)\n            if (b[r][c] == 0) {\n                ++cnt;\n                if (cnt == p) {\n                    b[r][c] = flavour;\n                    return;\n                }\n            }\n}\n\n/* BFS -> component ids, sizes, and count of equal\u2011flavour edges */\nvoid bfs(const Board &b,\n         array<array<int, N>, N> &compId,\n         vector<int> &compSize,\n         long long &adjEdges) {\n    for (auto &row : compId) row.fill(-1);\n    compSize.clear();\n    adjEdges = 0;\n\n    static const int dr[4] = {-1, 1, 0, 0};\n    static const int dc[4] = {0, 0, -1, 1};\n\n    int curId = 0;\n    for (int r = 0; r < N; ++r) for (int c = 0; c < N; ++c) {\n        if (b[r][c] == 0 || compId[r][c] != -1) continue;\n        int col = b[r][c];\n        queue<Pos> q;\n        q.push({r, c});\n        compId[r][c] = curId;\n        int sz = 0;\n        while (!q.empty()) {\n            Pos cur = q.front(); q.pop();\n            ++sz;\n            for (int d = 0; d < 4; ++d) {\n                int nr = cur.r + dr[d];\n                int nc = cur.c + dc[d];\n                if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue;\n                if (b[nr][nc] == col && compId[nr][nc] == -1) {\n                    compId[nr][nc] = curId;\n                    q.push({nr, nc});\n                }\n            }\n        }\n        compSize.push_back(sz);\n        ++curId;\n    }\n\n    // count equal\u2011flavour edges (right and down neighbours only)\n    for (int r = 0; r < N; ++r)\n        for (int c = 0; c < N; ++c) if (b[r][c]) {\n            if (c + 1 < N && b[r][c + 1] == b[r][c]) ++adjEdges;\n            if (r + 1 < N && b[r + 1][c] == b[r][c]) ++adjEdges;\n        }\n}\n\n/* \u03a3 size\u00b2 */\nlong long compScore(const vector<int> &sz) {\n    long long s = 0;\n    for (int x : sz) s += 1LL * x * x;\n    return s;\n}\n\n/* sum of Manhattan distances to board centre (4.5,4.5) */\ndouble compactness(const Board &b) {\n    double sum = 0.0;\n    for (int r = 0; r < N; ++r)\n        for (int c = 0; c < N; ++c)\n            if (b[r][c])\n                sum += fabs(r - 4.5) + fabs(c - 4.5);\n    return sum;\n}\n\n/* greedy direction used inside Monte\u2011Carlo simulations\n   (same one\u2011step greedy rule as before) */\nint greedyDirection(const Board &cur) {\n    const double lambda = 1.0;\n    double best = -1e300;\n    int bestDir = 0;\n    for (int d = 0; d < 4; ++d) {\n        Board nb = tilt(cur, d);\n        array<array<int, N>, N> cid;\n        vector<int> csz;\n        long long adj;\n        bfs(nb, cid, csz, adj);\n        double val = compScore(csz) + lambda * adj;\n        if (val > best) {\n            best = val;\n            bestDir = d;\n        }\n    }\n    return bestDir;\n}\n\n/* expected Q after the next random placement, using Monte\u2011Carlo */\ndouble expectedQMonteCarlo(const Board &base,\n                           const array<array<int, N>, N> &compId,\n                           const vector<int> &compSize,\n                           long long curComp,\n                           double lambda,\n                           const vector<int> &flavours,\n                           int step,\n                           int SAMPLES) {\n    // curComp already includes \u03a3 size\u00b2 of the current board\n    double sumFuture = 0.0;\n    for (int s = 0; s < SAMPLES; ++s) {\n        Board sim = base;\n        // simulate the rest of the game\n        for (int future = step + 1; future < 100; ++future) {\n            // random placement\n            int emptyCnt = 0;\n            for (int r = 0; r < N; ++r) for (int c = 0; c < N; ++c)\n                if (sim[r][c] == 0) ++emptyCnt;\n            static std::mt19937 rng((unsigned)chrono::steady_clock::now().time_since_epoch().count());\n            uniform_int_distribution<int> dist(1, emptyCnt);\n            int p = dist(rng);\n            place(sim, p, flavours[future]);\n\n            // greedy tilt for this simulated step\n            int nd = greedyDirection(sim);\n            sim = tilt(sim, nd);\n        }\n        // final component score\n        array<array<int, N>, N> cid2;\n        vector<int> sz2;\n        long long adj2;\n        bfs(sim, cid2, sz2, adj2);\n        sumFuture += compScore(sz2);\n    }\n    double avgFuture = sumFuture / SAMPLES;\n    // expected increase over current component score\n    return curComp + (avgFuture - curComp);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    vector<int> flavour(100);\n    for (int i = 0; i < 100; ++i) cin >> flavour[i];\n\n    Board board{};\n    const char dirChar[4] = {'F', 'B', 'L', 'R'};\n    const double lambda = 1.0;\n    const double mu = 0.5;          // weight of compactness penalty\n    const int SAMPLES = 6;          // Monte\u2011Carlo repetitions per direction\n\n    for (int step = 0; step < 100; ++step) {\n        int p;                      // position of the newly placed candy\n        cin >> p;\n        place(board, p, flavour[step]);\n\n        double bestVal = -1e300;\n        int bestDir = 0;\n\n        for (int d = 0; d < 4; ++d) {\n            Board nb = tilt(board, d);\n\n            // component data of nb\n            array<array<int, N>, N> cid;\n            vector<int> csz;\n            long long adj;\n            bfs(nb, cid, csz, adj);\n            long long curComp = compScore(csz);\n            double curQ = curComp + lambda * adj;\n\n            double expQ = curQ;\n            if (step < 99) {\n                expQ = expectedQMonteCarlo(nb, cid, csz, curComp,\n                                           lambda, flavour, step, SAMPLES);\n            }\n\n            double dist = compactness(nb);\n            double value = expQ - mu * dist;\n\n            if (value > bestVal) {\n                bestVal = value;\n                bestDir = d;\n            }\n        }\n\n        cout << dirChar[bestDir] << '\\n';\n        cout.flush();\n\n        board = tilt(board, bestDir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int M;\n    double eps;\n    if (!(cin >> M >> eps)) return 0;\n\n    const int N = 20;                         // fixed vertex count\n    const int L = N * (N - 1) / 2;            // length of each graph string\n\n    cout << N << \"\\n\";\n    for (int k = 0; k < M; ++k) {\n        string s(k, '1');                     // k ones\n        s.append(L - k, '0');                 // remaining zeros\n        cout << s << \"\\n\";\n    }\n    cout.flush();\n\n    for (int q = 0; q < 100; ++q) {\n        string H;\n        cin >> H;                             // length L\n        int cnt = 0;\n        for (char c : H) if (c == '1') ++cnt;\n\n        int t = min(cnt, M - 1);               // nearest index (0 \u2026 M\u20111)\n        cout << t << \"\\n\";\n        cout.flush();\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct AdjEdge {\n    int to;\n    int w;\n    int idx;          // original edge index\n};\n\nstruct DayInfo {\n    double sum;       // total importance already assigned\n    int id;           // 1\u2011based day number\n    bool operator<(DayInfo const& o) const {\n        // reverse for min\u2011heap\n        if (sum != o.sum) return sum > o.sum;\n        return id > o.id;\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    if (!(cin >> N >> M >> D >> K)) return 0;\n\n    vector<int> U(M), V(M), W(M);\n    for (int i = 0; i < M; ++i) {\n        cin >> U[i] >> V[i] >> W[i];\n        --U[i]; --V[i];\n    }\n\n    // coordinates are irrelevant for the schedule\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n    }\n\n    /* ---------- adjacency list ---------- */\n    vector<vector<AdjEdge>> g(N);\n    for (int i = 0; i < M; ++i) {\n        g[U[i]].push_back({V[i], W[i], i});\n        g[V[i]].push_back({U[i], W[i], i});\n    }\n\n    /* ---------- compute exact edge importance ----------\n       importance[e] = total number of all\u2011pairs shortest\u2011paths that use e   */\n    vector<double> importance(M, 0.0);\n    const long long INF = (1LL << 60);\n\n    // containers reused for each source\n    vector<long long> dist(N);\n    vector<double> cnt(N);\n    using PQNode = pair<long long,int>;\n\n    for (int s = 0; s < N; ++s) {\n        // Dijkstra from s\n        fill(dist.begin(), dist.end(), INF);\n        fill(cnt.begin(), cnt.end(), 0.0);\n        dist[s] = 0;\n        cnt[s] = 1.0;\n        priority_queue<PQNode, vector<PQNode>, greater<PQNode>> pq;\n        pq.emplace(0LL, s);\n\n        while (!pq.empty()) {\n            auto [d, v] = pq.top(); pq.pop();\n            if (d != dist[v]) continue;\n            for (const auto &e : g[v]) {\n                long long nd = d + e.w;\n                if (nd < dist[e.to]) {\n                    dist[e.to] = nd;\n                    cnt[e.to] = cnt[v];\n                    pq.emplace(nd, e.to);\n                } else if (nd == dist[e.to]) {\n                    cnt[e.to] += cnt[v];\n                }\n            }\n        }\n\n        // add contributions to edges\n        for (int i = 0; i < M; ++i) {\n            int a = U[i], b = V[i], w = W[i];\n            if (dist[a] + w == dist[b]) importance[i] += cnt[a];\n            if (dist[b] + w == dist[a]) importance[i] += cnt[b];\n        }\n    }\n\n    /* ---------- sort edges by decreasing importance ---------- */\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int x, int y) {\n             if (importance[x] != importance[y])\n                 return importance[x] > importance[y];\n             return W[x] > W[y];          // tie\u2011breaker\n         });\n\n    /* ---------- greedy balanced assignment ---------- */\n    vector<int> cntDay(D + 1, 0);\n    vector<double> sumDay(D + 1, 0.0);\n    priority_queue<DayInfo> heap;\n    for (int d = 1; d <= D; ++d) heap.push({0.0, d});\n\n    vector<int> answer(M, 1);\n    for (int idx : order) {\n        DayInfo cur = heap.top(); heap.pop();   // day with smallest sum\n        int d = cur.id;\n        answer[idx] = d;\n\n        ++cntDay[d];\n        sumDay[d] += importance[idx];\n        cur.sum = sumDay[d];\n        if (cntDay[d] < K) heap.push(cur);     // keep day while capacity remains\n    }\n\n    /* ---------- output ---------- */\n    for (int i = 0; i < M; ++i) {\n        if (i) cout << ' ';\n        cout << answer[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pos { int x, y, z; };\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int D;\n    if (!(cin >> D)) return 0;\n\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) cin >> f[i][z];\n        for (int z = 0; z < D; ++z) cin >> r[i][z];\n    }\n\n    const long long SZ = 1LL * D * D * D;\n    auto idx = [&](int x, int y, int z) -> long long {\n        return 1LL * x * D * D + 1LL * y * D + z;\n    };\n\n    /* -------------------------------------------------------------\n       masks: in1, in2, U, A, B\n       ------------------------------------------------------------- */\n    vector<char> in1(SZ, 0), in2(SZ, 0);\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 a = (f[0][z][x] == '1' && r[0][z][y] == '1');\n                bool b = (f[1][z][x] == '1' && r[1][z][y] == '1');\n                long long p = idx(x, y, z);\n                if (a) in1[p] = 1;\n                if (b) in2[p] = 1;\n            }\n\n    vector<char> maskU(SZ, 0), maskA(SZ, 0), maskB(SZ, 0);\n    for (long long p = 0; p < SZ; ++p) {\n        maskU[p] = (in1[p] && in2[p]);\n        maskA[p] = (in1[p] && !in2[p]);\n        maskB[p] = (in2[p] && !in1[p]);\n    }\n\n    const int dx[6] = {1,-1,0,0,0,0};\n    const int dy[6] = {0,0,1,-1,0,0};\n    const int dz[6] = {0,0,0,0,1,-1};\n\n    /* -------------------------------------------------------------\n       BFS that returns all components of a mask\n       ------------------------------------------------------------- */\n    auto bfs_components = [&](const vector<char>& mask) {\n        vector<char> visited(SZ, 0);\n        vector<vector<Pos>> comps;\n        queue<Pos> q;\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                    long long p = idx(x, y, z);\n                    if (!mask[p] || visited[p]) continue;\n                    comps.emplace_back();\n                    q = {};\n                    q.push({x, y, z});\n                    visited[p] = 1;\n                    while (!q.empty()) {\n                        Pos cur = q.front(); q.pop();\n                        comps.back().push_back(cur);\n                        for (int d = 0; d < 6; ++d) {\n                            int nx = cur.x + dx[d];\n                            int ny = cur.y + dy[d];\n                            int nz = cur.z + dz[d];\n                            if (nx < 0 || nx >= D || ny < 0 || ny >= D ||\n                                nz < 0 || nz >= D) continue;\n                            long long np = idx(nx, ny, nz);\n                            if (!mask[np] || visited[np]) continue;\n                            visited[np] = 1;\n                            q.push({nx, ny, nz});\n                        }\n                    }\n                }\n        return comps;\n    };\n\n    vector<vector<Pos>> compsU = bfs_components(maskU);\n    vector<vector<Pos>> compsA = bfs_components(maskA);\n    vector<vector<Pos>> compsB = bfs_components(maskB);\n\n    /* -------------------------------------------------------------\n       24 rotation matrices (determinant +1)\n       ------------------------------------------------------------- */\n    vector<array<array<int,3>,3>> rots;\n    vector<array<int,3>> perms = {{0,1,2},{0,2,1},{1,0,2},{1,2,0},{2,0,1},{2,1,0}};\n    for (auto p : perms) {\n        for (int sx : {1,-1})\n        for (int sy : {1,-1})\n        for (int sz : {1,-1}) {\n            if (sx*sy*sz != 1) continue;          // keep orientation\n            array<array<int,3>,3> m{};\n            m[0] = {0,0,0};\n            m[1] = {0,0,0};\n            m[2] = {0,0,0};\n            m[0][p[0]] = sx;\n            m[1][p[1]] = sy;\n            m[2][p[2]] = sz;\n            rots.push_back(m);\n        }\n    }\n    assert(rots.size() == 24);\n\n    /* -------------------------------------------------------------\n       canonical representation of a component (shape only)\n       ------------------------------------------------------------- */\n    auto canonical = [&](const vector<Pos>& cells) -> string {\n        string best;\n        bool first = true;\n        vector<Pos> tmp(cells.size());\n\n        for (const auto& R : rots) {\n            // rotate\n            for (size_t i = 0; i < cells.size(); ++i) {\n                const Pos& p = cells[i];\n                int nx = R[0][0]*p.x + R[0][1]*p.y + R[0][2]*p.z;\n                int ny = R[1][0]*p.x + R[1][1]*p.y + R[1][2]*p.z;\n                int nz = R[2][0]*p.x + R[2][1]*p.y + R[2][2]*p.z;\n                tmp[i] = {nx, ny, nz};\n            }\n            // translate to origin\n            int minx = INT_MAX, miny = INT_MAX, minz = INT_MAX;\n            for (auto &p : tmp) {\n                minx = min(minx, p.x);\n                miny = min(miny, p.y);\n                minz = min(minz, p.z);\n            }\n            for (auto &p : tmp) {\n                p.x -= minx; p.y -= miny; p.z -= minz;\n            }\n            sort(tmp.begin(), tmp.end(),\n                 [](const Pos& a, const Pos& b){\n                     if (a.x != b.x) return a.x < b.x;\n                     if (a.y != b.y) return a.y < b.y;\n                     return a.z < b.z;\n                 });\n            // serialize\n            string s;\n            s.reserve(tmp.size()*6);\n            for (auto &p : tmp) {\n                s += to_string(p.x); s += ',';\n                s += to_string(p.y); s += ',';\n                s += to_string(p.z); s += ';';\n            }\n            if (first || s < best) {\n                best = std::move(s);\n                first = false;\n            }\n        }\n        return best;\n    };\n\n    /* -------------------------------------------------------------\n       Build maps for A and B components by shape\n       ------------------------------------------------------------- */\n    unordered_map<string, vector<int>> mapA, mapB;\n    vector<string> shapeA(compsA.size()), shapeB(compsB.size());\n\n    for (int i = 0; i < (int)compsA.size(); ++i) {\n        shapeA[i] = canonical(compsA[i]);\n        mapA[shapeA[i]].push_back(i);\n    }\n    for (int i = 0; i < (int)compsB.size(); ++i) {\n        shapeB[i] = canonical(compsB[i]);\n        mapB[shapeB[i]].push_back(i);\n    }\n\n    vector<int> out1(SZ, 0), out2(SZ, 0);\n    long long curId = 0;\n\n    auto write_component = [&](const vector<Pos>& comp, bool to1, bool to2) {\n        ++curId;\n        for (const auto& p : comp) {\n            long long id = idx(p.x, p.y, p.z);\n            if (to1) out1[id] = (int)curId;\n            if (to2) out2[id] = (int)curId;\n        }\n    };\n\n    /* ------------ 4. match components of A and B by shape ------------ */\n    vector<char> usedA(compsA.size(), 0), usedB(compsB.size(), 0);\n    for (auto &kv : mapA) {\n        const string& key = kv.first;\n        auto itB = mapB.find(key);\n        if (itB == mapB.end()) continue;\n        vector<int>& vecA = kv.second;\n        vector<int>& vecB = itB->second;\n        int k = min((int)vecA.size(), (int)vecB.size());\n        for (int t = 0; t < k; ++t) {\n            int aIdx = vecA[t];\n            int bIdx = vecB[t];\n            usedA[aIdx] = usedB[bIdx] = 1;\n            ++curId;\n            for (const auto& p : compsA[aIdx]) out1[idx(p.x,p.y,p.z)] = (int)curId;\n            for (const auto& p : compsB[bIdx]) out2[idx(p.x,p.y,p.z)] = (int)curId;\n        }\n    }\n\n    /* ------------ 5. remaining exclusive components ------------------ */\n    for (int i = 0; i < (int)compsA.size(); ++i)\n        if (!usedA[i]) write_component(compsA[i], true, false);\n    for (int i = 0; i < (int)compsB.size(); ++i)\n        if (!usedB[i]) write_component(compsB[i], false, true);\n\n    /* ------------ 6. shared components U ----------------------------- */\n    for (const auto& comp : compsU) write_component(comp, true, true);\n\n    /* ------------------------ output -------------------------------- */\n    cout << curId << '\\n';\n    for (size_t i = 0; i < out1.size(); ++i) {\n        if (i) cout << ' ';\n        cout << out1[i];\n    }\n    cout << '\\n';\n    for (size_t i = 0; i < out2.size(); ++i) {\n        if (i) cout << ' ';\n        cout << out2[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*** Disjoint Set Union ***/\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n = 0) { init(n); }\n    void init(int n) { p.resize(n); r.assign(n, 0); iota(p.begin(), p.end(), 0); }\n    int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }\n    bool unite(int a, int b) {\n        a = find(a); b = find(b);\n        if (a == b) return false;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) ++r[a];\n        return true;\n    }\n};\n\n/*** evaluation result ***/\nstruct EvalResult {\n    long long powerCost;   // \u03a3 Pi\u00b2\n    long long mstWeight;   // metric MST weight\n    vector<int> power;     // Pi (0 if inactive)\n    vector<pair<int,int>> mstEdges;\n};\n\n/* evaluate a given active set */\nEvalResult evaluate(const vector<char>& active,\n                    const vector<vector<double>>& dRes,\n                    const vector<vector<long long>>& dist,\n                    const vector<vector<int>>& nxt) {\n    int N = (int)active.size() - 1;\n    int K = (int)dRes.size();\n\n    // assign residents to nearest active vertex\n    vector<int> assign(K, -1);\n    for (int r = 0; r < K; ++r) {\n        double best = 1e100;\n        int bestV = -1;\n        for (int v = 1; v <= N; ++v) if (active[v]) {\n            if (dRes[r][v] < best) {\n                best = dRes[r][v];\n                bestV = v;\n            }\n        }\n        assign[r] = bestV;\n    }\n\n    // compute powers\n    vector<int> power(N + 1, 0);\n    vector<double> maxDist(N + 1, -1.0);\n    for (int r = 0; r < K; ++r) {\n        int v = assign[r];\n        if (v == -1) continue;\n        if (dRes[r][v] > maxDist[v]) maxDist[v] = dRes[r][v];\n    }\n    long long powerCost = 0;\n    for (int v = 1; v <= N; ++v) {\n        if (!active[v]) { power[v] = 0; continue; }\n        if (maxDist[v] < 0) power[v] = 0;\n        else {\n            int p = (int)ceil(maxDist[v] - 1e-12);\n            if (p > 5000) p = 5000;\n            power[v] = p;\n        }\n        powerCost += 1LL * power[v] * power[v];\n    }\n\n    // metric complete graph on active nodes (including source)\n    vector<int> nodes;\n    for (int v = 1; v <= N; ++v) if (active[v]) nodes.push_back(v);\n    struct EdgeM { long long w; int u, v; };\n    vector<EdgeM> edgesM;\n    int sz = (int)nodes.size();\n    for (int i = 0; i < sz; ++i)\n        for (int j = i + 1; j < sz; ++j) {\n            int u = nodes[i], v = nodes[j];\n            edgesM.push_back({dist[u][v], u, v});\n        }\n    sort(edgesM.begin(), edgesM.end(),\n         [](const EdgeM& a, const EdgeM& b){ return a.w < b.w; });\n\n    DSU dsu(N + 1);\n    vector<pair<int,int>> mstEdges;\n    long long mstWeight = 0;\n    for (auto &e : edgesM) {\n        if (dsu.unite(e.u, e.v)) {\n            mstEdges.emplace_back(e.u, e.v);\n            mstWeight += e.w;\n            if ((int)mstEdges.size() == sz - 1) break;\n        }\n    }\n    return {powerCost, mstWeight, power, mstEdges};\n}\n\n/* ---------- main ---------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;\n\n    /* vertices */\n    vector<long long> xv(N + 1), yv(N + 1);\n    for (int i = 1; i <= N; ++i) cin >> xv[i] >> yv[i];\n\n    /* edges */\n    struct Edge {int u, v; long long w;};\n    vector<Edge> edges(M + 1);\n    const long long INF = (1LL << 60);\n    vector<vector<long long>> sp(N + 1, vector<long long>(N + 1, INF));\n    vector<vector<int>> nxt(N + 1, vector<int>(N + 1, -1));\n    map<pair<int,int>, int> idOfEdge;\n    for (int j = 1; j <= M; ++j) {\n        int u, v; long long w;\n        cin >> u >> v >> w;\n        edges[j] = {u, v, w};\n        if (w < sp[u][v]) {\n            sp[u][v] = sp[v][u] = w;\n            nxt[u][v] = v;\n            nxt[v][u] = u;\n        }\n        idOfEdge[{min(u, v), max(u, v)}] = j;\n    }\n    for (int i = 1; i <= N; ++i) {\n        sp[i][i] = 0;\n        nxt[i][i] = i;\n    }\n\n    /* Floyd\u2011Warshall */\n    for (int k = 1; k <= N; ++k)\n        for (int i = 1; i <= N; ++i) if (sp[i][k] != INF)\n            for (int j = 1; j <= N; ++j) if (sp[k][j] != INF) {\n                long long nd = sp[i][k] + sp[k][j];\n                if (nd < sp[i][j]) {\n                    sp[i][j] = nd;\n                    nxt[i][j] = nxt[i][k];\n                }\n            }\n\n    /* residents */\n    struct Resident { long long a, b; };\n    vector<Resident> residents(K);\n    for (int i = 0; i < K; ++i) cin >> residents[i].a >> residents[i].b;\n\n    /* distance resident \u2192 vertex */\n    vector<vector<double>> dRes(K, vector<double>(N + 1));\n    for (int r = 0; r < K; ++r) {\n        for (int v = 1; v <= N; ++v) {\n            long double dx = (long double)xv[v] - (long double)residents[r].a;\n            long double dy = (long double)yv[v] - (long double)residents[r].b;\n            dRes[r][v] = sqrt(dx*dx + dy*dy);\n        }\n    }\n\n    /* ---------- initial vertex reduction ---------- */\n    vector<char> active(N + 1, 1);\n    active[1] = 1;\n    vector<int> assign(K, -1);\n    vector<int> power(N + 1, 0);\n    bool changed = true;\n    while (changed) {\n        changed = false;\n        // assign residents\n        for (int r = 0; r < K; ++r) {\n            double best = 1e100;\n            int bestV = -1;\n            for (int v = 1; v <= N; ++v) if (active[v]) {\n                if (dRes[r][v] < best) {\n                    best = dRes[r][v];\n                    bestV = v;\n                }\n            }\n            assign[r] = bestV;\n        }\n        // compute powers\n        vector<double> maxDist(N + 1, -1.0);\n        for (int r = 0; r < K; ++r) {\n            int v = assign[r];\n            if (v == -1) continue;\n            if (dRes[r][v] > maxDist[v]) maxDist[v] = dRes[r][v];\n        }\n        for (int v = 1; v <= N; ++v) {\n            if (!active[v]) { power[v] = 0; continue; }\n            if (maxDist[v] < 0) power[v] = 0;\n            else {\n                int p = (int)ceil(maxDist[v] - 1e-12);\n                if (p > 5000) p = 5000;\n                power[v] = p;\n            }\n        }\n        // removable vertices\n        vector<char> removable(N + 1, 0);\n        for (int v = 2; v <= N; ++v) if (active[v]) {\n            bool canRemove = true;\n            bool hasResident = false;\n            for (int r = 0; r < K; ++r) if (assign[r] == v) {\n                hasResident = true;\n                bool covered = false;\n                for (int u = 1; u <= N; ++u)\n                    if (u != v && active[u] && power[u] > 0) {\n                        if (dRes[r][u] <= power[u] + 1e-9) {\n                            covered = true; break;\n                        }\n                    }\n                if (!covered) { canRemove = false; break; }\n            }\n            if (!hasResident) canRemove = true;\n            if (canRemove) removable[v] = 1;\n        }\n        for (int v = 2; v <= N; ++v) if (removable[v]) {\n            active[v] = 0;\n            changed = true;\n        }\n    }\n\n    /* ---------- global improvement using KMB estimate ---------- */\n    EvalResult cur = evaluate(active, dRes, sp, nxt);\n    long long curTour = 2 * cur.mstWeight;   // KMB upper bound\n\n    bool improved = true;\n    while (improved) {\n        improved = false;\n        for (int v = 2; v <= N; ++v) if (active[v]) {\n            vector<char> trialActive = active;\n            trialActive[v] = 0;\n            EvalResult trial = evaluate(trialActive, dRes, sp, nxt);\n            long long trialTour = 2 * trial.mstWeight;\n            if (trial.powerCost + trialTour < cur.powerCost + curTour) {\n                active = std::move(trialActive);\n                cur = trial;\n                curTour = trialTour;\n                improved = true;\n                break;   // restart after a successful deletion\n            }\n        }\n    }\n\n    /* ---------- final MST and activate original edges ---------- */\n    // cur already holds the metric MST of the final active set\n    vector<char> usedEdge(M + 1, 0);\n    auto addPath = [&](int s, int t) {\n        int curv = s;\n        while (curv != t) {\n            int nx = nxt[curv][t];\n            int a = min(curv, nx), b = max(curv, nx);\n            int idx = idOfEdge[{a, b}];\n            usedEdge[idx] = 1;\n            curv = nx;\n        }\n    };\n    for (auto [u, v] : cur.mstEdges) addPath(u, v);\n\n    /* ---------- output ---------- */\n    for (int i = 1; i <= N; ++i) {\n        if (i > 1) cout << ' ';\n        cout << cur.power[i];\n    }\n    cout << '\\n';\n    for (int j = 1; j <= M; ++j) {\n        if (j > 1) cout << ' ';\n        cout << (int)usedEdge[j];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Swap {\n    int x1, y1, x2, y2;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 30;\n    const int M = N * (N + 1) / 2;          // 465\n\n    // read the pyramid\n    vector<vector<int>> a(N);\n    for (int x = 0; x < N; ++x) {\n        a[x].resize(x + 1);\n        for (int y = 0; y <= x; ++y) {\n            cin >> a[x][y];\n        }\n    }\n\n    vector<Swap> ops;\n    ops.reserve(10000);\n\n    // bottom\u2011up heapify\n    for (int x = N - 2; x >= 0; --x) {\n        for (int y = 0; y <= x; ++y) {\n            int cx = x, cy = y;\n            while (cx + 1 < N) {\n                int leftX = cx + 1, leftY = cy;\n                int rightX = cx + 1, rightY = cy + 1;\n\n                // choose the smaller child\n                int childX, childY;\n                if (a[leftX][leftY] <= a[rightX][rightY]) {\n                    childX = leftX; childY = leftY;\n                } else {\n                    childX = rightX; childY = rightY;\n                }\n\n                if (a[childX][childY] < a[cx][cy]) {\n                    // perform the swap\n                    swap(a[cx][cy], a[childX][childY]);\n                    ops.push_back({cx, cy, childX, childY});\n                    if ((int)ops.size() >= 10000) break; // safety\n                    // continue from child's position\n                    cx = childX; cy = childY;\n                } else {\n                    break; // heap property satisfied at this node\n                }\n            }\n            if ((int)ops.size() >= 10000) break;\n        }\n        if ((int)ops.size() >= 10000) break;\n    }\n\n    // output\n    cout << ops.size() << '\\n';\n    for (auto &s : ops) {\n        cout << s.x1 << ' ' << s.y1 << ' '\n             << s.x2 << ' ' << s.y2 << '\\n';\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int D_input, N;\n    if (!(cin >> D_input >> N)) return 0;   // D = 9\n    const int D = D_input;\n    const int entrance_i = 0, entrance_j = (D - 1) / 2;\n    const int entrance_id = entrance_i * D + entrance_j;\n\n    vector<vector<int>> blocked(D, vector<int>(D, 0));\n    for (int k = 0; k < N; ++k) {\n        int ri, rj;\n        cin >> ri >> rj;\n        blocked[ri][rj] = 1;\n    }\n\n    auto inside = [&](int i, int j) {\n        return 0 <= i && i < D && 0 <= j && j < D;\n    };\n    const int di[4] = {-1, 1, 0, 0};\n    const int dj[4] = {0, 0, -1, 1};\n\n    const int V = D * D;\n    vector<vector<int>> adj(V);\n    for (int i = 0; i < D; ++i) {\n        for (int j = 0; j < D; ++j) {\n            if (blocked[i][j]) continue;\n            int v = i * D + j;\n            for (int d = 0; d < 4; ++d) {\n                int ni = i + di[d], nj = j + dj[d];\n                if (!inside(ni, nj)) continue;\n                if (blocked[ni][nj]) continue;\n                int nb = ni * D + nj;\n                adj[v].push_back(nb);\n            }\n        }\n    }\n\n    /* BFS distances from the entrance */\n    vector<int> dist(V, -1);\n    queue<int> q;\n    dist[entrance_id] = 0;\n    q.push(entrance_id);\n    while (!q.empty()) {\n        int v = q.front(); q.pop();\n        for (int nb : adj[v]) {\n            if (dist[nb] == -1) {\n                dist[nb] = dist[v] + 1;\n                q.push(nb);\n            }\n        }\n    }\n\n    /* list of all usable cells (except entrance) sorted by distance decreasing */\n    vector<int> orderDesc;\n    for (int v = 0; v < V; ++v) {\n        if (blocked[v / D][v % D]) continue;\n        if (v == entrance_id) continue;\n        orderDesc.push_back(v);\n    }\n    sort(orderDesc.begin(), orderDesc.end(),\n         [&](int a, int b) { return dist[a] > dist[b]; });\n\n    vector<int> container(V, -1);               // -1 = empty\n    const int M = D * D - 1 - N;                 // number of containers\n    size_t ptr = 0;                             // first still empty cell in orderDesc\n\n    for (int step = 0; step < M; ++step) {\n        int t;\n        cin >> t;                               // label of the arriving container\n\n        while (ptr < orderDesc.size() && container[orderDesc[ptr]] != -1) ++ptr;\n        int v = orderDesc[ptr];                 // farthest still empty cell\n        ++ptr;\n\n        cout << v / D << ' ' << v % D << '\\n' << flush;\n        container[v] = t;\n    }\n\n    /* ----- taking\u2011out order ----- */\n    int maxDist = 0;\n    for (int v = 0; v < V; ++v) {\n        if (blocked[v / D][v % D]) continue;\n        maxDist = max(maxDist, dist[v]);\n    }\n\n    for (int d = 1; d <= maxDist; ++d) {\n        vector<int> layer;\n        for (int v = 0; v < V; ++v) {\n            if (blocked[v / D][v % D]) continue;\n            if (dist[v] == d) layer.push_back(v);\n        }\n        sort(layer.begin(), layer.end(),\n             [&](int a, int b) { return container[a] < container[b]; });\n        for (int v : layer) {\n            cout << v / D << ' ' << v % D << '\\n';\n        }\n    }\n    cout << flush;\n    return 0;\n}","ahc024":"#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    if (!(cin >> n >> m)) return 0;\n    vector<vector<int>> a(n, vector<int>(n));\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < n; ++j)\n            cin >> a[i][j];\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if (j) cout << ' ';\n            cout << a[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, D, Q;\n    if (!(cin >> N >> D >> Q)) return 0;\n\n    // No need to read weights \u2013 they are unknown.\n    // -------------------------------------------------\n    // 1) Perform the required Q queries.\n    // -------------------------------------------------\n    for (int q = 0; q < Q; ++q) {\n        // left set = {0}, right set = {1} (both non\u2011empty, disjoint)\n        cout << \"1 1 0 1\\n\" << flush;   // flush after each query\n        string ans;\n        cin >> ans;                     // read the judge's reply and ignore it\n    }\n\n    // -------------------------------------------------\n    // 2) Output a trivial division (round\u2011robin).\n    // -------------------------------------------------\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << (i % D);\n    }\n    cout << '\\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    if (!(cin >> n >> m)) return 0;               // n = 200, m = 10\n    const int per = n / m;                         // 20\n    vector<vector<int>> st(m);                     // bottom -> top\n    for (int i = 0; i < m; ++i) {\n        st[i].reserve(per);\n        for (int j = 0; j < per; ++j) {\n            int x; cin >> x;\n            st[i].push_back(x);\n        }\n    }\n\n    const int INF = n + 1;\n    const int L = 3;                               // look\u2011ahead length\n\n    vector<pair<int,int>> ops;\n    ops.reserve(5000);\n\n    auto contains = [&](int idx, int val)->bool{\n        for (int x : st[idx]) if (x == val) return true;\n        return false;\n    };\n\n    for (int target = 1; target <= n; ++target) {\n        while (true) {\n            /* locate target */\n            int s = -1, pos = -1;\n            for (int i = 0; i < m; ++i) {\n                const auto &vec = st[i];\n                for (int j = 0; j < (int)vec.size(); ++j) {\n                    if (vec[j] == target) {\n                        s = i; pos = j;\n                        break;\n                    }\n                }\n                if (s != -1) break;\n            }\n\n            int topIdx = (int)st[s].size() - 1;\n            if (pos == topIdx) {                     // already on top\n                ops.emplace_back(target, 0);          // pop, no energy\n                st[s].pop_back();\n                break;                                // next target\n            }\n\n            /* block that hides target */\n            int start = pos + 1;\n            vector<int> block(st[s].begin() + start, st[s].end());\n            int maxBlock = *max_element(block.begin(), block.end());\n\n            /* upcoming targets */\n            vector<int> upcoming;\n            for (int d = 1; d <= L && target + d <= n; ++d)\n                upcoming.push_back(target + d);\n\n            auto containsUpcoming = [&](int idx)->bool{\n                for (int u : upcoming) if (contains(idx, u)) return true;\n                return false;\n            };\n\n            /* ---------- choose destination ---------- */\n            int dest = -1;\n            int bestTop   = INF;\n            int bestSize  = INT_MAX;\n            int bestIdx   = INT_MAX;\n\n            // 1) safe && does NOT contain any upcoming target\n            for (int i = 0; i < m; ++i) if (i != s) {\n                int topVal = st[i].empty() ? INF : st[i].back();\n                if (topVal > maxBlock && !containsUpcoming(i)) {\n                    if (topVal < bestTop ||\n                        (topVal == bestTop && (int)st[i].size() < bestSize) ||\n                        (topVal == bestTop && (int)st[i].size() == bestSize && i < bestIdx)) {\n                        bestTop = topVal;\n                        bestSize = (int)st[i].size();\n                        bestIdx = i;\n                        dest = i;\n                    }\n                }\n            }\n\n            // 2) safe (allow upcoming)\n            if (dest == -1) {\n                bestTop = INF; bestSize = INT_MAX; bestIdx = INT_MAX;\n                for (int i = 0; i < m; ++i) if (i != s) {\n                    int topVal = st[i].empty() ? INF : st[i].back();\n                    if (topVal > maxBlock) {\n                        if (topVal < bestTop ||\n                            (topVal == bestTop && (int)st[i].size() < bestSize) ||\n                            (topVal == bestTop && (int)st[i].size() == bestSize && i < bestIdx)) {\n                            bestTop = topVal;\n                            bestSize = (int)st[i].size();\n                            bestIdx = i;\n                            dest = i;\n                        }\n                    }\n                }\n            }\n\n            // 3) unsafe && does NOT contain upcoming (smallest height)\n            if (dest == -1) {\n                bestSize = INT_MAX; bestIdx = INT_MAX;\n                for (int i = 0; i < m; ++i) if (i != s) {\n                    if (!containsUpcoming(i)) {\n                        if ((int)st[i].size() < bestSize ||\n                            ((int)st[i].size() == bestSize && i < bestIdx)) {\n                            bestSize = (int)st[i].size();\n                            bestIdx = i;\n                            dest = i;\n                        }\n                    }\n                }\n            }\n\n            // 4) any stack (smallest height)\n            if (dest == -1) {\n                bestSize = INT_MAX; bestIdx = INT_MAX;\n                for (int i = 0; i < m; ++i) if (i != s) {\n                    if ((int)st[i].size() < bestSize ||\n                        ((int)st[i].size() == bestSize && i < bestIdx)) {\n                        bestSize = (int)st[i].size();\n                        bestIdx = i;\n                        dest = i;\n                    }\n                }\n            }\n\n            /* ---------- perform the move (type 1) ---------- */\n            int v = block.front();                     // bottom of block\n            ops.emplace_back(v, dest + 1);             // output operation\n\n            st[s].erase(st[s].begin() + start, st[s].end());\n            st[dest].insert(st[dest].end(), block.begin(), block.end());\n            // after the move target becomes top \u2192 loop again\n        }\n    }\n\n    for (auto [v, i] : ops) {\n        cout << v << ' ' << i << '\\n';\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    if (!(cin >> N)) return 0;\n\n    vector<string> h(N - 1);\n    for (int i = 0; i < N - 1; ++i) cin >> h[i];\n    vector<string> v(N);\n    for (int i = 0; i < N; ++i) cin >> v[i];\n\n    // d is read but not used\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            long long tmp;\n            cin >> tmp;\n        }\n    }\n\n    const int di[4] = {0, 1, 0, -1};\n    const int dj[4] = {1, 0, -1, 0};\n    const char moveChar[4] = {'R', 'D', 'L', 'U'};\n    const char backChar[4] = {'L', 'U', 'R', 'D'};\n\n    vector<vector<char>> visited(N, vector<char>(N, 0));\n    string answer;\n\n    function<void(int,int)> dfs = [&](int i, int j) {\n        visited[i][j] = 1;\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + di[dir];\n            int nj = j + dj[dir];\n            if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n            if (visited[ni][nj]) continue;\n            // check wall\n            bool blocked = false;\n            if (dir == 0) { // right\n                blocked = (v[i][j] == '1');\n            } else if (dir == 2) { // left\n                blocked = (v[i][j-1] == '1');\n            } else if (dir == 1) { // down\n                blocked = (h[i][j] == '1');\n            } else { // up\n                blocked = (h[i-1][j] == '1');\n            }\n            if (blocked) continue;\n\n            answer.push_back(moveChar[dir]);\n            dfs(ni, nj);\n            answer.push_back(backChar[dir]);\n        }\n    };\n\n    dfs(0, 0);\n    cout << answer << '\\n';\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing pii = pair<int,int>;\n\ninline int manhattan(const pii& a, const pii& b){\n    return abs(a.first - b.first) + abs(a.second - b.second);\n}\n\n/* ---------- optimal internal path of a 5\u2011letter word ---------- */\nstruct WordInfo{\n    vector<pii> path;   // 5 coordinates, minimal cost\n    pii start, finish;\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    if(!(cin >> N >> M)) return 0;          // N = 15, M = 200 (fixed)\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<string> board(N);\n    for(int i=0;i<N;i++) cin >> board[i];\n\n    /* 1. all positions of each letter */\n    vector<pii> pos[26];\n    for(int i=0;i<N;i++)\n        for(int j=0;j<N;j++)\n            pos[ board[i][j] - 'A' ].push_back({i,j});\n\n    /* 2. read words */\n    vector<string> words(M);\n    for(int i=0;i<M;i++) cin >> words[i];\n\n    /* 3. compute optimal internal path for each word */\n    vector<WordInfo> info(M);\n    for(int idx=0; idx<M; ++idx){\n        const string& w = words[idx];\n        array<vector<pii>*,5> lst;\n        for(int p=0;p<5;p++) lst[p] = &pos[w[p]-'A'];\n        int sz[5];\n        for(int p=0;p<5;p++) sz[p] = (int)lst[p]->size();\n\n        vector<vector<int>> dp(5);\n        vector<vector<int>> pre(5);\n        for(int i=0;i<5;i++){\n            dp[i].assign(sz[i], INT_MAX);\n            pre[i].assign(sz[i], -1);\n        }\n        for(int k=0;k<sz[0];++k) dp[0][k] = 1;      // press only\n\n        for(int i=1;i<5;i++){\n            for(int k=0;k<sz[i];++k){\n                int best = INT_MAX, bestPrev = -1;\n                for(int q=0;q<sz[i-1];++q){\n                    int cand = dp[i-1][q] + manhattan((*lst[i-1])[q], (*lst[i])[k]) + 1;\n                    if(cand < best){\n                        best = cand;\n                        bestPrev = q;\n                    }\n                }\n                dp[i][k] = best;\n                pre[i][k] = bestPrev;\n            }\n        }\n        int endIdx = 0;\n        for(int k=1;k<sz[4];++k)\n            if(dp[4][k] < dp[4][endIdx]) endIdx = k;\n\n        info[idx].path.resize(5);\n        int cur = endIdx;\n        for(int i=4;i>=0;--i){\n            info[idx].path[i] = (*lst[i])[cur];\n            cur = (i==0) ? -1 : pre[i][cur];\n        }\n        info[idx].start  = info[idx].path.front();\n        info[idx].finish = info[idx].path.back();\n    }\n\n    /* 4. greedy nearest\u2011neighbor order */\n    vector<int> order;\n    order.reserve(M);\n    vector<char> used(M,0);\n    pii curPos = {si, sj};\n\n    for(int taken=0; taken<M; ++taken){\n        int bestIdx = -1, bestDist = INT_MAX;\n        for(int i=0;i<M;i++) if(!used[i]){\n            int d = manhattan(curPos, info[i].start);\n            if(d < bestDist){\n                bestDist = d;\n                bestIdx = i;\n            }\n        }\n        used[bestIdx] = 1;\n        order.push_back(bestIdx);\n        curPos = info[bestIdx].finish;\n    }\n\n    /* helper to compute total distance of the whole order */\n    auto total_distance = [&](const vector<int>& ord)->long long{\n        long long sum = manhattan(pii{si,sj}, info[ord[0]].start);\n        for(int k=0;k+1<(int)ord.size();++k)\n            sum += manhattan(info[ord[k]].finish, info[ord[k+1]].start);\n        return sum;\n    };\n\n    long long total = total_distance(order);\n\n    /* 5. random\u2011pair 2\u2011opt improvement */\n    const int TRIALS = 50000;\n    mt19937 rng(1234567);\n    uniform_int_distribution<int> distIdx(0, M-2);\n\n    for(int t=0; t<TRIALS; ++t){\n        int i = distIdx(rng);\n        uniform_int_distribution<int> distJ(i+1, M-1);\n        int j = distJ(rng);\n        swap(order[i], order[j]);\n        long long newTot = total_distance(order);\n        if(newTot < total){\n            total = newTot;               // keep swap\n        }else{\n            swap(order[i], order[j]);    // revert\n        }\n    }\n\n    /* 6. output concatenated optimal paths */\n    for(int idx : order){\n        for(const pii& p : info[idx].path)\n            cout << p.first << ' ' << p.second << '\\n';\n    }\n    return 0;\n}","ahc030":"#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    double eps;\n    if (!(cin >> N >> M >> eps)) return 0;\n\n    // ---- read shapes (ignored later) ----\n    for (int k = 0; k < M; ++k) {\n        int d;\n        cin >> d;\n        for (int t = 0; t < d; ++t) {\n            int a, b;\n            cin >> a >> b;\n        }\n    }\n\n    // ---- read positions of each field (unused) ----\n    for (int k = 0; k < M; ++k) {\n        int di, dj;\n        cin >> di >> dj;\n        (void)di; (void)dj;\n    }\n\n    // ---- read the whole v matrix ----\n    vector<vector<int>> v(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> v[i][j];\n\n    // ---- discard the remaining numbers (up to 2*N^2) ----\n    // The exact amount is not needed; just read until EOF.\n    double dummy;\n    while (cin >> dummy) { /* discard */ }\n\n    // ---- collect cells with v > 0 ----\n    vector<pair<int,int>> ans;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (v[i][j] > 0) ans.emplace_back(i, j);\n\n    // ---- output in the required format ----\n    cout << \"a \" << ans.size();\n    for (auto [i, j] : ans) {\n        cout << ' ' << i << ' ' << j;\n    }\n    cout << \"\\n\";\n    cout.flush();\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    const int W = 1000;                 // hall size (fixed)\n    int W_in, D, N;\n    if (!(cin >> W_in >> D >> N)) return 0;   // W_in is always 1000\n\n    vector<vector<long long>> a(D, vector<long long>(N));\n    for (int d = 0; d < D; ++d)\n        for (int k = 0; k < N; ++k)\n            cin >> a[d][k];\n\n    for (int d = 0; d < D; ++d) {\n        // compute widths of full\u2011height strips\n        vector<int> width(N);\n        long long total_width = 0;\n        for (int k = 0; k < N; ++k) {\n            long long need = a[d][k];\n            int w = (int)((need + W - 1) / W);   // ceil(need / 1000)\n            if (w < 1) w = 1;\n            if (w > W) w = W;                    // safety, should not happen\n            width[k] = w;\n            total_width += w;\n        }\n\n        if (total_width <= W) {\n            // place the full\u2011height strips side by side\n            int cur = 0;\n            for (int k = 0; k < N; ++k) {\n                int i0 = 0;\n                int j0 = cur;\n                int i1 = W;           // full height\n                int j1 = cur + width[k];\n                cout << i0 << ' ' << j0 << ' '\n                     << i1 << ' ' << j1 << '\\n';\n                cur = j1;\n            }\n        } else {\n            // fallback: width\u20111 vertical strips\n            for (int k = 0; k < N; ++k) {\n                int i0 = k;\n                int j0 = 0;\n                int i1 = k + 1;\n                int j1 = W;\n                cout << i0 << ' ' << j0 << ' '\n                     << i1 << ' ' << j1 << '\\n';\n            }\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing int64 = long long;\nconst int64 MOD = 998244353LL;\n\nstruct Op {\n    int m, p, q;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    if (!(cin >> N >> M >> K)) return 0;          // N = 9, M = 20, K = 81\n\n    vector<vector<int64>> init(N, vector<int64>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> init[i][j];\n\n    // stamps[m][i][j]\n    vector<array<array<int64, 3>, 3>> stamp(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 >> stamp[m][i][j];\n\n    // ---------- Greedy construction ----------\n    vector<Op> best_ops;\n    best_ops.reserve(K);\n    vector<vector<int64>> board = init;   // current board\n\n    for (int step = 0; step < K; ++step) {\n        int best_m = -1, best_p = -1, best_q = -1;\n        int64 best_gain = 0;   // we only accept strictly positive gain\n\n        for (int m = 0; m < M; ++m) {\n            for (int p = 0; p <= N - 3; ++p) {\n                for (int q = 0; q <= N - 3; ++q) {\n                    int64 gain = 0;\n                    for (int i = 0; i < 3; ++i) {\n                        for (int j = 0; j < 3; ++j) {\n                            int64 oldv = board[p + i][q + j];\n                            int64 oldr = oldv % MOD;\n                            int64 newr = (oldv + stamp[m][i][j]) % MOD;\n                            gain += newr - oldr;\n                        }\n                    }\n                    if (gain > best_gain) {\n                        best_gain = gain;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n\n        if (best_gain <= 0) break;   // no improving press exists\n\n        // apply the chosen press\n        for (int i = 0; i < 3; ++i)\n            for (int j = 0; j < 3; ++j)\n                board[best_p + i][best_q + j] += stamp[best_m][i][j];\n\n        best_ops.push_back({best_m, best_p, best_q});\n    }\n\n    // ---------- Local\u2011search improvement ----------\n    // random generator\n    std::mt19937 rng(static_cast<unsigned>(chrono::steady_clock::now().time_since_epoch().count()));\n    uniform_int_distribution<int> dist_m(0, M - 1);\n    uniform_int_distribution<int> dist_pos(0, N - 3);\n    uniform_int_distribution<int> dist_bool(0, 1);\n    uniform_int_distribution<int> dist_idx;   // will be set later when needed\n\n    // helper to compute total score of a given operation list\n    auto compute_score = [&](const vector<Op>& ops) -> int64 {\n        vector<vector<int64>> cur = init;\n        for (const Op& op : ops) {\n            for (int i = 0; i < 3; ++i)\n                for (int j = 0; j < 3; ++j)\n                    cur[op.p + i][op.q + j] += stamp[op.m][i][j];\n        }\n        int64 sum = 0;\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                sum += cur[i][j] % MOD;\n        return sum;\n    };\n\n    int64 best_score = compute_score(best_ops);\n    const double TIME_LIMIT = 1.70;   // seconds\n    auto start_time = chrono::steady_clock::now();\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        vector<Op> cur_ops = best_ops;\n\n        if (!cur_ops.empty()) {\n            dist_idx = uniform_int_distribution<int>(0, (int)cur_ops.size() - 1);\n            int replace_idx = dist_idx(rng);\n            cur_ops[replace_idx] = {dist_m(rng), dist_pos(rng), dist_pos(rng)};\n        }\n\n        // occasionally try to add one more operation (if we still have quota)\n        if ((int)cur_ops.size() < K && dist_bool(rng) == 0) {\n            cur_ops.push_back({dist_m(rng), dist_pos(rng), dist_pos(rng)});\n        }\n\n        int64 cur_score = compute_score(cur_ops);\n        if (cur_score > best_score) {\n            best_score = cur_score;\n            best_ops.swap(cur_ops);\n        }\n    }\n\n    // ---------- Output ----------\n    cout << best_ops.size() << '\\n';\n    for (const Op& op : best_ops) {\n        cout << op.m << ' ' << op.p << ' ' << op.q << '\\n';\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cont {\n    int src;   // receiving gate row\n    int num;   // container number\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 5;\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    /* ----- small cranes: bomb immediately ----- */\n    vector<string> out(N);\n    for (int i = 1; i < N; ++i) out[i] = \"B\";\n\n    /* ----- collect containers per destination gate ----- */\n    vector<Cont> perDst[N];                 // per destination row\n    for (int src = 0; src < N; ++src) {\n        for (int j = 0; j < N; ++j) {\n            int num = A[src][j];\n            int dst = num / N;\n            perDst[dst].push_back({src, num});\n        }\n    }\n    /* sort each list by container number (ascending) */\n    for (int dst = 0; dst < N; ++dst)\n        sort(perDst[dst].begin(), perDst[dst].end(),\n             [](const Cont& a, const Cont& b){ return a.num < b.num; });\n\n    /* ----- build actions for the large crane (index 0) ----- */\n    string S;\n    int curRow = 0, curCol = 0;            // start at (0,0)\n\n    for (int dst = 0; dst < N; ++dst) {\n        for (const auto& con : perDst[dst]) {\n            int src = con.src;\n\n            // if we are on the right edge, go back left\n            if (curCol == 4) {\n                S.append(4, 'L');\n                curCol = 0;\n            }\n\n            // vertical move (empty) to source row\n            while (curRow < src) { S.push_back('D'); ++curRow; }\n            while (curRow > src) { S.push_back('U'); --curRow; }\n\n            S.push_back('P');               // pick\n\n            S.append(4, 'R');               // move to column 4\n            curCol = 4;\n\n            // vertical move (carrying) to destination row\n            while (curRow < dst) { S.push_back('D'); ++curRow; }\n            while (curRow > dst) { S.push_back('U'); --curRow; }\n\n            S.push_back('Q');               // drop (dispatch)\n            // now at (dst,4) and empty\n        }\n    }\n\n    out[0] = S;\n\n    /* ----- pad all strings to equal length ----- */\n    size_t maxLen = 0;\n    for (const auto& t : out) maxLen = max(maxLen, t.size());\n    for (auto& t : out) {\n        if (t.size() < maxLen) t.append(maxLen - t.size(), '.');\n        cout << t << '\\n';\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cell {\n    int r, c;\n    int amt;          // for positives: amount to load; for negatives: amount to receive\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N;\n    if (!(cin >> N)) return 0;\n    vector<vector<int>> h(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            cin >> h[i][j];\n    \n    vector<Cell> pos, neg;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            if (h[i][j] > 0) pos.push_back({i, j, h[i][j]});\n            else if (h[i][j] < 0) neg.push_back({i, j, -h[i][j]});\n        }\n    \n    int curR = 0, curC = 0;          // current truck position\n    long long load = 0;              // soil currently on the truck\n    \n    auto move_to = [&](int tr, int tc) {\n        while (curR < tr) { cout << \"D\\n\"; ++curR; }\n        while (curR > tr) { cout << \"U\\n\"; --curR; }\n        while (curC < tc) { cout << \"R\\n\"; ++curC; }\n        while (curC > tc) { cout << \"L\\n\"; --curC; }\n    };\n    \n    while (!pos.empty() || !neg.empty()) {\n        if (load == 0) {\n            // find nearest positive cell\n            int best = -1, bestDist = INT_MAX;\n            for (int i = 0; i < (int)pos.size(); ++i) {\n                int d = abs(pos[i].r - curR) + abs(pos[i].c - curC);\n                if (d < bestDist) {\n                    bestDist = d;\n                    best = i;\n                }\n            }\n            // move there and load\n            move_to(pos[best].r, pos[best].c);\n            load = pos[best].amt;\n            cout << \"+\" << load << \"\\n\";\n            // remove this cell\n            pos[best] = pos.back();\n            pos.pop_back();\n        } else {\n            // we have load, go to nearest negative cell\n            int best = -1, bestDist = INT_MAX;\n            for (int i = 0; i < (int)neg.size(); ++i) {\n                int d = abs(neg[i].r - curR) + abs(neg[i].c - curC);\n                if (d < bestDist) {\n                    bestDist = d;\n                    best = i;\n                }\n            }\n            // move there\n            move_to(neg[best].r, neg[best].c);\n            int need = neg[best].amt;\n            int d = (int)min<long long>(load, need);\n            cout << \"-\" << d << \"\\n\";\n            load -= d;\n            need -= d;\n            if (need == 0) {\n                // finished this negative cell\n                neg[best] = neg.back();\n                neg.pop_back();\n            } else {\n                neg[best].amt = need;   // still needs more soil\n            }\n        }\n    }\n    // At this point load == 0 and all heights are zero.\n    return 0;\n}","ahc035":"#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, T;\n    if (!(cin >> N >> M >> T)) return 0;          // N=6, M=15, T=10\n    const int S = 2 * N * (N - 1);                // 60 seeds\n    const int C = N * N;                          // 36 cells\n    const int EDGE_NUM = 2 * N * (N - 1);         // 60 edges\n\n    /* ---------- read the first set of seeds ---------- */\n    vector<vector<int>> seed(S, vector<int>(M));\n    for (int i = 0; i < S; ++i)\n        for (int j = 0; j < M; ++j)\n            cin >> seed[i][j];\n\n    auto cellId = [&](int r, int c) { return r * N + c; };\n\n    /* ---------- list of edges (undirected) ---------- */\n    vector<pair<int,int>> edges;\n    for (int r = 0; r < N; ++r) {\n        for (int c = 0; c < N; ++c) {\n            int u = cellId(r, c);\n            if (c + 1 < N) edges.emplace_back(u, cellId(r, c + 1));\n            if (r + 1 < N) edges.emplace_back(u, cellId(r + 1, c));\n        }\n    }\n    const int E = edges.size();   // = 60\n\n    /* ---------- main loop over turns ---------- */\n    for (int turn = 0; turn < T; ++turn) {\n        /* ---- 1) per\u2011dimension maxima X[l] ---- */\n        vector<int> X(M, 0);\n        for (int i = 0; i < S; ++i)\n            for (int l = 0; l < M; ++l)\n                X[l] = max(X[l], seed[i][l]);\n\n        /* ---- 2) best pair (a,b) w.r.t. edge potential ---- */\n        long long bestPot = -1;\n        int bestA = 0, bestB = 1;\n        for (int i = 0; i < S; ++i) {\n            for (int j = i + 1; j < S; ++j) {\n                long long pot = 0;\n                for (int l = 0; l < M; ++l)\n                    pot += max(seed[i][l], seed[j][l]);\n                if (pot > bestPot) {\n                    bestPot = pot;\n                    bestA = i;\n                    bestB = j;\n                }\n            }\n        }\n\n        /* ---- 3) normalised scores ---- */\n        vector<double> norm(S, 0.0);\n        for (int i = 0; i < S; ++i) {\n            double s = 0.0;\n            for (int l = 0; l < M; ++l)\n                if (X[l] > 0) s += static_cast<double>(seed[i][l]) / X[l];\n            norm[i] = s;\n        }\n\n        /* ---- 4) build a set of exactly 36 distinct seeds ---- */\n        vector<int> chosen;\n        vector<char> inSet(S, 0);\n\n        // keep the best pair\n        inSet[bestA] = inSet[bestB] = 1;\n        chosen.push_back(bestA);\n        chosen.push_back(bestB);\n\n        // one seed for each dimension\n        for (int l = 0; l < M; ++l) {\n            int best = 0;\n            for (int i = 1; i < S; ++i)\n                if (seed[i][l] > seed[best][l]) best = i;\n            if (!inSet[best]) {\n                inSet[best] = 1;\n                chosen.push_back(best);\n            }\n        }\n\n        // fill the rest with highest normalised scores\n        vector<int> order(S);\n        iota(order.begin(), order.end(), 0);\n        sort(order.begin(), order.end(),\n             [&](int a, int b) { return norm[a] > norm[b]; });\n\n        for (int idx : order) {\n            if ((int)chosen.size() >= C) break;\n            if (inSet[idx]) continue;\n            inSet[idx] = 1;\n            chosen.push_back(idx);\n        }\n\n        /* ---- 5) initial placement ---- */\n        vector<int> board(C, -1);          // cell -> seed id\n        board[cellId(0, 0)] = bestA;\n        board[cellId(0, 1)] = bestB;\n\n        // mark which chosen seeds are already placed\n        vector<char> used(S, 0);\n        used[bestA] = used[bestB] = 1;\n\n        int ptr = 0;\n        for (int pos = 0; pos < C; ++pos) {\n            if (board[pos] != -1) continue;\n            while (ptr < (int)chosen.size() && used[chosen[ptr]]) ++ptr;\n            board[pos] = chosen[ptr];\n            used[chosen[ptr]] = 1;\n        }\n\n        /* ---- 6) helper structures for fast updates ---- */\n        vector<int> cell2seed = board;               // copy\n        vector<int> seed2cell(S, -1);\n        for (int c = 0; c < C; ++c) seed2cell[cell2seed[c]] = c;\n\n        auto edgePotential = [&](int s1, int s2) -> long long {\n            long long p = 0;\n            for (int l = 0; l < M; ++l) p += max(seed[s1][l], seed[s2][l]);\n            return p;\n        };\n\n        // total sum of edge potentials (objective for local search)\n        long long totalPot = 0;\n        for (auto [u, v] : edges)\n            totalPot += edgePotential(cell2seed[u], cell2seed[v]);\n\n        /* ---- 7) local optimisation (swap / replace) ---- */\n        mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n        uniform_int_distribution<int> cellDist(0, C - 1);\n        uniform_int_distribution<int> seedDist(0, S - 1);\n\n        const int ITER = 20000;          // enough for the tiny instance\n        for (int it = 0; it < ITER; ++it) {\n            if (uniform_int_distribution<int>(0, 1)(rng)) {\n                /* ---- swap two cells ---- */\n                int a = cellDist(rng);\n                int b = cellDist(rng);\n                if (a == b) continue;\n                int sa = cell2seed[a];\n                int sb = cell2seed[b];\n                long long delta = 0;\n                // edges incident to a\n                for (auto [u, v] : edges) {\n                    if (u == a && v != b)      delta -= edgePotential(sa, cell2seed[v]);\n                    else if (v == a && u != b) delta -= edgePotential(sa, cell2seed[u]);\n                }\n                // edges incident to b\n                for (auto [u, v] : edges) {\n                    if (u == b && v != a)      delta -= edgePotential(sb, cell2seed[v]);\n                    else if (v == b && u != a) delta -= edgePotential(sb, cell2seed[u]);\n                }\n                // after swap\n                for (auto [u, v] : edges) {\n                    if (u == a && v != b)      delta += edgePotential(sb, cell2seed[v]);\n                    else if (v == a && u != b) delta += edgePotential(sb, cell2seed[u]);\n                }\n                for (auto [u, v] : edges) {\n                    if (u == b && v != a)      delta += edgePotential(sa, cell2seed[v]);\n                    else if (v == b && u != a) delta += edgePotential(sa, cell2seed[u]);\n                }\n\n                if (delta > 0) {                 // keep improving move\n                    totalPot += delta;\n                    swap(cell2seed[a], cell2seed[b]);\n                    seed2cell[sa] = b;\n                    seed2cell[sb] = a;\n                }\n            } else {\n                /* ---- replace a cell by an unused seed ---- */\n                int cell = cellDist(rng);\n                int curSeed = cell2seed[cell];\n                int newSeed = seedDist(rng);\n                if (seed2cell[newSeed] != -1) continue; // already placed\n\n                long long delta = 0;\n                for (auto [u, v] : edges) {\n                    if (u == cell) delta -= edgePotential(curSeed, cell2seed[v]);\n                    else if (v == cell) delta -= edgePotential(curSeed, cell2seed[u]);\n                }\n                for (auto [u, v] : edges) {\n                    if (u == cell) delta += edgePotential(newSeed, cell2seed[v]);\n                    else if (v == cell) delta += edgePotential(newSeed, cell2seed[u]);\n                }\n\n                if (delta > 0) {\n                    totalPot += delta;\n                    cell2seed[cell] = newSeed;\n                    seed2cell[curSeed] = -1;\n                    seed2cell[newSeed] = cell;\n                }\n            }\n        }\n\n        /* ---- 8) output the final board ---- */\n        for (int r = 0; r < N; ++r) {\n            for (int c = 0; c < N; ++c) {\n                if (c) cout << ' ';\n                cout << cell2seed[cellId(r, c)];\n            }\n            cout << '\\n';\n        }\n        cout.flush();\n\n        /* ---- 9) read the next generation of seeds ---- */\n        for (int i = 0; i < S; ++i)\n            for (int l = 0; l < M; ++l)\n                cin >> seed[i][l];\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\n/* ---------- Hungarian algorithm (minimum assignment) ---------- */\nconst long long INF = (1LL << 60);\n\nvector<int> hungarian(const vector<vector<long long>>& a) {\n    int n = (int)a.size();\n    vector<long long> u(n + 1), v(n + 1);\n    vector<int> p(n + 1), way(n + 1);\n    for (int i = 1; i <= n; ++i) {\n        p[0] = i;\n        long long j0 = 0;\n        vector<long long> minv(n + 1, INF);\n        vector<char> used(n + 1, false);\n        do {\n            used[j0] = true;\n            int i0 = p[j0];\n            long long delta = INF;\n            long long j1 = 0;\n            for (int j = 1; j <= n; ++j) if (!used[j]) {\n                long long cur = a[i0 - 1][j - 1] - u[i0] - v[j];\n                if (cur < minv[j]) { minv[j] = cur; way[j] = (int)j0; }\n                if (minv[j] < delta) { delta = minv[j]; j1 = j; }\n            }\n            for (int j = 0; j <= n; ++j) {\n                if (used[j]) { u[p[j]] += delta; v[j] -= delta; }\n                else          minv[j] -= delta;\n            }\n            j0 = j1;\n        } while (p[j0] != 0);\n        // augmenting\n        do {\n            int j1 = way[j0];\n            p[j0] = p[j1];\n            j0 = j1;\n        } while (j0);\n    }\n    vector<int> ans(n);\n    for (int j = 1; j <= n; ++j) ans[p[j] - 1] = j - 1;\n    return ans;          // row i -> column ans[i]\n}\n\n/* ------------------------------------------------------------- */\n\nstruct Job {\n    int sx, sy, dx, dy;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, V;\n    if (!(cin >> N >> M >> V)) return 0;\n    vector<string> s(N), t(N);\n    for (int i = 0; i < N; ++i) cin >> s[i];\n    for (int i = 0; i < N; ++i) cin >> t[i];\n\n    /* ----- collect cells, discard already\u2011correct ones ----- */\n    using P = pair<int,int>;\n    vector<P> src, dst;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) {\n            bool has = (s[i][j] == '1');\n            bool need = (t[i][j] == '1');\n            if (has && need) continue;          // already correct\n            if (has) src.emplace_back(i, j);\n            if (need) dst.emplace_back(i, j);\n        }\n\n    int K = (int)src.size();\n    if (K == 0) {\n        // nothing to move \u2013 still have to output a valid arm\n        cout << 2 << \"\\n\";\n        cout << 0 << ' ' << 1 << \"\\n\";\n        cout << 0 << ' ' << 0 << \"\\n\";\n        return 0;\n    }\n\n    /* ----- cost matrix (Manhattan distances) ----- */\n    vector<vector<long long>> cost(K, vector<long long>(K));\n    for (int i = 0; i < K; ++i)\n        for (int j = 0; j < K; ++j)\n            cost[i][j] = llabs(src[i].first - dst[j].first) +\n                         llabs(src[i].second - dst[j].second);\n\n    /* ----- optimal matching ----- */\n    vector<int> match = hungarian(cost);          // src i -> dst[match[i]]\n\n    /* ----- build job list ----- */\n    vector<Job> jobs;\n    jobs.reserve(K);\n    for (int i = 0; i < K; ++i)\n        jobs.push_back({src[i].first, src[i].second,\n                        dst[match[i]].first, dst[match[i]].second});\n\n    /* ----- greedy nearest\u2011neighbour ordering ----- */\n    vector<Job> ordered;\n    ordered.reserve(K);\n    int cur_rx = 0, cur_ry = 0;   // current root position (used only for ordering)\n    vector<char> taken(K, 0);\n    for (int step = 0; step < K; ++step) {\n        long long best = (1LL << 60);\n        int bestIdx = -1;\n        for (int i = 0; i < K; ++i) if (!taken[i]) {\n            long long d = llabs(jobs[i].sx - cur_rx) + llabs(jobs[i].sy - cur_ry);\n            if (d < best) { best = d; bestIdx = i; }\n        }\n        taken[bestIdx] = 1;\n        ordered.push_back(jobs[bestIdx]);\n        // approximate next root position by the destination of this job\n        cur_rx = ordered.back().dx;\n        cur_ry = ordered.back().dy;\n    }\n\n    /* ----- robot state ----- */\n    const int DX[4] = {0, 1, 0, -1};   // U D L R   (x downwards)\n    const int DY[4] = {1, 0, -1, 0};\n\n    int root_x = 0, root_y = 0;   // initial root (chosen arbitrarily inside grid)\n    int cur_dir = 0;             // initial orientation is to the right\n\n    auto output_turn = [&](char mv, char rot,\n                           char act_root = '.', char act_leaf = '.') {\n        string S;\n        S.reserve(4);\n        S.push_back(mv);\n        S.push_back(rot);\n        S.push_back(act_root);\n        S.push_back(act_leaf);\n        cout << S << \"\\n\";\n    };\n\n    auto move_root_to = [&](int tx, int ty) {\n        while (root_x != tx || root_y != ty) {\n            char mv = '.';\n            if (root_x < tx) { ++root_x; mv = 'D'; }\n            else if (root_x > tx) { --root_x; mv = 'U'; }\n            else if (root_y < ty) { ++root_y; mv = 'R'; }\n            else if (root_y > ty) { --root_y; mv = 'L'; }\n            output_turn(mv, '.');\n        }\n    };\n\n    /* rotate from cur_dir to target_dir using the minimal number of 90\u00b0 turns */\n    auto rotate_to = [&](int target_dir) {\n        int diff = (target_dir - cur_dir + 4) % 4;\n        if (diff == 0) return;\n        if (diff == 1) {                 // one clockwise\n            output_turn('.', 'R');\n            cur_dir = (cur_dir + 1) & 3;\n        } else if (diff == 3) {          // one counter\u2011clockwise\n            output_turn('.', 'L');\n            cur_dir = (cur_dir + 3) & 3;\n        } else {                         // diff == 2\n            output_turn('.', 'R');\n            cur_dir = (cur_dir + 1) & 3;\n            output_turn('.', 'R');\n            cur_dir = (cur_dir + 1) & 3;\n        }\n    };\n\n    /* move robot so that the fingertip ends on (cx,cy) */\n    auto go_to_cell = [&](int cx, int cy) {\n        int chosen_dir = -1, rx = 0, ry = 0;\n        for (int d = 0; d < 4; ++d) {\n            int nx = cx - DX[d];\n            int ny = cy - DY[d];\n            if (0 <= nx && nx < N && 0 <= ny && ny < N) {\n                chosen_dir = d;\n                rx = nx; ry = ny;\n                break;\n            }\n        }\n        move_root_to(rx, ry);\n        rotate_to(chosen_dir);\n    };\n\n    /* ----- output robot arm description (root at (0,0)) ----- */\n    cout << 2 << \"\\n\";\n    cout << 0 << ' ' << 1 << \"\\n\";\n    cout << root_x << ' ' << root_y << \"\\n\";\n\n    /* ----- execute all jobs ----- */\n    for (const Job& jb : ordered) {\n        // pick\n        go_to_cell(jb.sx, jb.sy);\n        output_turn('.', '.', '.', 'P');\n        // drop\n        go_to_cell(jb.dx, jb.dy);\n        output_turn('.', '.', '.', 'P');\n    }\n\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point { int x, y; };\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    if (!(cin >> N)) return 0;\n    vector<Point> mackerel(N), sardine(N);\n    for (int i = 0; i < N; ++i) cin >> mackerel[i].x >> mackerel[i].y;\n    for (int i = 0; i < N; ++i) cin >> sardine[i].x >> sardine[i].y;\n\n    /* ------------------------------------------------------------\n       1. very fine grid (4000 \u00d7 4000)\n    */\n    const int G    = 4000;\n    const int cell = (100000 + G - 1) / G;          // = 25\n    vector<vector<int>> grid(G, vector<int>(G, 0));\n\n    auto add = [&](const Point& p, int w) {\n        int gx = p.x / cell;\n        int gy = p.y / cell;\n        if (gx >= G) gx = G - 1;\n        if (gy >= G) gy = G - 1;\n        grid[gx][gy] += w;\n    };\n    for (auto &p : mackerel) add(p, +1);\n    for (auto &p : sardine)  add(p, -1);\n\n    /* ------------------------------------------------------------\n       2. 2\u2011D prefix sum\n    */\n    vector<vector<long long>> pref(G + 1, vector<long long>(G + 1, 0));\n    for (int i = 0; i < G; ++i)\n        for (int j = 0; j < G; ++j)\n            pref[i + 1][j + 1] = pref[i][j + 1] + pref[i + 1][j] -\n                                 pref[i][j] + grid[i][j];\n\n    auto rectSum = [&](int x1, int x2, int y1, int y2) -> long long {\n        // inclusive indices, assume x1\u2264x2 , y1\u2264y2\n        return pref[x2 + 1][y2 + 1] - pref[x1][y2 + 1] -\n               pref[x2 + 1][y1] + pref[x1][y1];\n    };\n\n    /* ------------------------------------------------------------\n       3. massive random search (more candidates)\n    */\n    std::mt19937 rng(\n        (unsigned)chrono::high_resolution_clock::now().time_since_epoch().count());\n    std::uniform_int_distribution<int> distG(0, G - 1);\n    const double TIME_LIMIT = 1.97;                 // seconds\n    auto start = chrono::high_resolution_clock::now();\n\n    long long bestW = LLONG_MIN;\n    int bx1 = 0, bx2 = 0, by1 = 0, by2 = 0;\n\n    auto consider = [&](int xa, int xb, int ya, int yb) {\n        if (xa > xb) swap(xa, xb);\n        if (ya > yb) swap(ya, yb);\n        long long w = rectSum(xa, xb, ya, yb);\n        if (w > bestW) {\n            bestW = w;\n            bx1 = xa; bx2 = xb;\n            by1 = ya; by2 = yb;\n        }\n    };\n\n    const int RAND_ITER = 1700000;   // more than before\n    for (int i = 0; i < RAND_ITER; ++i) {\n        if (chrono::duration<double>(chrono::high_resolution_clock::now() - start).count()\n                > TIME_LIMIT) break;\n        int x1 = distG(rng), x2 = distG(rng);\n        int y1 = distG(rng), y2 = distG(rng);\n        consider(x1, x2, y1, y2);\n    }\n\n    /* fish\u2011based rectangles */\n    vector<pair<int,int>> mIdx, sIdx;\n    mIdx.reserve(N); sIdx.reserve(N);\n    for (auto &p : mackerel) {\n        int gx = min(p.x / cell, G - 1);\n        int gy = min(p.y / cell, G - 1);\n        mIdx.emplace_back(gx, gy);\n    }\n    for (auto &p : sardine) {\n        int gx = min(p.x / cell, G - 1);\n        int gy = min(p.y / cell, G - 1);\n        sIdx.emplace_back(gx, gy);\n    }\n    std::uniform_int_distribution<int> distM(0, (int)mIdx.size() - 1);\n    std::uniform_int_distribution<int> distS(0, (int)sIdx.size() - 1);\n\n    const int POINT_ITER = 1300000;\n    for (int i = 0; i < POINT_ITER; ++i) {\n        if (chrono::duration<double>(chrono::high_resolution_clock::now() - start).count()\n                > TIME_LIMIT) break;\n        int xa, xb, ya, yb;\n        int typ = rng() & 3;\n        if (typ == 0) {                       // two mackerels\n            auto a = mIdx[distM(rng)];\n            auto b = mIdx[distM(rng)];\n            xa = a.first; xb = b.first;\n            ya = a.second; yb = b.second;\n        } else if (typ == 1) {                // two sardines\n            auto a = sIdx[distS(rng)];\n            auto b = sIdx[distS(rng)];\n            xa = a.first; xb = b.first;\n            ya = a.second; yb = b.second;\n        } else if (typ == 2) {                // one of each\n            auto a = mIdx[distM(rng)];\n            auto b = sIdx[distS(rng)];\n            xa = a.first; xb = b.first;\n            ya = a.second; yb = b.second;\n        } else {                              // single cell + small margin\n            auto a = mIdx[distM(rng)];\n            xa = xb = a.first;\n            ya = yb = a.second;\n            xb = min(G - 1, xb + (int)(rng() % 3));\n            yb = min(G - 1, yb + (int)(rng() % 3));\n        }\n        consider(xa, xb, ya, yb);\n    }\n\n    /* ------------------------------------------------------------\n       4. hill\u2011climb routine\n    */\n    auto hillClimb = [&](int x1, int x2, int y1, int y2)\n        -> tuple<int,int,int,int,long long>\n    {\n        long long w = rectSum(x1, x2, y1, y2);\n        bool improved = true;\n        while (improved) {\n            improved = false;\n            // outward\n            if (x1 > 0) {\n                long long w2 = rectSum(x1 - 1, x2, y1, y2);\n                if (w2 > w) { w = w2; --x1; improved = true; }\n            }\n            if (x2 + 1 < G) {\n                long long w2 = rectSum(x1, x2 + 1, y1, y2);\n                if (w2 > w) { w = w2; ++x2; improved = true; }\n            }\n            if (y1 > 0) {\n                long long w2 = rectSum(x1, x2, y1 - 1, y2);\n                if (w2 > w) { w = w2; --y1; improved = true; }\n            }\n            if (y2 + 1 < G) {\n                long long w2 = rectSum(x1, x2, y1, y2 + 1);\n                if (w2 > w) { w = w2; ++y2; improved = true; }\n            }\n            // inward (keep size \u2265 1)\n            if (x2 - x1 >= 1) {\n                long long w2 = rectSum(x1 + 1, x2, y1, y2);\n                if (w2 > w) { w = w2; ++x1; improved = true; }\n            }\n            if (x2 - x1 >= 1) {\n                long long w2 = rectSum(x1, x2 - 1, y1, y2);\n                if (w2 > w) { w = w2; --x2; improved = true; }\n            }\n            if (y2 - y1 >= 1) {\n                long long w2 = rectSum(x1, x2, y1 + 1, y2);\n                if (w2 > w) { w = w2; ++y1; improved = true; }\n            }\n            if (y2 - y1 >= 1) {\n                long long w2 = rectSum(x1, x2, y1, y2 - 1);\n                if (w2 > w) { w = w2; --y2; improved = true; }\n            }\n        }\n        return {x1, x2, y1, y2, w};\n    };\n\n    tie(bx1, bx2, by1, by2, bestW) = hillClimb(bx1, bx2, by1, by2);\n\n    /* ------------------------------------------------------------\n       5. big\u2011step expansion\n    */\n    auto bigExpand = [&](int &x1, int &x2, int &y1, int &y2, long long &curW) {\n        bool improved = true;\n        while (improved) {\n            improved = false;\n            // left\n            for (int d = 1; d <= 10; ++d) {\n                if (x1 - d < 0) break;\n                long long w2 = rectSum(x1 - d, x2, y1, y2);\n                if (w2 > curW) { curW = w2; x1 -= d; improved = true; break; }\n            }\n            // right\n            for (int d = 1; d <= 10; ++d) {\n                if (x2 + d >= G) break;\n                long long w2 = rectSum(x1, x2 + d, y1, y2);\n                if (w2 > curW) { curW = w2; x2 += d; improved = true; break; }\n            }\n            // bottom\n            for (int d = 1; d <= 10; ++d) {\n                if (y1 - d < 0) break;\n                long long w2 = rectSum(x1, x2, y1 - d, y2);\n                if (w2 > curW) { curW = w2; y1 -= d; improved = true; break; }\n            }\n            // top\n            for (int d = 1; d <= 10; ++d) {\n                if (y2 + d >= G) break;\n                long long w2 = rectSum(x1, x2, y1, y2 + d);\n                if (w2 > curW) { curW = w2; y2 += d; improved = true; break; }\n            }\n        }\n    };\n\n    bigExpand(bx1, bx2, by1, by2, bestW);\n\n    /* ------------------------------------------------------------\n       6. perturbations + two hill\u2011climbs + big\u2011expand\n    */\n    std::uniform_int_distribution<int> shiftDist(-5, 5);\n    for (int rep = 0; rep < 200; ++rep) {\n        int nx1 = bx1 + shiftDist(rng);\n        int nx2 = bx2 + shiftDist(rng);\n        int ny1 = by1 + shiftDist(rng);\n        int ny2 = by2 + shiftDist(rng);\n        nx1 = max(0, min(G - 1, nx1));\n        nx2 = max(0, min(G - 1, nx2));\n        ny1 = max(0, min(G - 1, ny1));\n        ny2 = max(0, min(G - 1, ny2));\n        if (nx1 > nx2) swap(nx1, nx2);\n        if (ny1 > ny2) swap(ny1, ny2);\n        if (nx2 - nx1 < 1) { if (nx2 + 1 < G) ++nx2; else if (nx1 > 0) --nx1; }\n        if (ny2 - ny1 < 1) { if (ny2 + 1 < G) ++ny2; else if (ny1 > 0) --ny1; }\n\n        int tx1, tx2, ty1, ty2;\n        long long tw;\n        tie(tx1, tx2, ty1, ty2, tw) = hillClimb(nx1, nx2, ny1, ny2);\n        // **second** hill\u2011climb\n        tie(tx1, tx2, ty1, ty2, tw) = hillClimb(tx1, tx2, ty1, ty2);\n        bigExpand(tx1, tx2, ty1, ty2, tw);\n\n        if (tw > bestW) {\n            bestW = tw;\n            bx1 = tx1; bx2 = tx2; by1 = ty1; by2 = ty2;\n        }\n    }\n\n    /* ------------------------------------------------------------\n       7. output\n    */\n    if (bestW <= 0) {                     // empty rectangle, score = 1\n        cout << 4 << '\\n';\n        cout << 0 << ' ' << 0 << '\\n';\n        cout << 1 << ' ' << 0 << '\\n';\n        cout << 1 << ' ' << 1 << '\\n';\n        cout << 0 << ' ' << 1 << '\\n';\n        return 0;\n    }\n\n    int xmin = bx1 * cell;\n    int xmax = min(100000, (bx2 + 1) * cell);\n    int ymin = by1 * cell;\n    int ymax = min(100000, (by2 + 1) * cell);\n\n    if (xmin == xmax) { ++xmax; if (xmax > 100000) xmax = 100000; }\n    if (ymin == ymax) { ++ymax; if (ymax > 100000) ymax = 100000; }\n\n    cout << 4 << '\\n';\n    cout << xmin << ' ' << ymin << '\\n';\n    cout << xmax << ' ' << ymin << '\\n';\n    cout << xmax << ' ' << ymax << '\\n';\n    cout << xmin << ' ' << ymax << '\\n';\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Placed {\n    long long x, y;   // bottom\u2011left corner\n    long long w, h;   // width, height after rotation\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    long long sigma;\n    if (!(cin >> N >> T >> sigma)) return 0;\n\n    vector<long long> w_obs(N), h_obs(N);\n    for (int i = 0; i < N; ++i) cin >> w_obs[i] >> h_obs[i];\n\n    /* ------------------------------------------------------------\n       1. Greedy placement, allowing both directions U and L\n       ------------------------------------------------------------ */\n    vector<int>     chosen_rot(N);   // 0 = keep, 1 = rotate\n    vector<char>    chosen_dir(N);   // 'U' or 'L'\n    vector<int>     chosen_ref(N);   // -1 or previous index\n    vector<Placed>  placed(N);\n\n    long long curW = 0, curH = 0;   // current bounding box\n\n    for (int i = 0; i < N; ++i) {\n        long long bestScore = LLONG_MAX;\n        int      bestRot   = 0;\n        char     bestDir   = 'U';\n        int      bestRef   = -1;\n        long long bestX    = 0, bestY = 0, bestW = 0, bestH = 0;\n\n        for (int rot = 0; rot <= 1; ++rot) {\n            long long rw = (rot == 0 ? w_obs[i] : h_obs[i]);\n            long long rh = (rot == 0 ? h_obs[i] : w_obs[i]);\n\n            for (char dir : {'U', 'L'}) {\n                for (int ref = -1; ref < i; ++ref) {\n                    long long x, y;\n\n                    if (dir == 'U') {               // move upward\n                        x = (ref == -1 ? 0LL : placed[ref].x + placed[ref].w);\n                        y = 0;\n                        for (int j = 0; j < i; ++j) {\n                            // horizontal overlap ?\n                            long long l1 = x, r1 = x + rw;\n                            long long l2 = placed[j].x, r2 = placed[j].x + placed[j].w;\n                            if (r1 <= l2 || r2 <= l1) continue;\n                            y = max(y, placed[j].y + placed[j].h);\n                        }\n                    } else {                         // dir == 'L', move leftward\n                        y = (ref == -1 ? 0LL : placed[ref].y + placed[ref].h);\n                        x = 0;\n                        for (int j = 0; j < i; ++j) {\n                            // vertical overlap ?\n                            long long b1 = y, t1 = y + rh;\n                            long long b2 = placed[j].y, t2 = placed[j].y + placed[j].h;\n                            if (t1 <= b2 || t2 <= b1) continue;\n                            x = max(x, placed[j].x + placed[j].w);\n                        }\n                    }\n\n                    long long newW = max(curW, x + rw);\n                    long long newH = max(curH, y + rh);\n                    long long score = newW + newH;\n\n                    if (score < bestScore) {\n                        bestScore = score;\n                        bestRot   = rot;\n                        bestDir   = dir;\n                        bestRef   = ref;\n                        bestX     = x;\n                        bestY     = y;\n                        bestW     = rw;\n                        bestH     = rh;\n                    }\n                } // ref\n            } // dir\n        } // rot\n\n        // store the choice\n        chosen_rot[i] = bestRot;\n        chosen_dir[i] = bestDir;\n        chosen_ref[i] = bestRef;\n        placed[i] = {bestX, bestY, bestW, bestH};\n\n        curW = max(curW, bestX + bestW);\n        curH = max(curH, bestY + bestH);\n    }\n\n    /* ------------------------------------------------------------\n       2. Output the same placement for every turn\n       ------------------------------------------------------------ */\n    for (int turn = 0; turn < T; ++turn) {\n        cout << N << '\\n';\n        for (int i = 0; i < N; ++i) {\n            cout << i << ' ' << chosen_rot[i] << ' ' << chosen_dir[i] << ' '\n                 << chosen_ref[i] << '\\n';\n        }\n        cout.flush();\n\n        long long Wp, Hp;\n        if (!(cin >> Wp >> Hp)) return 0;\n        (void)Wp; (void)Hp;   // values are not needed\n    }\n    return 0;\n}","ahc041":"#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, H;\n    if (!(cin >> N >> M >> H)) return 0;\n\n    vector<int> A(N);\n    for (int i = 0; i < N; ++i) cin >> A[i];\n\n    vector<vector<int>> adj(N);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n\n    // coordinates are irrelevant \u2013 just read them\n    for (int i = 0; i < N; ++i) {\n        int x, y;\n        cin >> x >> y;\n        (void)x; (void)y;\n    }\n\n    /* -------------------------------------------------------------\n       1. Greedy construction: single root + beauty\u2011ordered frontier\n       ------------------------------------------------------------- */\n    vector<int> parent(N, -1);\n    vector<int> depth(N, -1);\n    vector<char> assigned(N, 0);\n\n    using P = pair<int,int>;                     // (beauty , vertex)\n\n    priority_queue<P, vector<P>, greater<P>> freeHeap;\n    for (int v = 0; v < N; ++v) freeHeap.emplace(A[v], v);\n\n    while (!freeHeap.empty()) {\n        int root = -1;\n        while (!freeHeap.empty()) {\n            auto [val, v] = freeHeap.top(); freeHeap.pop();\n            if (!assigned[v]) { root = v; break; }\n        }\n        if (root == -1) break;   // all vertices assigned\n\n        parent[root] = -1;\n        depth[root]  = 0;\n        assigned[root] = 1;\n\n        priority_queue<P, vector<P>, greater<P>> frontier;\n        frontier.emplace(A[root], root);\n\n        while (!frontier.empty()) {\n            auto [_, u] = frontier.top(); frontier.pop();\n            if (depth[u] == H) continue;          // cannot go deeper\n            for (int nb : adj[u]) {\n                if (assigned[nb]) continue;\n                parent[nb] = u;\n                depth[nb]  = depth[u] + 1;\n                assigned[nb] = 1;\n                frontier.emplace(A[nb], nb);\n            }\n        }\n    }\n\n    /* -------------------------------------------------------------\n       2. Build children list (needed for subtree updates)\n       ------------------------------------------------------------- */\n    vector<vector<int>> children(N);\n    for (int v = 0; v < N; ++v) {\n        if (parent[v] != -1) children[parent[v]].push_back(v);\n    }\n\n    /* -------------------------------------------------------------\n       3. Helper: max depth inside the subtree rooted at `v`\n       ------------------------------------------------------------- */\n    auto subtree_max_depth = [&](int v) -> int {\n        int mx = depth[v];\n        queue<int> q;\n        q.push(v);\n        while (!q.empty()) {\n            int x = q.front(); q.pop();\n            mx = max(mx, depth[x]);\n            for (int ch : children[x]) q.push(ch);\n        }\n        return mx;\n    };\n\n    /* -------------------------------------------------------------\n       4. Local improvement \u2013 deepen high\u2011beauty vertices safely\n       ------------------------------------------------------------- */\n    const int ITER = 4;                     // number of improvement passes\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int a, int b){ return A[a] > A[b]; });   // descending beauty\n\n    for (int it = 0; it < ITER; ++it) {\n        for (int v : order) {\n            int curDepth = depth[v];\n            for (int nb : adj[v]) {\n                // candidate new depth\n                if (depth[nb] + 1 <= curDepth) continue;     // not deeper\n                if (depth[nb] + 1 > H) continue;            // would exceed limit\n\n                // avoid creating a cycle: nb must not be a descendant of v\n                bool cycle = false;\n                int cur = nb;\n                while (cur != -1) {\n                    if (cur == v) { cycle = true; break; }\n                    cur = parent[cur];\n                }\n                if (cycle) continue;\n\n                int newDepth = depth[nb] + 1;\n                int delta    = newDepth - curDepth;          // > 0\n                // safety check: every node of the subtree must stay \u2264 H\n                int maxInSub = subtree_max_depth(v);\n                if (maxInSub + delta > H) continue;          // would violate H\n\n                /* ----- perform the re\u2011attachment ----- */\n                // remove v from old parent's child list\n                if (parent[v] != -1) {\n                    auto &vec = children[parent[v]];\n                    vec.erase(remove(vec.begin(), vec.end(), v), vec.end());\n                }\n                // set new parent\n                parent[v] = nb;\n                children[nb].push_back(v);\n\n                // update depths of the whole subtree rooted at v\n                queue<int> q;\n                q.push(v);\n                while (!q.empty()) {\n                    int x = q.front(); q.pop();\n                    depth[x] += delta;\n                    for (int ch : children[x]) q.push(ch);\n                }\n                break;   // after a successful move stop trying other neighbours\n            }\n        }\n    }\n\n    /* -------------------------------------------------------------\n       5. Output\n       ------------------------------------------------------------- */\n    for (int i = 0; i < N; ++i) {\n        if (i) cout << ' ';\n        cout << parent[i];\n    }\n    cout << '\\n';\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    const int N = 20;\n    vector<string> g(N);\n    for (int i = 0; i < N; ++i) cin >> g[i];\n\n    struct Op { char d; int p; };\n    vector<Op> ans;\n\n    // collect all Oni positions\n    vector<pair<int,int>> oni;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (g[i][j] == 'x') oni.emplace_back(i, j);\n\n    for (auto [i, j] : oni) {\n        // check freedom in four directions\n        bool freeU = true, freeD = true, freeL = true, freeR = true;\n        for (int ii = 0; ii < i; ++ii) if (g[ii][j] == 'o') freeU = false;\n        for (int ii = i+1; ii < N; ++ii) if (g[ii][j] == 'o') freeD = false;\n        for (int jj = 0; jj < j; ++jj) if (g[i][jj] == 'o') freeL = false;\n        for (int jj = j+1; jj < N; ++jj) if (g[i][jj] == 'o') freeR = false;\n\n        // distances to the corresponding edge\n        int du = i + 1;\n        int dd = N - i;\n        int dl = j + 1;\n        int dr = N - j;\n\n        // choose the free direction with minimal distance\n        int bestDist = INT_MAX;\n        char dir = '?';\n        if (freeU && du < bestDist) { bestDist = du; dir = 'U'; }\n        if (freeD && dd < bestDist) { bestDist = dd; dir = 'D'; }\n        if (freeL && dl < bestDist) { bestDist = dl; dir = 'L'; }\n        if (freeR && dr < bestDist) { bestDist = dr; dir = 'R'; }\n\n        // apply the two opposite shifts\n        if (dir == 'U') {\n            for (int k = 0; k < du; ++k) ans.push_back({'U', j});\n            for (int k = 0; k < du; ++k) ans.push_back({'D', j});\n        } else if (dir == 'D') {\n            for (int k = 0; k < dd; ++k) ans.push_back({'D', j});\n            for (int k = 0; k < dd; ++k) ans.push_back({'U', j});\n        } else if (dir == 'L') {\n            for (int k = 0; k < dl; ++k) ans.push_back({'L', i});\n            for (int k = 0; k < dl; ++k) ans.push_back({'R', i});\n        } else if (dir == 'R') {\n            for (int k = 0; k < dr; ++k) ans.push_back({'R', i});\n            for (int k = 0; k < dr; ++k) ans.push_back({'L', i});\n        }\n        // after this Oni is considered removed; we do not modify g\n    }\n\n    for (auto [c, p] : ans) {\n        cout << c << ' ' << p << '\\n';\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = double;\n\n/* ---------- global data ---------- */\nstatic const int N = 100;          // fixed by the problem\nstatic const ll L = 500000;       // fixed\nstatic vector<int> T;             // target frequencies\nstatic vector<ll> pref;           // prefix sums of T\n\n/* ---------- weighted sampler (probability proportional to T[i]) ---------- */\nint weighted_sample(mt19937 &rng) {\n    uniform_int_distribution<ll> dist(0, L - 1);\n    ll r = dist(rng);\n    int lo = 0, hi = N - 1;\n    while (lo < hi) {\n        int mid = (lo + hi) >> 1;\n        if (pref[mid] > r) hi = mid;\n        else lo = mid + 1;\n    }\n    return lo;                    // 0 <= lo < N\n}\n\n/* ---------- fast evaluation using power iteration ---------- */\nld evaluate(const array<array<int, N>, N> &ab) {\n    // build transition matrix prob[i][j] (double)\n    static ld prob[N][N];\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            prob[i][j] = 0.0;\n\n    for (int i = 0; i < N; ++i) {\n        prob[i][ab[i][0]] += 0.5;   // a[i]\n        prob[i][ab[i][1]] += 0.5;   // b[i]\n    }\n\n    // power iteration\n    static ld v[N], v2[N];\n    for (int i = 0; i < N; ++i) v[i] = 1.0 / N;   // uniform start\n\n    const int ITER = 500;        // enough for convergence (N=100)\n    for (int it = 0; it < ITER; ++it) {\n        for (int j = 0; j < N; ++j) v2[j] = 0.0;\n        for (int i = 0; i < N; ++i) {\n            if (v[i] == 0.0) continue;\n            for (int j = 0; j < N; ++j) {\n                if (prob[i][j] != 0.0) v2[j] += v[i] * prob[i][j];\n            }\n        }\n        for (int i = 0; i < N; ++i) v[i] = v2[i];\n    }\n\n    // compute error \u03a3 |v[i]*L - T[i]|\n    ld err = 0.0;\n    for (int i = 0; i < N; ++i) {\n        ld expected = v[i] * (ld)L;\n        err += fabs(expected - (ld)T[i]);\n    }\n    return err;\n}\n\n/* ---------- main ---------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // input (N and L are fixed, but we read them for completeness)\n    int readN; ll readL;\n    if (!(cin >> readN >> readL)) return 0;\n    T.assign(N, 0);\n    for (int i = 0; i < N; ++i) cin >> T[i];\n\n    // prefix sums for weighted sampling\n    pref.assign(N, 0);\n    ll acc = 0;\n    for (int i = 0; i < N; ++i) {\n        acc += T[i];\n        pref[i] = acc;\n    }\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    // initial candidate (both edges drawn proportionally to T)\n    array<array<int, N>, N> cur;          // cur[i][0]=a[i], cur[i][1]=b[i]\n    for (int i = 0; i < N; ++i) {\n        cur[i][0] = weighted_sample(rng);\n        cur[i][1] = weighted_sample(rng);\n    }\n\n    ld bestErr = evaluate(cur);\n    auto best = cur;\n\n    // time\u2011controlled hill climbing\n    const double TIME_BUDGET = 1.90;       // seconds\n    auto start = chrono::steady_clock::now();\n\n    while (true) {\n        auto now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(now - start).count();\n        if (elapsed > TIME_BUDGET) break;\n\n        // propose a small mutation\n        array<array<int, N>, N> cand = best;\n        int i = rng() % N;\n        bool changeA = (rng() & 1);\n        if (changeA) cand[i][0] = weighted_sample(rng);\n        else        cand[i][1] = weighted_sample(rng);\n\n        ld curErr = evaluate(cand);\n        if (curErr < bestErr) {\n            bestErr = curErr;\n            best = cand;\n        }\n    }\n\n    // output the best plan found\n    for (int i = 0; i < N; ++i) {\n        cout << best[i][0] << ' ' << best[i][1] << '\\n';\n    }\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing int64 = long long;\nusing u64   = unsigned long long;\n\n/* -------------------------------------------------------------\n   Hilbert order (grid 2^14 > 10000)\n   ------------------------------------------------------------- */\nstatic inline void rot(int n, int &x, int &y, int rx, int ry) {\n    if (ry == 0) {\n        if (rx == 1) {\n            x = n - 1 - x;\n            y = n - 1 - y;\n        }\n        swap(x, y);\n    }\n}\nstatic inline u64 hilbertOrder(int x, int y) {\n    const int LOG = 14;\n    u64 d = 0;\n    int s = 1 << (LOG - 1);\n    for (int i = LOG; i > 0; --i) {\n        int rx = (x & s) > 0;\n        int ry = (y & s) > 0;\n        d <<= 2;\n        d |= (u64)(rx * 3 ^ ry);\n        rot(s, x, y, rx, ry);\n        s >>= 1;\n    }\n    return d;\n}\n\n/* -------------------------------------------------------------\n   Euclidean distance (floor) between centre points\n   ------------------------------------------------------------- */\ninline int distFloor(const vector<int>& cx,\n                     const vector<int>& cy,\n                     int a, int b) {\n    int64 dx = (int64)cx[a] - cx[b];\n    int64 dy = (int64)cy[a] - cy[b];\n    return (int)std::sqrt((double)(dx * dx + dy * dy));\n}\n\n/* -------------------------------------------------------------\n   Prim on dense complete graph \u2013 returns edges and total length\n   ------------------------------------------------------------- */\nstatic pair<vector<pair<int,int>>, int64>\nprimDense(const vector<int>& verts,\n          const vector<int>& cx,\n          const vector<int>& cy) {\n    int s = (int)verts.size();\n    vector<char> in(s, 0);\n    vector<int64> bestDist(s, (int64)4e18);\n    vector<int> parent(s, -1);\n    vector<pair<int,int>> edges;\n    edges.reserve(s - 1);\n    int64 total = 0;\n\n    // start from vertex 0\n    in[0] = 1;\n    for (int i = 1; i < s; ++i) {\n        int d = distFloor(cx, cy, verts[0], verts[i]);\n        bestDist[i] = d;\n        parent[i] = 0;\n    }\n\n    for (int added = 1; added < s; ++added) {\n        int u = -1;\n        int64 best = (int64)4e18;\n        for (int i = 0; i < s; ++i) if (!in[i] && bestDist[i] < best) {\n            best = bestDist[i];\n            u = i;\n        }\n        edges.emplace_back(verts[u], verts[parent[u]]);\n        total += best;\n        in[u] = 1;\n\n        for (int i = 0; i < s; ++i) if (!in[i]) {\n            int d = distFloor(cx, cy, verts[u], verts[i]);\n            if (d < bestDist[i]) {\n                bestDist[i] = d;\n                parent[i] = u;\n            }\n        }\n    }\n    return {edges, total};\n}\n\n/* -------------------------------------------------------------\n   Main\n   ------------------------------------------------------------- */\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    if (!(cin >> N >> M >> Q >> L >> W)) return 0;\n    vector<int> G(M);\n    for (int i = 0; i < M; ++i) cin >> G[i];\n\n    vector<int> cx(N), cy(N);\n    for (int i = 0; i < N; ++i) {\n        int lx, rx, ly, ry;\n        cin >> lx >> rx >> ly >> ry;\n        cx[i] = (lx + rx) / 2;\n        cy[i] = (ly + ry) / 2;\n    }\n\n    /* ---------- Hilbert ordering ---------- */\n    vector<u64> ord(N);\n    for (int i = 0; i < N; ++i) ord[i] = hilbertOrder(cx[i], cy[i]);\n\n    vector<int> ids(N);\n    iota(ids.begin(), ids.end(), 0);\n    sort(ids.begin(), ids.end(),\n         [&](int a, int b){ return ord[a] < ord[b]; });\n\n    /* ---------- initial partition ---------- */\n    vector<vector<int>> groups(M);\n    int pos = 0;\n    for (int k = 0; k < M; ++k) {\n        groups[k].assign(ids.begin() + pos, ids.begin() + pos + G[k]);\n        pos += G[k];\n    }\n\n    /* ---------- compute MST for every group ---------- */\n    struct Info {\n        vector<pair<int,int>> edges;\n        int64 cost;\n    };\n    vector<Info> mstInfo(M);\n    for (int k = 0; k < M; ++k) {\n        auto res = primDense(groups[k], cx, cy);\n        mstInfo[k].edges = move(res.first);\n        mstInfo[k].cost  = res.second;\n    }\n\n    /* ---------- local improvement (swap) ---------- */\n    const int PASS = 2;\n    const int LIM  = 10;          // max examined cities per group\n    for (int pass = 0; pass < PASS; ++pass) {\n        for (int k = 0; k + 1 < M; ++k) {\n            auto &A = groups[k];\n            auto &B = groups[k + 1];\n            if (A.empty() || B.empty()) continue;\n\n            int limitA = min((int)A.size(), LIM);\n            int limitB = min((int)B.size(), LIM);\n\n            int64 bestGain = 0;\n            int bestAi = -1, bestBj = -1;\n            Info bestAInfo, bestBInfo;\n\n            for (int i = 0; i < limitA; ++i) {\n                for (int j = 0; j < limitB; ++j) {\n                    int a = A[i];\n                    int b = B[j];\n                    // swapped groups\n                    vector<int> A2 = A;\n                    vector<int> B2 = B;\n                    A2[i] = b;\n                    B2[j] = a;\n\n                    auto rA = primDense(A2, cx, cy);\n                    auto rB = primDense(B2, cx, cy);\n                    int64 gain = mstInfo[k].cost + mstInfo[k+1].cost\n                                 - (rA.second + rB.second);\n                    if (gain > bestGain) {\n                        bestGain = gain;\n                        bestAi = i; bestBj = j;\n                        bestAInfo.edges = move(rA.first);\n                        bestAInfo.cost  = rA.second;\n                        bestBInfo.edges = move(rB.first);\n                        bestBInfo.cost  = rB.second;\n                    }\n                }\n            }\n\n            if (bestGain > 0) {\n                // apply swap\n                int a_old = A[bestAi];\n                int b_old = B[bestBj];\n                A[bestAi] = b_old;\n                B[bestBj] = a_old;\n                mstInfo[k]   = move(bestAInfo);\n                mstInfo[k+1] = move(bestBInfo);\n            }\n        }\n    }\n\n    /* ---------- output ---------- */\n    cout << \"!\\n\";\n    for (int k = 0; k < M; ++k) {\n        const auto &g = groups[k];\n        for (size_t i = 0; i < g.size(); ++i) {\n            if (i) cout << ' ';\n            cout << g[i];\n        }\n        cout << '\\n';\n        for (auto &e : mstInfo[k].edges) {\n            cout << e.first << ' ' << e.second << '\\n';\n        }\n    }\n    return 0;\n}","ahc046":"#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    if (!(cin >> N >> M)) return 0;          // N = 20, M = 40 in the official tests\n\n    vector<pair<int,int>> p(M);\n    for (int i = 0; i < M; ++i) cin >> p[i].first >> p[i].second;\n\n    int cur_i = p[0].first;   // current row\n    int cur_j = p[0].second;  // current column\n\n    vector<string> ans;\n    auto add = [&](char act, char dir) {\n        ans.emplace_back(string(1, act) + \" \" + string(1, dir));\n    };\n\n    // ---------------------------------------------------------------\n    // move one coordinate (row or column) from cur to target\n    auto move_axis = [&](int &cur, int target, char dirPos, char dirNeg) {\n        int d = abs(target - cur);\n\n        int cost_direct = d;\n        int cost_to0    = 1 + target;               // slide to 0 then forward\n        int cost_toN    = 1 + (N - 1 - target);     // slide to N-1 then backward\n\n        int best = cost_direct;\n        int method = 0; // 0 = direct, 1 = slide to 0, 2 = slide to N-1\n        if (cost_to0 < best) { best = cost_to0; method = 1; }\n        if (cost_toN < best) { best = cost_toN; method = 2; }\n\n        if (method == 0) {                     // direct moves\n            char dir = (target > cur) ? dirPos : dirNeg;\n            int step = (target > cur) ? 1 : -1;\n            for (int k = 0; k < d; ++k) {\n                add('M', dir);\n                cur += step;\n            }\n        } else if (method == 1) {              // slide to 0 then forward\n            add('S', dirNeg);                   // slide towards the border 0\n            cur = 0;\n            for (int k = 0; k < target; ++k) {\n                add('M', dirPos);\n                ++cur;\n            }\n        } else {                               // method == 2, slide to N-1 then backward\n            add('S', dirPos);                   // slide towards the opposite border\n            cur = N - 1;\n            int back = (N - 1 - target);\n            for (int k = 0; k < back; ++k) {\n                add('M', dirNeg);\n                --cur;\n            }\n        }\n    };\n    // ---------------------------------------------------------------\n\n    for (int t = 1; t < M; ++t) {\n        // vertical movement (rows)\n        move_axis(cur_i, p[t].first, 'D', 'U');\n\n        // horizontal movement (columns)\n        move_axis(cur_j, p[t].second, 'R', 'L');\n    }\n\n    for (const string &s : ans) cout << s << '\\n';\n    return 0;\n}"}}}