{"model_name":"o4-mini-high","codes":{"1":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Rect { int x1,y1,x2,y2; };\nstruct Cand {\n    int j,w,h,left,right,down,up;\n    int waste;\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n;\n    cin >> n;\n    vector<int> x(n), y(n);\n    vector<long long> r(n);\n    for(int i=0;i<n;i++){\n        cin >> x[i] >> y[i] >> r[i];\n    }\n\n    // process largest first\n    vector<int> order(n);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int i,int j){ return r[i]>r[j]; });\n\n    // answer rectangles\n    vector<array<int,4>> ans(n);\n\n    // free space list, as half-open [x1,x2)x[y1,y2)\n    vector<Rect> freeRects;\n    freeRects.reserve(1000);\n    freeRects.push_back({0,0,10000,10000});\n\n    for(int idx: order){\n        long long ri = r[idx];\n        int xi = x[idx], yi = y[idx];\n\n        // 1) build \u201cideal\u201d dims near sqrt(r_i)\n        int w0 = std::sqrt((double)ri);\n        while(1LL*w0*w0 > ri) --w0;\n        while(1LL*(w0+1)*(w0+1) <= ri) ++w0;\n        w0 = max(1, min(w0,10000));\n        int h0 = (ri + w0 - 1)/w0;\n        if(h0>10000){\n            h0=10000;\n            w0 = (ri + h0 - 1)/h0;\n        }\n\n        vector<pair<int,int>> dims;\n        dims.emplace_back(w0,h0);\n        if(h0!=w0) dims.emplace_back(h0,w0);\n\n        // 2) scan free rectangles for a tight fit\n        vector<Cand> cands;\n        cands.reserve(freeRects.size()*2);\n        for(auto &d: dims){\n            int w=d.first, h=d.second;\n            for(int j=0;j<(int)freeRects.size();j++){\n                auto &R = freeRects[j];\n                int Rw=R.x2-R.x1, Rh=R.y2-R.y1;\n                if(Rw<w||Rh<h) continue;\n                int L = max(R.x1, xi - w + 1);\n                int Rg= min(xi,    R.x2 - w);\n                if(L>Rg) continue;\n                int D = max(R.y1, yi - h + 1);\n                int U = min(yi,    R.y2 - h);\n                if(D>U) continue;\n                int area = Rw*Rh;\n                int waste= area - w*h;\n                cands.push_back({j,w,h,L,Rg,D,U,waste});\n            }\n        }\n\n        if(!cands.empty()){\n            // pick minimal wasted\n            int best=0;\n            int bestW=cands[0].waste;\n            int bestA = (freeRects[cands[0].j].x2 - freeRects[cands[0].j].x1)*\n                        (freeRects[cands[0].j].y2 - freeRects[cands[0].j].y1);\n            for(int i=1;i<(int)cands.size();i++){\n                int wst=cands[i].waste;\n                if(wst<bestW ||\n                   (wst==bestW && \n                    (freeRects[cands[i].j].x2 - freeRects[cands[i].j].x1)*\n                    (freeRects[cands[i].j].y2 - freeRects[cands[i].j].y1) < bestA)){\n                    best=i;\n                    bestW=wst;\n                    bestA = (freeRects[cands[i].j].x2 - freeRects[cands[i].j].x1)*\n                            (freeRects[cands[i].j].y2 - freeRects[cands[i].j].y1);\n                }\n            }\n            auto &c=cands[best];\n            // center as much as possible around the seed\n            int a0= xi - c.w/2;\n            a0 = min(max(a0,c.left), c.right);\n            int b0= yi - c.h/2;\n            b0 = min(max(b0,c.down), c.up);\n            ans[idx]={a0,b0,a0+c.w,b0+c.h};\n\n            // split out freeRects[c.j]\n            Rect R=freeRects[c.j];\n            // remove it\n            freeRects[c.j]=freeRects.back();\n            freeRects.pop_back();\n            int X1=R.x1, Y1=R.y1, X2=R.x2, Y2=R.y2;\n            // four-guillotine split\n            if(X1<a0)        freeRects.push_back({X1,Y1, a0,  Y2});\n            if(a0+c.w<X2)    freeRects.push_back({a0+c.w,Y1, X2,  Y2});\n            if(Y1<b0)        freeRects.push_back({a0, Y1, a0+c.w, b0});\n            if(b0+c.h<Y2)    freeRects.push_back({a0, b0+c.h, a0+c.w, Y2});\n        }\n        else {\n            // 3) fallback #1: take whole free rect covering the seed\n            double bestR=-1;\n            int bestJ=-1;\n            for(int j=0;j<(int)freeRects.size();j++){\n                auto &R=freeRects[j];\n                if(R.x1<=xi && xi<R.x2 && R.y1<=yi && yi<R.y2){\n                    long long wc=R.x2-R.x1, hc=R.y2-R.y1;\n                    long long sc=wc*hc;\n                    double ratio= (double)min(sc,ri)/max(sc,ri);\n                    if(ratio>bestR){\n                        bestR=ratio;\n                        bestJ=j;\n                    }\n                }\n            }\n            if(bestJ!=-1){\n                // occupy R fully\n                auto R=freeRects[bestJ];\n                ans[idx]={R.x1,R.y1,R.x2,R.y2};\n                freeRects[bestJ]=freeRects.back();\n                freeRects.pop_back();\n            }\n            else {\n                // 4) fallback #2: seed got covered by an earlier ad \u21d2 just place a 1\u00d71 somewhere\n                auto R=freeRects.back();\n                int j=(int)freeRects.size()-1;\n                int a=R.x1, b=R.y1;\n                ans[idx]={a,b,a+1,b+1};\n                freeRects[j]=freeRects.back();\n                freeRects.pop_back();\n                // split that little 1\u00d71 hole out\n                if(R.x1<a)        freeRects.push_back({R.x1,R.y1, a,  R.y2});\n                if(a+1<R.x2)      freeRects.push_back({a+1,R.y1,R.x2,R.y2});\n                if(R.y1<b)        freeRects.push_back({a,  R.y1, a+1, b  });\n                if(b+1<R.y2)      freeRects.push_back({a,  b+1, a+1,R.y2});\n            }\n        }\n    }\n\n    // finally print in the original order\n    for(int i=0;i<n;i++){\n        cout << ans[i][0] << ' '\n             << ans[i][1] << ' '\n             << ans[i][2] << ' '\n             << ans[i][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    int si, sj;\n    cin >> si >> sj;\n\n    static int t[50][50], p[50][50];\n    int maxTile = 0;\n    for(int i = 0; i < 50; i++){\n        for(int j = 0; j < 50; j++){\n            cin >> t[i][j];\n            maxTile = max(maxTile, t[i][j]);\n        }\n    }\n    // read the scores\n    for(int i = 0; i < 50; i++){\n        for(int j = 0; j < 50; j++){\n            cin >> p[i][j];\n        }\n    }\n\n    int M = maxTile + 1;\n    vector<char> answer;\n    answer.reserve(3000);\n\n    // visitedTile[x] = true once we've stepped on any cell of tile x\n    vector<bool> visitedTile(M, false);\n    visitedTile[ t[si][sj] ] = true;\n\n    // current position\n    int ci = si, cj = sj;\n\n    // random for tiny tie\u2010breaking\n    mt19937_64 rng( (unsigned)chrono::high_resolution_clock::now().time_since_epoch().count() );\n\n    // Directions: U=0, D=1, L=2, R=3\n    constexpr int dx[4] = {-1, 1, 0, 0};\n    constexpr int dy[4] = { 0, 0,-1, 1};\n    constexpr char dc[4] = {'U','D','L','R'};\n\n    // greedy until we run out of moves\n    while(true){\n        int bestW = -1;\n        int bestDir = -1;\n        int bestNi = -1, bestNj = -1;\n\n        for(int d = 0; d < 4; d++){\n            int ni = ci + dx[d];\n            int nj = cj + dy[d];\n            if(ni < 0 || ni >= 50 || nj < 0 || nj >= 50) continue;\n            int tileId = t[ni][nj];\n            if(visitedTile[tileId]) continue;\n\n            // compute \"degree\" = number of onward moves from (ni,nj)\n            int deg = 0;\n            for(int d2 = 0; d2 < 4; d2++){\n                int xi = ni + dx[d2];\n                int xj = nj + dy[d2];\n                if(xi < 0 || xi >= 50 || xj < 0 || xj >= 50) continue;\n                if(!visitedTile[ t[xi][xj] ]) deg++;\n            }\n\n            // weight = deg * BIG + p[ni][nj] + tiny_noise\n            int noise = int(rng() & 0xF);\n            int w = deg * 10000 + p[ni][nj] + noise;\n\n            if(w > bestW){\n                bestW = w;\n                bestDir = d;\n                bestNi = ni;\n                bestNj = nj;\n            }\n        }\n\n        if(bestDir < 0) break;  // no valid move\n\n        // commit to that move\n        ci = bestNi;\n        cj = bestNj;\n        visitedTile[ t[ci][cj] ] = true;\n        answer.push_back(dc[bestDir]);\n    }\n\n    // output the move sequence\n    for(char c : answer) cout << c;\n    cout << \"\\n\";\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nstatic constexpr int N = 30;\nstatic constexpr int VERTS = N*N;\nstatic constexpr double INIT_W = 5000.0;\nstatic constexpr double ALPHA = 0.1;\n\nint dr[4] = {-1,1,0,0};\nint dc[4] = {0,0,-1,1};\nchar dch[4] = {'U','D','L','R'};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // Estimated weights and visit counts\n    static double w_h[N][N-1], w_v[N-1][N];\n    static int cnt_h[N][N-1], cnt_v[N-1][N];\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N-1;j++){\n            w_h[i][j] = INIT_W;\n            cnt_h[i][j] = 0;\n        }\n    }\n    for(int i=0;i<N-1;i++){\n        for(int j=0;j<N;j++){\n            w_v[i][j] = INIT_W;\n            cnt_v[i][j] = 0;\n        }\n    }\n\n    // For Dijkstra\n    static double distArr[VERTS];\n    static bool done[VERTS];\n    static int prevNode[VERTS];\n    static char prevDir[VERTS];\n\n    auto idx = [&](int r,int c){ return r*N + c; };\n\n    for(int qi=0;qi<1000;qi++){\n        int si,sj,ti,tj;\n        if(!(cin>>si>>sj>>ti>>tj)){\n            return 0; // EOF safety\n        }\n        // Reset Dijkstra\n        const double INF = 1e18;\n        for(int i=0;i<VERTS;i++){\n            distArr[i] = INF;\n            done[i] = false;\n        }\n        int s_id = idx(si,sj), t_id = idx(ti,tj);\n        distArr[s_id] = 0.0;\n        // min-heap (dist,node)\n        priority_queue<pair<double,int>,\n                       vector<pair<double,int>>,\n                       greater<pair<double,int>>> pq;\n        pq.push({0.0,s_id});\n\n        // Dijkstra\n        while(!pq.empty()){\n            auto [cd,u] = pq.top(); pq.pop();\n            if(done[u]) continue;\n            done[u] = true;\n            if(u==t_id) break;\n            int ur = u / N, uc = u % N;\n            for(int d=0;d<4;d++){\n                int vr = ur + dr[d], vc = uc + dc[d];\n                if(vr<0||vr>=N||vc<0||vc>=N) continue;\n                double cost;\n                if(d==0){ // U\n                    cost = w_v[vr][vc]; \n                } else if(d==1){ // D\n                    cost = w_v[ur][uc];\n                } else if(d==2){ // L\n                    cost = w_h[vr][vc];\n                } else {    // R\n                    cost = w_h[ur][uc];\n                }\n                int v = idx(vr,vc);\n                double nd = cd + cost;\n                if(nd < distArr[v]){\n                    distArr[v] = nd;\n                    prevNode[v] = u;\n                    prevDir[v] = dch[d];\n                    pq.push({nd,v});\n                }\n            }\n        }\n\n        // Reconstruct path\n        vector<char> rev;\n        {\n            int cur = t_id;\n            while(cur != s_id){\n                rev.push_back(prevDir[cur]);\n                cur = prevNode[cur];\n            }\n        }\n        int L = rev.size();\n        string path;\n        path.reserve(L);\n        for(int i=L-1;i>=0;i--) path.push_back(rev[i]);\n\n        // Output and flush\n        cout<<path<<\"\\n\"<<flush;\n\n        // Read noisy total length\n        int b_obs;\n        cin>>b_obs;\n\n        // Compute estimated sum and collect edges\n        double s_est = 0;\n        int cr = si, cc = sj;\n        struct E { bool horiz; int r,c; };\n        vector<E> edges; edges.reserve(L);\n        for(char mv: path){\n            if(mv=='U'){\n                // edge v[cr-1][cc]\n                edges.push_back({false, cr-1, cc});\n                s_est += w_v[cr-1][cc];\n                cr--;\n            } else if(mv=='D'){\n                edges.push_back({false, cr, cc});\n                s_est += w_v[cr][cc];\n                cr++;\n            } else if(mv=='L'){\n                edges.push_back({true, cr, cc-1});\n                s_est += w_h[cr][cc-1];\n                cc--;\n            } else { // 'R'\n                edges.push_back({true, cr, cc});\n                s_est += w_h[cr][cc];\n                cc++;\n            }\n        }\n\n        // Distribute residual\n        double err = double(b_obs) - s_est;\n        if(L>0 && fabs(err)>1e-9){\n            double per = err / L;\n            for(auto &e: edges){\n                if(e.horiz){\n                    int &cnt = cnt_h[e.r][e.c];\n                    cnt++;\n                    double lr = ALPHA / sqrt(double(cnt));\n                    w_h[e.r][e.c] += lr * per;\n                    if(w_h[e.r][e.c] < 1.0) w_h[e.r][e.c] = 1.0;\n                } else {\n                    int &cnt = cnt_v[e.r][e.c];\n                    cnt++;\n                    double lr = ALPHA / sqrt(double(cnt));\n                    w_v[e.r][e.c] += lr * per;\n                    if(w_v[e.r][e.c] < 1.0) w_v[e.r][e.c] = 1.0;\n                }\n            }\n        }\n    }\n\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// fast xorshift RNG\nstatic uint64_t rng_state = chrono::steady_clock::now().time_since_epoch().count();\ninline uint32_t xorshift32() {\n    rng_state ^= rng_state << 13;\n    rng_state ^= rng_state >> 7;\n    rng_state ^= rng_state << 17;\n    return (uint32_t)rng_state;\n}\ninline int randInt(int l, int r) {\n    return l + (xorshift32() % (r - l + 1));\n}\ninline double randDouble() {\n    // 24\u2010bit uniform\n    return (xorshift32() & 0xFFFFFF) / double(1<<24);\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const double TL = 2.95;     // leave a small margin\n    const int N = 20;\n    int M;\n    cin >> M;\n    vector<string> s(M);\n    for(int i = 0; i < M; i++){\n        cin >> s[i];\n    }\n    // convert strings to 0..7\n    vector<vector<int>> sChars(M);\n    for(int i = 0; i < M; i++){\n        int L = s[i].size();\n        sChars[i].resize(L);\n        for(int j = 0; j < L; j++){\n            sChars[i][j] = s[i][j] - 'A';\n        }\n    }\n\n    // Build all placements\n    struct Placement {\n        int si;\n        int len;\n        vector<int> coord; // (i,j) pairs flattened: coord[2*p],coord[2*p+1]\n    };\n    vector<Placement> placements;\n    placements.reserve(M * 2 * N);\n    const int CELL = N * N;\n    vector<vector<int>> byCell(CELL);\n    for(int c = 0; c < CELL; c++){\n        byCell[c].reserve(600);\n    }\n\n    for(int si = 0; si < M; si++){\n        int L = sChars[si].size();\n        for(int dir = 0; dir < 2; dir++){ // 0=H,1=V\n            for(int x = 0; x < N; x++){\n                for(int st = 0; st < N; st++){\n                    Placement P;\n                    P.si = si;\n                    P.len = L;\n                    P.coord.resize(2 * L);\n                    for(int p = 0; p < L; p++){\n                        int i,j;\n                        if(dir == 0){\n                            i = x;\n                            j = (st + p) % N;\n                        } else {\n                            i = (st + p) % N;\n                            j = x;\n                        }\n                        P.coord[2*p] = i;\n                        P.coord[2*p+1] = j;\n                    }\n                    int pid = placements.size();\n                    placements.push_back(move(P));\n                    // index into byCell\n                    auto &C = placements.back().coord;\n                    for(int p = 0; p < placements.back().len; p++){\n                        int i = C[2*p], j = C[2*p+1];\n                        byCell[i*N + j].push_back(pid);\n                    }\n                }\n            }\n        }\n    }\n\n    int Pn = placements.size();\n\n    // current grid as ints 0..7\n    vector<int> grid(CELL);\n    vector<int> bestGrid(CELL);\n\n    // valid flags for placements\n    vector<char> valid(Pn, 0);\n    // match count per string\n    vector<int> matchCount(M, 0);\n\n    // initialize grid randomly\n    for(int i = 0; i < CELL; i++){\n        grid[i] = randInt(0,7);\n    }\n    // compute initial valid[] and matchCount[]\n    for(int pid = 0; pid < Pn; pid++){\n        auto &P = placements[pid];\n        bool ok = true;\n        for(int p = 0; p < P.len; p++){\n            int i = P.coord[2*p], j = P.coord[2*p+1];\n            if(grid[i*N+j] != sChars[P.si][p]){\n                ok = false;\n                break;\n            }\n        }\n        if(ok){\n            valid[pid] = 1;\n            matchCount[P.si]++;\n        }\n    }\n    int curC = 0;\n    for(int i = 0; i < M; i++) if(matchCount[i] > 0) curC++;\n    int bestC = curC;\n    bestGrid = grid;\n\n    // buffers for delta computations\n    vector<pair<int,char>> changed; changed.reserve(1000);\n    vector<int> sis; sis.reserve(1000);\n    vector<int> oldMatch(M);\n    vector<char> seen(M,0);\n\n    auto start = chrono::steady_clock::now();\n    int iter = 0;\n    const double T0 = 5.0, T1 = 0.1;\n\n    while(true){\n        iter++;\n        if((iter & 511) == 0){\n            auto now = chrono::steady_clock::now();\n            double t = chrono::duration<double>(now - start).count();\n            if(t > TL) break;\n        }\n        // temperature\n        auto now = chrono::steady_clock::now();\n        double t = chrono::duration<double>(now - start).count() / TL;\n        if(t > 1.0) t = 1.0;\n        double T = T0 + (T1 - T0) * t;\n\n        // pick a random cell\n        int c = randInt(0, CELL-1);\n        int oldL = grid[c];\n        int newL = randInt(0,7);\n        if(newL == oldL) continue;\n\n        changed.clear();\n        sis.clear();\n        int newC = curC;\n\n        int ci = c / N, cj = c % N;\n\n        // try the change\n        for(int pid : byCell[c]){\n            auto &P = placements[pid];\n            int si = P.si;\n            bool prev = valid[pid];\n            bool nowv = true;\n            // check validity if we change this cell to newL\n            for(int p = 0; p < P.len; p++){\n                int ii = P.coord[2*p], jj = P.coord[2*p+1];\n                int gv = (ii==ci && jj==cj ? newL : grid[ii*N+jj]);\n                if(gv != sChars[si][p]){\n                    nowv = false;\n                    break;\n                }\n            }\n            if(prev != nowv){\n                changed.emplace_back(pid, prev);\n                if(!seen[si]){\n                    seen[si] = 1;\n                    sis.push_back(si);\n                    oldMatch[si] = matchCount[si];\n                }\n                if(prev){\n                    matchCount[si]--;\n                    if(oldMatch[si] > 0 && matchCount[si] == 0) newC--;\n                } else {\n                    matchCount[si]++;\n                    if(oldMatch[si] == 0 && matchCount[si] == 1) newC++;\n                }\n                valid[pid] = nowv;\n            }\n        }\n\n        int delta = newC - curC;\n        bool accept = false;\n        if(delta >= 0) accept = true;\n        else {\n            double p = exp(delta / T);\n            if(randDouble() < p) accept = true;\n        }\n\n        if(accept){\n            grid[c] = newL;\n            curC = newC;\n            if(curC > bestC){\n                bestC = curC;\n                bestGrid = grid;\n            }\n        } else {\n            // revert\n            for(auto &pc : changed){\n                valid[pc.first] = pc.second;\n            }\n            for(int si : sis){\n                matchCount[si] = oldMatch[si];\n            }\n        }\n        for(int si : sis) seen[si] = 0;\n    }\n\n    // output bestGrid\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            char ch = char('A' + bestGrid[i*N+j]);\n            cout << ch;\n        }\n        cout << \"\\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    cin >> N >> si >> sj;\n    vector<string> C(N);\n    for(int i = 0; i < N; i++) {\n        cin >> C[i];\n    }\n\n    // 1) Assign an ID [0..r-1] to each road cell, record its cost and position.\n    vector<int> id_map(N*N, -1);\n    vector<pair<int,int>> id2pos;\n    vector<int> id2cost;\n    id2pos.reserve(N*N);\n    id2cost.reserve(N*N);\n\n    int r = 0;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(C[i][j] != '#'){\n                id_map[i*N + j] = r++;\n                id2pos.emplace_back(i, j);\n                id2cost.push_back(C[i][j] - '0');\n            }\n        }\n    }\n    int startId = id_map[si*N + sj];\n\n    // 2) Build the adjacency graph (undirected) with symmetric weights w(u,v)=cost[u]+cost[v].\n    vector<vector<pair<int,int>>> graph(r);\n    const int di[4] = {-1,1,0,0}, dj[4] = {0,0,-1,1};\n    for(int u = 0; u < r; u++){\n        auto [i, j] = id2pos[u];\n        int cu = id2cost[u];\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            int v = id_map[ni*N + nj];\n            if(v < 0) continue; // obstacle\n            int cv = id2cost[v];\n            int wuv = cu + cv;\n            graph[u].emplace_back(v, wuv);\n        }\n    }\n\n    // 3) Prim's MST on that graph, starting from startId\n    const int INF = 1e9;\n    vector<int> key(r, INF), parent(r, -1);\n    vector<bool> inMST(r, false);\n    key[startId] = 0;\n    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq;\n    pq.push({0, startId});\n\n    while(!pq.empty()){\n        auto [cw, u] = pq.top(); pq.pop();\n        if(inMST[u] || cw != key[u]) continue;\n        inMST[u] = true;\n        for(auto &e : graph[u]){\n            int v = e.first, wuv = e.second;\n            if(!inMST[v] && wuv < key[v]){\n                key[v] = wuv;\n                parent[v] = u;\n                pq.push({wuv, v});\n            }\n        }\n    }\n\n    // 4) Build the tree adjacency from parent[]\n    vector<vector<int>> treeAdj(r);\n    for(int v = 0; v < r; v++){\n        int u = parent[v];\n        if(u >= 0){\n            treeAdj[u].push_back(v);\n            treeAdj[v].push_back(u);\n        }\n    }\n\n    // 5) DFS/Euler tour to output the moves\n    string ans;\n    ans.reserve(2*(r-1) + 10);\n    auto opposite = [&](char c){\n        if(c=='U') return 'D';\n        if(c=='D') return 'U';\n        if(c=='L') return 'R';\n        return 'L';\n    };\n\n    function<void(int,int)> dfs = [&](int u, int p){\n        auto [ui, uj] = id2pos[u];\n        for(int v: treeAdj[u]){\n            if(v == p) continue;\n            auto [vi, vj] = id2pos[v];\n            char mv;\n            if(vi == ui-1 && vj == uj) mv = 'U';\n            else if(vi == ui+1 && vj == uj) mv = 'D';\n            else if(vi == ui && vj == uj-1) mv = 'L';\n            else if(vi == ui && vj == uj+1) mv = 'R';\n            else mv = 'U'; // (should not happen)\n            ans.push_back(mv);\n            dfs(v, u);\n            ans.push_back(opposite(mv));\n        }\n    };\n\n    dfs(startId, -1);\n\n    // 6) Print the move sequence\n    //    (It automatically returns to start at the end of the Euler tour.)\n    cout << ans << \"\\n\";\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Interactive greedy scheduler: critical\u2010path first, ignore skill estimation.\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    vector<vector<int>> d(N, vector<int>(K));\n    for(int i = 0; i < N; i++)\n        for(int j = 0; j < K; j++)\n            cin >> d[i][j];\n\n    vector<vector<int>> adj(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        adj[u].push_back(v);\n        indeg[v]++;\n    }\n\n    // Precompute for each task:\n    //  depth[i] = 1 + max depth over children\n    //  sumd[i] = sum of d[i][*]\n    vector<int> depth(N, -1), sumd(N,0);\n    for(int i = 0; i < N; i++){\n        int s = 0;\n        for(int x : d[i]) s += x;\n        sumd[i] = s;\n    }\n    function<int(int)> dfs = [&](int u){\n        if(depth[u] >= 0) return depth[u];\n        int best = 0;\n        for(int v : adj[u]){\n            best = max(best, dfs(v));\n        }\n        return depth[u] = best + 1;\n    };\n    for(int i = 0; i < N; i++){\n        if(depth[i] < 0) dfs(i);\n    }\n\n    // Ready\u2010task priority queue: by (depth desc, sumd desc, task id asc)\n    struct Task{\n        int d, sd, id;\n    };\n    struct Cmp{\n        bool operator()(Task const &a, Task const &b) const {\n            if(a.d != b.d) return a.d < b.d;\n            if(a.sd != b.sd) return a.sd < b.sd;\n            return a.id > b.id;\n        }\n    };\n    priority_queue<Task, vector<Task>, Cmp> pq;\n    for(int i = 0; i < N; i++){\n        if(indeg[i] == 0){\n            pq.push({depth[i], sumd[i], i});\n        }\n    }\n\n    // Track worker states\n    vector<int> assigned_task(M, -1);\n    vector<bool> worker_free(M, true);\n    vector<int> free_list;\n    free_list.reserve(M);\n    for(int j = 0; j < M; j++)\n        free_list.push_back(j);\n\n    vector<bool> done(N,false), started(N,false);\n\n    // Main interactive loop: day by day until judge sends -1\n    while(true){\n        // Assign as many as possible this morning\n        vector<pair<int,int>> assigns;\n        while(!free_list.empty() && !pq.empty()){\n            int w = free_list.back(); free_list.pop_back();\n            auto t = pq.top(); pq.pop();\n            int ti = t.id;\n            // assign worker w -> task ti\n            assigns.emplace_back(w, ti);\n            assigned_task[w] = ti;\n            worker_free[w] = false;\n            started[ti] = true;\n        }\n        // Output\n        cout << assigns.size();\n        for(auto &pr : assigns){\n            cout << \" \" << (pr.first+1) << \" \" << (pr.second+1);\n        }\n        cout << \"\\n\";\n        cout.flush();\n\n        // Read who finished at end of today\n        int cnt;\n        if(!(cin >> cnt)) return 0;\n        if(cnt == -1){\n            // all done or time up\n            break;\n        }\n        if(cnt > 0){\n            for(int i = 0; i < cnt; i++){\n                int f; \n                cin >> f;\n                int w = f-1;\n                int ti = assigned_task[w];\n                // free worker\n                worker_free[w] = true;\n                assigned_task[w] = -1;\n                free_list.push_back(w);\n                // mark task done\n                if(ti >= 0 && !done[ti]){\n                    done[ti] = true;\n                    for(int nxt : adj[ti]){\n                        if(--indeg[nxt] == 0 && !started[nxt])\n                            pq.push({depth[nxt], sumd[nxt], nxt});\n                    }\n                }\n            }\n        }\n        // else cnt==0: no one finished today; just go to next day\n    }\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\n#include <chrono>\nusing namespace std;\nusing ll = long long;\n\nint manh(int x1,int y1,int x2,int y2){\n    return abs(x1-x2)+abs(y1-y2);\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // 1) Read input\n    struct Order{int a,b,c,d,dist;};\n    vector<Order> ord(1000);\n    for(int i=0;i<1000;i++){\n        cin>>ord[i].a>>ord[i].b>>ord[i].c>>ord[i].d;\n        ord[i].dist = manh(ord[i].a,ord[i].b,ord[i].c,ord[i].d);\n    }\n\n    // 2) Select 50 orders with smallest internal distance\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 ord[i].dist < ord[j].dist; });\n    idx.resize(50);\n    // Now idx[0..49] are our selected order\u2010indices (unsorted).\n\n    // 3) Build cost matrices for the 50 nodes numbered 0..49\n    const int M = 50;\n    vector<int> sel = idx; // sel[k] = original order index\n    // Precompute coordinates\n    vector<int> px(M), py(M), dx(M), dy(M);\n    for(int i=0;i<M;i++){\n        px[i]=ord[sel[i]].a;\n        py[i]=ord[sel[i]].b;\n        dx[i]=ord[sel[i]].c;\n        dy[i]=ord[sel[i]].d;\n    }\n    // start/end costs\n    vector<int> start_cost(M), end_cost(M);\n    for(int i=0;i<M;i++){\n        start_cost[i]=manh(400,400,px[i],py[i]);\n        end_cost[i]  =manh(dx[i],dy[i],400,400);\n    }\n    // transition cost\n    static int trans[50][50];\n    for(int i=0;i<M;i++){\n        for(int j=0;j<M;j++){\n            trans[i][j]=manh(dx[i],dy[i],px[j],py[j]);\n        }\n    }\n\n    // 4) Multi\u2010start greedy to get an initial permutation\n    vector<int> order_by_start(M);\n    iota(order_by_start.begin(), order_by_start.end(), 0);\n    sort(order_by_start.begin(), order_by_start.end(),\n         [&](int i,int j){ return start_cost[i]<start_cost[j]; });\n\n    ll best_cost = LLONG_MAX;\n    vector<int> best_path;\n\n    for(int s=0; s<min(10,M); s++){\n        int st = order_by_start[s];\n        vector<char> used(M,false);\n        vector<int> path;\n        path.reserve(M);\n        path.push_back(st);\n        used[st]=1;\n        int cur=st;\n        // greedy nearest\u2010neighbor\n        for(int step=1;step<M;step++){\n            int best_j=-1, best_c=INT_MAX;\n            for(int j=0;j<M;j++){\n                if(!used[j]){\n                    int c = trans[cur][j];\n                    if(c<best_c){\n                        best_c=c;\n                        best_j=j;\n                    }\n                }\n            }\n            path.push_back(best_j);\n            used[best_j]=1;\n            cur=best_j;\n        }\n        // compute its cost\n        ll cost = start_cost[path[0]];\n        for(int i=0;i+1<M;i++) cost += trans[path[i]][path[i+1]];\n        cost += end_cost[path[M-1]];\n        if(cost<best_cost){\n            best_cost=cost;\n            best_path=path;\n        }\n    }\n\n    // 5) Asymmetric 2\u2010opt on best_path\n    auto t_start = chrono::steady_clock::now();\n    ll cur_cost = best_cost;\n    vector<int> &P = best_path;\n    const double TIME_LIMIT = 1.9; // sec\n    while(true){\n        auto t_now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(t_now - t_start).count();\n        if(elapsed > TIME_LIMIT) break;\n\n        bool improved=false;\n        // positions 0..M-1 in P; keep P[0] fixed as start\n        for(int i=1;i<M-1 && !improved;i++){\n            int A = P[i-1], B = P[i];\n            int orig1 = trans[A][B];\n            for(int j=i+1;j<M && !improved;j++){\n                int C = P[j];\n                int D = (j+1<M ? P[j+1] : -1);\n                int orig2 = (D>=0 ? trans[C][D] : end_cost[C]);\n                int new1  = trans[A][C];\n                int new2  = (D>=0 ? trans[B][D] : end_cost[B]);\n                int delta = (new1 + new2) - (orig1 + orig2);\n                if(delta<0){\n                    // apply reversal of segment [i..j]\n                    reverse(P.begin()+i, P.begin()+j+1);\n                    cur_cost += delta;\n                    improved = true;\n                }\n            }\n        }\n        if(!improved) break;\n    }\n\n    // 6) Output\n    // First line: m = 50, r_1..r_50 (1-based original order indices)\n    cout<<M;\n    for(int id:P){\n        cout<<\" \"<<(sel[id]+1);\n    }\n    cout<<\"\\n\";\n\n    // Second line: the route length n and the coordinates\n    // We do: (400,400) \u2192 [pickup,delivery]\u00d750 in best_path order \u2192 (400,400)\n    vector<pair<int,int>> route;\n    route.reserve(2*M+2);\n    route.emplace_back(400,400);\n    for(int id:P){\n        route.emplace_back(px[id], py[id]);\n        route.emplace_back(dx[id], dy[id]);\n    }\n    route.emplace_back(400,400);\n\n    cout<<route.size();\n    for(auto &pt:route){\n        cout<<\" \"<<pt.first<<\" \"<<pt.second;\n    }\n    cout<<\"\\n\";\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Disjoint\u2010set union (union by rank + path compression)\nstruct DSU {\n    int n;\n    vector<int> p, r;\n    DSU(int _n): n(_n), p(n,-1), r(n,0) {\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        return p[x]==x ? x : 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    vector<pair<int,int>> coord(N);\n    for(int i = 0; i < N; i++){\n        cin >> coord[i].first >> coord[i].second;\n    }\n    struct Edge { int u,v,id; int d; };\n    vector<Edge> edges;\n    edges.reserve(M);\n    for(int i = 0; i < M; i++){\n        int u,v;\n        cin >> u >> v;\n        int dx = coord[u].first  - coord[v].first;\n        int dy = coord[u].second - coord[v].second;\n        // rounded Euclidean distance\n        int di = int( round( sqrt(double(dx*dx + dy*dy)) ) );\n        edges.push_back({u,v,i,di});\n    }\n\n    // Kruskal on weights = d_i\n    vector<bool> choose(M,false);\n    DSU dsu(N);\n    sort(edges.begin(), edges.end(),\n         [&](auto &A, auto &B){\n             return A.d < B.d;\n         });\n    int taken = 0;\n    for(auto &e: edges){\n        if(taken == N-1) break;\n        if(dsu.unite(e.u, e.v)){\n            choose[e.id] = true;\n            taken++;\n        }\n    }\n    // Now process the stream\n    for(int i = 0; i < M; i++){\n        int l;\n        if(!(cin >> l)) return 0;  // safety\n        if(choose[i]){\n            cout << 1 << '\\n';\n        } else {\n            cout << 0 << '\\n';\n        }\n        cout.flush();  // must flush after each decision\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    vector<int> px(N), py(N), pt(N);\n    for(int i = 0; i < N; i++){\n        cin >> px[i] >> py[i] >> pt[i];\n    }\n    int M;\n    cin >> M;\n    vector<int> hx(M), hy(M);\n    for(int i = 0; i < M; i++){\n        cin >> hx[i] >> hy[i];\n    }\n\n    const int TURNS = 300;\n    string action(M, '.');\n    for(int turn = 0; turn < TURNS; turn++){\n        // 1) Output M actions: here we do nothing for all humans\n        cout << action << \"\\n\" << flush;\n\n        // 2) Read N pet\u2010movement strings (we ignore them)\n        for(int i = 0; i < N; i++){\n            string mv;\n            cin >> mv;\n        }\n        // repeat\n    }\n    return 0;\n}","ahc009":"#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,ti,tj;\n    double p;\n    cin>>si>>sj>>ti>>tj>>p;\n    vector<string> h(20), v(19);\n    for(int i=0;i<20;i++) cin>>h[i];\n    for(int i=0;i<19;i++) cin>>v[i];\n\n    // BFS\n    static int dist[20][20];\n    static int pi_[20][20], pj_[20][20];\n    static char pm_[20][20];\n    for(int i=0;i<20;i++) for(int j=0;j<20;j++) dist[i][j]=1e9;\n    queue<pair<int,int>> q;\n    dist[si][sj]=0;\n    q.push({si,sj});\n    // dir order: U,D,L,R\n    int dx[4]={-1,1,0,0}, dy[4]={0,0,-1,1};\n    char dc[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        for(int d=0;d<4;d++){\n            int ni=i+dx[d], nj=j+dy[d];\n            bool ok=false;\n            if(d==0){\n                if(i>=1 && v[i-1][j]=='0') ok=true;\n            } else if(d==1){\n                if(i<=18 && v[i][j]=='0') ok=true;\n            } else if(d==2){\n                if(j>=1 && h[i][j-1]=='0') ok=true;\n            } else {\n                if(j<=18 && h[i][j]=='0') ok=true;\n            }\n            if(!ok) continue;\n            if(dist[ni][nj]>dist[i][j]+1){\n                dist[ni][nj]=dist[i][j]+1;\n                pi_[ni][nj]=i;\n                pj_[ni][nj]=j;\n                pm_[ni][nj]=dc[d];\n                q.push({ni,nj});\n            }\n        }\n    }\n\n    // Reconstruct path\n    vector<char> path;\n    int ci=ti, cj=tj;\n    while(!(ci==si && cj==sj)){\n        char c = pm_[ci][cj];\n        path.push_back(c);\n        int ti2 = pi_[ci][cj], tj2 = pj_[ci][cj];\n        ci=ti2; cj=tj2;\n    }\n    reverse(path.begin(), path.end());\n    int D = path.size();\n    if(D==0){\n        // Already at office: just output a dummy move\n        cout<<\"U\\n\";\n        return 0;\n    }\n\n    // Choose repetition factor k\n    int k_cap = 200 / D;\n    if(k_cap<=0) k_cap=1;\n    // want p^k <= 0.1  =>  k >= log(0.1)/log(p)\n    double thresh = 0.1;\n    double tmp = log(thresh) / log(p);\n    int k_base = (int)ceil(tmp);\n    if(k_base<1) k_base=1;\n    int k = min(k_base, k_cap);\n\n    // Output each direction k times\n    string out;\n    out.reserve(D*k);\n    for(char c:path){\n        for(int i=0;i<k;i++) out.push_back(c);\n    }\n    cout<<out<<\"\\n\";\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Directions: 0=left,1=up,2=right,3=down\nint di[4] = {0, -1, 0, 1};\nint dj[4] = {-1, 0, 1, 0};\n// opposite direction\ninline int opp(int d){ return (d+2)&3; }\n\n// to[s][d] = exit direction if we enter tile-state s from direction d,\n// or -1 if no track there.\nint to_dir[8][4] = {\n    {1,0,-1,-1},\n    {3,-1,-1,0},\n    {-1,-1,3,2},\n    {-1,2,1,-1},\n    {1,0,3,2},\n    {3,2,1,0},\n    {2,-1,0,-1},\n    {-1,3,-1,1}\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // Read input: 30 lines of 30 characters each\n    vector<vector<int>> orig(30, vector<int>(30));\n    for(int i = 0; i < 30; i++){\n        string s;\n        cin >> s;\n        for(int j = 0; j < 30; j++){\n            orig[i][j] = s[j] - '0';\n        }\n    }\n\n    // Precompute for each state s the set of open directions\n    // openDirs[s] is a bitmask: bit d set if tile-state s has an open end on side d.\n    array<int,8> openMask = {0};\n    for(int s = 0; s < 8; s++){\n        int m = 0;\n        for(int d = 0; d < 4; d++){\n            if(to_dir[s][d] != -1){\n                m |= (1 << d);\n                // also the exit side is open but it's redundant since\n                // if we enter from d we exit on to_dir[s][d] so that side\n                // automatically shows up when we consider d = to_dir[s][d].\n            }\n        }\n        openMask[s] = m;\n    }\n\n    // Rotation mapping: state of tile after r CCW-rotations.\n    // r in {0,1,2,3}\n    auto rotateState = [&](int s, int r){\n        if(s < 4){\n            // single curve: just add r mod 4\n            return (s + r) & 3;\n        } else if(s < 6){\n            // double curves: 4<->5 alternate\n            if(r & 1) return 5 - (s-4);\n            else      return s;\n        } else {\n            // straights: 6<->7 alternate\n            if(r & 1) return 13 - s; // 6->7,7->6\n            else      return s;\n        }\n    };\n\n    // Current rotation counts\n    static int rot[30][30];\n    for(int i = 0; i < 30; i++)\n        for(int j = 0; j < 30; j++)\n            rot[i][j] = 0;\n\n    // Greedy sweeps\n    const int MAX_PASSES = 20;\n    for(int pass = 0; pass < MAX_PASSES; pass++){\n        bool changed = false;\n        for(int i = 0; i < 30; i++){\n            for(int j = 0; j < 30; j++){\n                int bestR = rot[i][j];\n                // compute score for current orientation\n                int curState = rotateState(orig[i][j], bestR);\n                int bestScore = 0;\n                // We can precompute current score, but recomputing is cheap:\n                {\n                    int m = openMask[curState];\n                    int sc = 0;\n                    for(int d = 0; d < 4; d++){\n                        if(m & (1 << d)){\n                            int ni = i + di[d], nj = j + dj[d];\n                            if(ni >= 0 && ni < 30 && nj >= 0 && nj < 30){\n                                int neighState = rotateState(orig[ni][nj], rot[ni][nj]);\n                                if(openMask[neighState] & (1 << opp(d)))\n                                    sc++;\n                            } else {\n                                // penalize open edge at boundary\n                                sc--;\n                            }\n                        }\n                    }\n                    bestScore = sc;\n                }\n                // try all 4 rotations\n                for(int r = 0; r < 4; r++){\n                    if(r == bestR) continue;\n                    int s = rotateState(orig[i][j], r);\n                    int m = openMask[s];\n                    int sc = 0;\n                    for(int d = 0; d < 4; d++){\n                        if(m & (1 << d)){\n                            int ni = i + di[d], nj = j + dj[d];\n                            if(ni >= 0 && ni < 30 && nj >= 0 && nj < 30){\n                                int neighState = rotateState(orig[ni][nj], rot[ni][nj]);\n                                if(openMask[neighState] & (1 << opp(d)))\n                                    sc++;\n                            } else {\n                                sc--;\n                            }\n                        }\n                    }\n                    if(sc > bestScore){\n                        bestScore = sc;\n                        bestR = r;\n                    }\n                }\n                if(bestR != rot[i][j]){\n                    rot[i][j] = bestR;\n                    changed = true;\n                }\n            }\n        }\n        if(!changed) break;\n    }\n\n    // Output the 900-character string\n    // flatten row-major\n    string out;\n    out.reserve(900);\n    for(int i = 0; i < 30; i++){\n        for(int j = 0; j < 30; j++){\n            out.push_back(char('0' + rot[i][j]));\n        }\n    }\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, T;\n    cin >> N >> T;\n    vector<string> grid(N);\n    for(int i = 0; i < N; i++){\n        cin >> grid[i];\n    }\n\n    // Baseline: perform zero moves.\n    // This is always legal (K = 0 <= T), so we get score = round(500000 * S/(N^2-1)),\n    // where S is computed on the input position.\n    // A real submission would implement a heuristic here.\n    cout << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, K;\n    cin >> N >> K;\n    vector<int> a(11);\n    for(int d = 1; d <= 10; d++){\n        cin >> a[d];\n    }\n    vector<pair<int,int>> P(N);\n    vector<bool> xmark(20001,false), ymark(20001,false);\n    const int OFF = 10000;\n    for(int i = 0; i < N; i++){\n        int x,y;\n        cin >> x >> y;\n        P[i] = {x,y};\n        if(x >= -10000 && x <= 10000) xmark[x + OFF] = true;\n        if(y >= -10000 && y <= 10000) ymark[y + OFF] = true;\n    }\n\n    // We'll pick 49 vertical and 49 horizontal lines.\n    vector<int> vx, vy;\n    auto pick_lines = [&](bool vertical, int cnt, vector<bool> &mark, vector<int> &out){\n        // We want roughly equally spaced lines in [-10000,10000]:\n        // initial target positions: -10000 + j*(20000/cnt) for j=1..cnt-1\n        int steps = cnt;\n        for(int j = 1; j < steps; j++){\n            // target = -10000 + j * (20000/steps)\n            double raw = -10000.0 + (20000.0 * j) / steps;\n            int target = int(round(raw));\n            // now shift until we find an integer not marked\n            int found = target;\n            for(int delta = 0; delta <= 20000; delta++){\n                // try target - delta, then target + delta\n                int cands[2] = { target - delta, target + delta };\n                for(int t = 0; t < 2; t++){\n                    int c = cands[t];\n                    if(c < -10000 || c > 10000) continue;\n                    if(mark[c + OFF]) continue;         // hits a strawberry\n                    // also avoid duplicate lines\n                    bool dup = false;\n                    for(int x: out) if(x == c) { dup = true; break; }\n                    if(dup) continue;\n                    found = c;\n                    goto GOT;\n                }\n            }\n        GOT:\n            out.push_back(found);\n        }\n    };\n\n    pick_lines(true, 50, xmark, vx);   // 49 vertical\n    pick_lines(false, 50, ymark, vy);  // 49 horizontal\n\n    int k = vx.size() + vy.size();\n    if(k > K) k = K; // safety, though we expect 98<=100\n\n    cout << k << \"\\n\";\n    // vertical: x = c\n    for(int i = 0; i < (int)vx.size() && i < k; i++){\n        ll c = vx[i];\n        // line through (c,-20000)\u2013(c,20000)\n        cout << c << \" \" << -20000 << \" \" << c << \" \" << 20000 << \"\\n\";\n    }\n    // horizontal: y = c\n    int rem = k - (int)vx.size();\n    for(int i = 0; i < rem; i++){\n        ll c = vy[i];\n        // line through (-20000,c)\u2013(20000,c)\n        cout << -20000 << \" \" << c << \" \" << 20000 << \" \" << c << \"\\n\";\n    }\n\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\n// A single operation: we place a new dot at (x1,y1), using existing dots\n// at (x2,y2),(x3,y3),(x4,y4) in that cyclic order.\nstruct Op { \n    int x1,y1, x2,y2, x3,y3, x4,y4; \n};\n\nint N, M;\nstatic bool dotp[65][65];\nstatic bool used_h[65][65], used_v[65][65];\n// Precompute the weight of each grid point\nstatic long long wgt[65][65];\n\n// Check whether the rectangle p1->p2->p3->p4 is a valid axis-aligned\n// rectangle: no other dots on its perimeter and no previously used edges.\nbool validate_rect(int x1,int y1,int x2,int y2,int x3,int y3,int x4,int y4){\n    // We assume (p1,p2,p3,p4) go around the rectangle in order.\n    int xs[4] = {x1,x2,x3,x4}, ys[4] = {y1,y2,y3,y4};\n    for(int i=0;i<4;i++){\n        int j=(i+1)&3;\n        int sx=xs[i], sy=ys[i], ex=xs[j], ey=ys[j];\n        if(sx==ex){\n            // vertical side\n            int x = sx;\n            int y0 = min(sy,ey), y1 = max(sy,ey);\n            // no used edge\n            for(int y=y0; y<y1; y++){\n                if(used_v[y][x]) return false;\n            }\n            // no other dots on interior points\n            for(int y=y0+1; y<y1; y++){\n                if(dotp[x][y]) return false;\n            }\n        } else if(sy==ey){\n            // horizontal side\n            int y = sy;\n            int x0 = min(sx,ex), x1 = max(sx,ex);\n            for(int x=x0; x<x1; x++){\n                if(used_h[y][x]) return false;\n            }\n            for(int x=x0+1; x<x1; x++){\n                if(dotp[x][y]) return false;\n            }\n        } else {\n            // not axis-aligned\n            return false;\n        }\n    }\n    return true;\n}\n\n// After we choose a rectangle, mark its 4 sides' unit-edges as used.\nvoid mark_rect(int x1,int y1,int x2,int y2,int x3,int y3,int x4,int y4){\n    int xs[4] = {x1,x2,x3,x4}, ys[4] = {y1,y2,y3,y4};\n    for(int i=0;i<4;i++){\n        int j=(i+1)&3;\n        int sx=xs[i], sy=ys[i], ex=xs[j], ey=ys[j];\n        if(sx==ex){\n            int x=sx, y0=min(sy,ey), y1=max(sy,ey);\n            for(int y=y0; y<y1; y++){\n                used_v[y][x] = true;\n            }\n        } else {\n            int y=sy, x0=min(sx,ex), x1=max(sx,ex);\n            for(int x=x0; x<x1; x++){\n                used_h[y][x] = true;\n            }\n        }\n    }\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M;\n    vector<pair<int,int>> E;\n    E.reserve(N*N);\n\n    for(int i=0;i<M;i++){\n        int x,y; cin >> x >> y;\n        dotp[x][y] = true;\n        E.emplace_back(x,y);\n    }\n\n    // center coordinate\n    int C = (N-1)/2;\n    // precompute weights\n    for(int x=0;x<N;x++){\n        for(int y=0;y<N;y++){\n            long long dx = x - C, dy = y - C;\n            wgt[x][y] = dx*dx + dy*dy + 1;\n        }\n    }\n\n    // Random engine\n    mt19937_64 rng(1234567);\n\n    // record operations\n    vector<Op> ops;\n    ops.reserve(N*N);\n\n    // time\u2010limit guard\n    clock_t start = clock();\n    const double TL = 4.8;  // leave a small margin\n\n    while(true){\n        double used = double(clock() - start)/CLOCKS_PER_SEC;\n        if(used > TL) break;\n        int Esz = (int)E.size();\n        if(Esz < 2) break;\n\n        // sample up to T random diagonals per iteration\n        int T = min(1000, Esz*2);\n        long long bestW = -1;\n        Op    bestOp{};\n\n        for(int t=0;t<T; t++){\n            if((t & 511)==0 && double(clock() - start)/CLOCKS_PER_SEC > TL)\n                break;\n\n            int i = rng() % Esz;\n            int j = rng() % Esz;\n            if(i==j) continue;\n            auto [x2,y2] = E[i];\n            auto [x4,y4] = E[j];\n            // must form a proper diagonal\n            if(x2==x4 || y2==y4) continue;\n\n            // option 1: missing corner p1 = (x4,y2), opposite p3=(x2,y4)\n            int x1 = x4, y1 = y2;\n            int x3 = x2, y3 = y4;\n            if(!dotp[x1][y1] && dotp[x3][y3]){\n                if(validate_rect(x1,y1, x2,y2, x3,y3, x4,y4)){\n                    long long W = wgt[x1][y1];\n                    if(W > bestW){\n                        bestW = W;\n                        bestOp = {x1,y1, x2,y2, x3,y3, x4,y4};\n                    }\n                }\n            }\n            // option 2: missing corner p1 = (x2,y4), opposite p3=(x4,y2)\n            int x1b = x2, y1b = y4;\n            int x3b = x4, y3b = y2;\n            if(!dotp[x1b][y1b] && dotp[x3b][y3b]){\n                if(validate_rect(x1b,y1b, x2,y2, x3b,y3b, x4,y4)){\n                    long long W = wgt[x1b][y1b];\n                    if(W > bestW){\n                        bestW = W;\n                        bestOp = {x1b,y1b, x2,y2, x3b,y3b, x4,y4};\n                    }\n                }\n            }\n        }\n\n        // if we found a valid rectangle, commit it\n        if(bestW >= 0){\n            auto &o = bestOp;\n            dotp[o.x1][o.y1] = true;\n            E.emplace_back(o.x1,o.y1);\n            mark_rect(o.x1,o.y1, o.x2,o.y2, o.x3,o.y3, o.x4,o.y4);\n            ops.push_back(o);\n        } else {\n            // no more valid sample\u2192stop\n            break;\n        }\n    }\n\n    // Output\n    cout << ops.size() << \"\\n\";\n    for(auto &o: ops){\n        cout\n          << o.x1 << \" \" << o.y1 << \" \"\n          << o.x2 << \" \" << o.y2 << \" \"\n          << o.x3 << \" \" << o.y3 << \" \"\n          << o.x4 << \" \" << o.y4 << \"\\n\";\n    }\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    // Read in the 100 flavors\n    vector<int> f(101);\n    for(int i = 1; i <= 100; i++){\n        cin >> f[i];\n    }\n\n    // For each turn t, read the random placement index p_t,\n    // then output our predetermined tilt for flavor f[t].\n    // We flush after each line to satisfy the interactive requirement.\n    for(int t = 1; t <= 100; t++){\n        int p;\n        if(!(cin >> p)) break;  // in case input ends\n        char out;\n        if(f[t] == 1)       out = 'L';\n        else if(f[t] == 2)  out = 'R';\n        else                out = 'F';\n        cout << out << '\\n' << flush;\n    }\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    // Baseline: choose N = 20\n    int N = 20;\n    int L = N*(N-1)/2;\n    cout << N << \"\\n\";\n\n    // Output G_k: a graph with exactly k edges in the lex order of (i<j)\n    for (int k = 0; k < M; k++) {\n        int ones = min(k, L);\n        cout << string(ones, '1') << string(L - ones, '0') << \"\\n\";\n    }\n    cout << flush;\n\n    // Process 100 queries\n    for (int qi = 0; qi < 100; qi++) {\n        string H;\n        cin >> H;\n        if (!cin) break;\n        // Count edges in H\n        int cnt = 0;\n        for (char c : H) if (c == '1') cnt++;\n        // Predict index = min(cnt, M-1)\n        int t = min(cnt, M - 1);\n        cout << t << \"\\n\" << flush;\n    }\n\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll INF = (ll)4e18;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n    vector<int> U(M), V(M);\n    vector<ll> 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    // skip coordinates\n    for(int i = 0; i < N; i++){\n        int x,y;\n        cin >> x >> y;\n    }\n\n    // build adjacency\n    vector<vector<pair<int,int>>> adj(N);\n    adj.reserve(N);\n    for(int e = 0; e < M; e++){\n        adj[U[e]].push_back({V[e], e});\n        adj[V[e]].push_back({U[e], e});\n    }\n\n    // sample B sources for Brandes\n    int B = 50;\n    B = min(B, N);\n    vector<int> vs(N);\n    iota(vs.begin(), vs.end(), 0);\n    mt19937 rng(12345);\n    shuffle(vs.begin(), vs.end(), rng);\n    vs.resize(B);\n\n    // edge centrality accumulator\n    vector<double> central(M, 0.0);\n\n    // Temporary structures for one run\n    vector<ll> dist(N);\n    vector<double> sigma(N), delta(N);\n    vector<vector<pair<int,int>>> pred(N);\n    vector<int> S; S.reserve(N);\n\n    // run Brandes\u2010style accumulation\n    for(int si = 0; si < B; si++){\n        int s = vs[si];\n        // init\n        fill(dist.begin(), dist.end(), INF);\n        fill(sigma.begin(), sigma.end(), 0.0);\n        for(int i = 0; i < N; i++){\n            pred[i].clear();\n        }\n        dist[s] = 0;\n        sigma[s] = 1.0;\n        S.clear();\n\n        // Dijkstra\n        using pli = pair<ll,int>;\n        priority_queue<pli, vector<pli>, greater<pli>> pq;\n        pq.push({0LL, s});\n\n        while(!pq.empty()){\n            auto [d,u] = pq.top(); pq.pop();\n            if(d != dist[u]) continue;\n            S.push_back(u);\n            for(auto &ed : adj[u]){\n                int v = ed.first;\n                int e = ed.second;\n                ll nd = d + W[e];\n                if(nd < dist[v]){\n                    dist[v] = nd;\n                    sigma[v] = sigma[u];\n                    pred[v].clear();\n                    pred[v].push_back({u, e});\n                    pq.push({nd, v});\n                } else if(nd == dist[v]){\n                    sigma[v] += sigma[u];\n                    pred[v].push_back({u, e});\n                }\n            }\n        }\n\n        // accumulation\n        fill(delta.begin(), delta.end(), 0.0);\n        for(int idx = (int)S.size() - 1; idx >= 0; idx--){\n            int w = S[idx];\n            for(auto &pp : pred[w]){\n                int v = pp.first;\n                int e = pp.second;\n                double c = (sigma[v] / sigma[w]) * (1.0 + delta[w]);\n                delta[v] += c;\n                central[e] += c;\n            }\n        }\n    }\n\n    // sort edges by descending centrality\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int a, int b){\n             return central[a] > central[b];\n         });\n\n    // assign days in round-robin\n    vector<int> ans(M);\n    for(int i = 0; i < M; i++){\n        int e = order[i];\n        ans[e] = (i % D) + 1;\n    }\n\n    // output\n    for(int i = 0; i < M; i++){\n        cout << ans[i] << (i+1<M ? ' ' : '\\n');\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(NULL);\n\n    int D;\n    cin >> D;\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for(int i = 0; i < D; i++) cin >> f1[i];\n    for(int i = 0; i < D; i++) cin >> r1[i];\n    for(int i = 0; i < D; i++) cin >> f2[i];\n    for(int i = 0; i < D; i++) cin >> r2[i];\n\n    int N = D*D*D;\n    vector<int> b1(N, 0), b2(N, 0);\n\n    // Helper to test if (x,y,z) is needed in silhouette i\n    auto need1 = [&](int x,int y,int z){\n        return (f1[z][x]=='1' && r1[z][y]=='1');\n    };\n    auto need2 = [&](int x,int y,int z){\n        return (f2[z][x]=='1' && r2[z][y]=='1');\n    };\n\n    int block_id = 0;\n    // First, assign all voxels needed in *both* shapes the same block\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(need1(x,y,z) && need2(x,y,z)){\n                    ++block_id;\n                    int idx = x*D*D + y*D + z;\n                    b1[idx] = block_id;\n                    b2[idx] = block_id;\n                }\n            }\n        }\n    }\n    // Next, voxels unique to shape 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(need1(x,y,z) && !need2(x,y,z)){\n                    ++block_id;\n                    int idx = x*D*D + y*D + z;\n                    b1[idx] = block_id;\n                }\n            }\n        }\n    }\n    // Finally, voxels unique to shape 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(need2(x,y,z) && !need1(x,y,z)){\n                    ++block_id;\n                    int idx = x*D*D + y*D + z;\n                    b2[idx] = block_id;\n                }\n            }\n        }\n    }\n\n    // Output\n    cout << block_id << \"\\n\";\n    for(int i = 0; i < N; i++){\n        cout << b1[i] << (i+1==N?'\\n':' ');\n    }\n    for(int i = 0; i < N; i++){\n        cout << b2[i] << (i+1==N?'\\n':' ');\n    }\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll INF = (1LL<<62);\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M, K;\n    cin >> N >> M >> K;\n    vector<ll> x(N), y(N);\n    for(int i = 0; i < N; i++){\n        cin >> x[i] >> y[i];\n    }\n    struct Edge{ int to; ll w; int id; };\n    vector<vector<Edge>> g(N);\n    vector<int> U(M), V(M);\n    vector<ll> W(M);\n    for(int j = 0; j < M; j++){\n        int u, v; ll w;\n        cin >> u >> v >> w;\n        --u; --v;\n        U[j]=u; V[j]=v; W[j]=w;\n        g[u].push_back({v,w,j});\n        g[v].push_back({u,w,j});\n    }\n    vector<ll> a(K), b(K);\n    for(int k = 0; k < K; k++){\n        cin >> a[k] >> b[k];\n    }\n\n    // 1) Assign each resident to nearest station\n    vector<ll> max_d2(N, 0);\n    for(int k = 0; k < K; k++){\n        ll best = LLONG_MAX;\n        int bi = 0;\n        for(int i = 0; i < N; i++){\n            ll dx = x[i]-a[k], dy = y[i]-b[k];\n            ll d2 = dx*dx + dy*dy;\n            if(d2 < best){\n                best = d2;\n                bi = i;\n            }\n        }\n        max_d2[bi] = max(max_d2[bi], best);\n    }\n\n    // 2) Set P[i] = ceil(sqrt(max_d2[i]))\n    vector<int> P(N,0);\n    for(int i = 0; i < N; i++){\n        if(max_d2[i] > 0){\n            ll d2 = max_d2[i];\n            ll s = (ll)floor(sqrt((long double)d2));\n            while(s*s < d2) s++;\n            while((s-1)*(s-1) >= d2) s--;\n            P[i] = (int)s;\n        }\n    }\n\n    // 3) Dijkstra from node 0 (station 1)\n    vector<ll> dist(N, INF);\n    vector<int> prev_v(N, -1), prev_e(N, -1);\n    dist[0] = 0;\n    priority_queue<pair<ll,int>, vector<pair<ll,int>>, greater<>> pq;\n    pq.push({0,0});\n    while(!pq.empty()){\n        auto [cd, u] = pq.top(); pq.pop();\n        if(cd > dist[u]) continue;\n        for(auto &ed : g[u]){\n            int v = ed.to; ll w = ed.w; int id = ed.id;\n            if(dist[v] > cd + w){\n                dist[v] = cd + w;\n                prev_v[v] = u;\n                prev_e[v] = id;\n                pq.push({dist[v], v});\n            }\n        }\n    }\n\n    // 4) Mark edges ON only on the paths needed to reach each i with P[i]>0\n    vector<int> B(M,0);\n    for(int i = 0; i < N; i++){\n        if(P[i] > 0){\n            int v = i;\n            while(v != 0){\n                int e = prev_e[v];\n                if(e < 0) break;\n                B[e] = 1;\n                v = prev_v[v];\n            }\n        }\n    }\n\n    // Output\n    for(int i = 0; i < N; i++){\n        cout << P[i] << (i+1<N?' ':'\\n');\n    }\n    for(int j = 0; j < M; j++){\n        cout << B[j] << (j+1<M?' ':'\\n');\n    }\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    const int N = 30;\n    const int M = N*(N+1)/2; // 465\n    vector<int> posBall(M), curPos(M);\n    // read input\n    for(int x=0, idx=0; x<N; x++){\n        for(int y=0; y<=x; y++, idx++){\n            int b; \n            cin >> b;\n            posBall[idx] = b;\n            curPos[b] = idx;\n        }\n    }\n    // build (x,y)<->id mappings\n    vector<pair<int,int>> id2xy(M);\n    auto xy2id = [&](int x,int y){\n        return x*(x+1)/2 + y;\n    };\n    for(int x=0, idx=0; x<N; x++){\n        for(int y=0; y<=x; y++, idx++){\n            id2xy[idx] = {x,y};\n        }\n    }\n    // adjacency lists on the triangular grid\n    vector<vector<int>> adj(M);\n    for(int id=0; id<M; id++){\n        auto [x,y] = id2xy[id];\n        if(x>0 && y>0)       adj[id].push_back(xy2id(x-1,y-1));\n        if(x>0 && y<=x-1)    adj[id].push_back(xy2id(x-1,y));\n        if(y>0)              adj[id].push_back(xy2id(x,y-1));\n        if(y< x)             adj[id].push_back(xy2id(x,y+1));\n        if(x+1< N)          {\n            adj[id].push_back(xy2id(x+1,y));\n            adj[id].push_back(xy2id(x+1,y+1));\n        }\n    }\n\n    vector<bool> locked(M,false), vis(M);\n    vector<int> parent(M);\n    struct Move { int x1,y1,x2,y2; };\n    vector<Move> moves;\n    moves.reserve(M * 12);\n\n    // for each label L=0..M-1, BFS in the subgraph { id>=L }\n    for(int L=0; L<M; L++){\n        int s = curPos[L];\n        int t = L; // target id = L\n        if(s!=t){\n            // BFS from s to t, only visiting id>=L\n            fill(vis.begin(), vis.end(), false);\n            fill(parent.begin(), parent.end(), -1);\n            queue<int> q;\n            q.push(s);\n            vis[s]=true;\n            while(!q.empty() && !vis[t]){\n                int u=q.front(); q.pop();\n                for(int v: adj[u]){\n                    if(vis[v]) continue;\n                    if(v< L) continue; // skip locked region\n                    vis[v]=true;\n                    parent[v]=u;\n                    q.push(v);\n                    if(v==t) break;\n                }\n            }\n            // reconstruct path s->...->t\n            vector<int> path;\n            int u = t;\n            while(u!=-1){\n                path.push_back(u);\n                if(u==s) break;\n                u = parent[u];\n            }\n            reverse(path.begin(), path.end());\n            // bubble L along that path\n            for(int i=1; i<int(path.size()); i++){\n                int u0=path[i-1], v0=path[i];\n                int A = posBall[u0], B = posBall[v0];\n                // swap them\n                posBall[u0]=B; posBall[v0]=A;\n                curPos[A]=v0;  curPos[B]=u0;\n                auto [x1,y1]=id2xy[u0];\n                auto [x2,y2]=id2xy[v0];\n                moves.push_back({x1,y1,x2,y2});\n            }\n        }\n        // lock the target cell so it never moves again\n        locked[t]=true;\n    }\n\n    // output\n    cout << moves.size() << \"\\n\";\n    for(auto &m: moves){\n        cout << m.x1 << \" \" << m.y1 << \" \"\n             << m.x2 << \" \" << m.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, N;\n    cin >> D >> N;\n    vector<vector<bool>> is_obstacle(D, vector<bool>(D,false));\n    for(int k = 0; k < N; k++){\n        int ri, rj;\n        cin >> ri >> rj;\n        is_obstacle[ri][rj] = true;\n    }\n    // Entrance\n    int ex = 0, ey = (D-1)/2;\n\n    // Precompute static BFS\u2010distances from entrance (ignoring containers)\n    const int dx[4] = {1,-1,0,0}, dy[4] = {0,0,1,-1};\n    vector<vector<int>> dist0(D, vector<int>(D, -1));\n    {\n        queue<pair<int,int>> q;\n        dist0[ex][ey] = 0;\n        q.push({ex,ey});\n        while(!q.empty()){\n            auto [x,y] = q.front(); q.pop();\n            for(int d=0;d<4;d++){\n                int nx = x+dx[d], ny=y+dy[d];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(is_obstacle[nx][ny]) continue;\n                if(dist0[nx][ny]!=-1) continue;\n                dist0[nx][ny] = dist0[x][y]+1;\n                q.push({nx,ny});\n            }\n        }\n    }\n    // Find maxDist over all non\u2010obstacle, non\u2010entrance cells\n    int maxDist = 0;\n    for(int i=0;i<D;i++)for(int j=0;j<D;j++){\n        if(is_obstacle[i][j]) continue;\n        if(i==ex && j==ey) continue;\n        maxDist = max(maxDist, dist0[i][j]);\n    }\n\n    int C = D*D - 1 - N;  // total containers\n    // occ== -1 obstacle, 0 free, 1 occupied by a container\n    vector<vector<int>> occ(D, vector<int>(D,0));\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++)\n        if(is_obstacle[i][j]) occ[i][j] = -1;\n    // posToT: at (i,j), which t\u2010tag is stored there\n    vector<vector<int>> posToT(D, vector<int>(D, -1));\n    // ---- Storing phase ----\n    for(int d=0; d<C; d++){\n        int t; \n        cin >> t;\n        // BFS to find currently reachable FREE squares\n        vector<vector<bool>> vis(D, vector<bool>(D,false));\n        queue<pair<int,int>> q;\n        vis[ex][ey] = true;\n        q.push({ex,ey});\n        while(!q.empty()){\n            auto [x,y] = q.front(); q.pop();\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(vis[nx][ny]) continue;\n                if(occ[nx][ny]!=0) continue; // only walk on free squares\n                vis[nx][ny] = true;\n                q.push({nx,ny});\n            }\n        }\n        // Decide target distance\n        double target = (C>1 ? (double)t / (C-1) * maxDist : 0.0);\n\n        // Among reachable frees (not entrance), pick the one with dist0 closest to target\n        double bestErr = 1e9;\n        int bestX=-1, bestY=-1;\n        int bestDist = -1;\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            if(i==ex && j==ey) continue;\n            if(occ[i][j]!=0) continue;\n            if(!vis[i][j]) continue;\n            double e = fabs(dist0[i][j] - target);\n            if(e + 1e-9 < bestErr\n             || (fabs(e - bestErr)<1e-9 && dist0[i][j] < bestDist))\n            {\n                bestErr = e;\n                bestDist = dist0[i][j];\n                bestX = i; bestY = j;\n            }\n        }\n        // Place it\n        occ[bestX][bestY] = 1;\n        posToT[bestX][bestY] = t;\n        // Output and flush\n        cout << bestX << \" \" << bestY << \"\\n\";\n        cout.flush();\n    }\n\n    // ---- Retrieval phase ----\n    // We'll do C steps.  At each step, BFS over current free squares (entrance + removed ones)\n    // to find which containers are reachable, then pick the one with minimum t.\n    vector<pair<int,int>> answer;\n    answer.reserve(C);\n    for(int step=0; step<C; step++){\n        // BFS over occ==0 squares\n        vector<vector<bool>> vis(D, vector<bool>(D,false));\n        queue<pair<int,int>> q;\n        vis[ex][ey] = true;\n        q.push({ex,ey});\n        while(!q.empty()){\n            auto [x,y] = q.front(); q.pop();\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(vis[nx][ny]) continue;\n                if(occ[nx][ny]!=0) continue; // only walk on free\n                vis[nx][ny] = true;\n                q.push({nx,ny});\n            }\n        }\n        // Find all containers occ==1 that neighbor a vis==true cell\n        int pickT = INT_MAX, pickX=-1, pickY=-1;\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            if(occ[i][j]==1){\n                // check adjacency\n                bool can = false;\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni<0||ni>=D||nj<0||nj>=D) continue;\n                    if(vis[ni][nj]){\n                        can = true; break;\n                    }\n                }\n                if(!can) continue;\n                int tt = posToT[i][j];\n                if(tt < pickT){\n                    pickT = tt;\n                    pickX = i; pickY = j;\n                }\n            }\n        }\n        // remove it\n        occ[pickX][pickY] = 0;\n        answer.push_back({pickX,pickY});\n    }\n\n    // Finally print the retrieval order\n    for(auto &pp : answer){\n        cout << pp.first << \" \" << pp.second << \"\\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    cin >> n >> m;\n    vector<vector<int>> c(n, vector<int>(n));\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < n; j++){\n            cin >> c[i][j];\n        }\n    }\n    // Baseline: just reproduce the input map verbatim.\n    // This preserves all ward-to-ward and ward-to-outside adjacencies,\n    // and keeps every color's region connected.\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < n; j++){\n            cout << c[i][j] << (j+1 < n ? ' ' : '\\n');\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    cin >> N >> D >> Q;\n\n    // --- Dummy query loop: always compare item 0 vs item 1 ---\n    //     (must do exactly Q queries, each non-empty L and R, L \u2229 R = \u2205)\n    for(int q = 0; q < Q; q++){\n        // output: nL=1, nR=1, l0=0, r0=1\n        cout << 1 << ' ' << 1 << ' ' << 0 << ' ' << 1 << '\\n' << flush;\n        char resp;\n        cin >> resp;\n        // we ignore '<', '>', '='\n    }\n\n    // --- Dummy partition: round\u2010robin assignment ---\n    //     d_i = i % D\n    vector<int> ans(N);\n    for(int i = 0; i < N; i++){\n        ans[i] = i % D;\n    }\n\n    // output final assignment\n    for(int i = 0; i < N; i++){\n        cout << ans[i] << (i+1==N?'\\n':' ');\n    }\n    cout << flush;\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(NULL);\n\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> st(m);\n    for(int i = 0; i < m; i++){\n        st[i].resize(n/m);\n        for(int j = 0; j < n/m; j++){\n            cin >> st[i][j];\n        }\n    }\n\n    vector<pair<int,int>> ops;\n    ops.reserve(2*n);\n\n    // For each target v = 1..n\n    for(int v = 1; v <= n; v++){\n        // 1) locate v in some stack s at depth j\n        int s = -1, j = -1;\n        for(int i = 0; i < m && s==-1; i++){\n            for(int k = 0; k < (int)st[i].size(); k++){\n                if(st[i][k] == v){\n                    s = i; j = k;\n                    break;\n                }\n            }\n        }\n        int sz = st[s].size();\n        int above = sz - (j+1);\n        // 2) if there are boxes above v, move the largest segment above in one op\n        if(above > 0){\n            // the box immediately above v\n            int w = st[s][j+1];\n            // choose a destination stack t != s of minimal height\n            int t = -1, besth = INT_MAX;\n            for(int i = 0; i < m; i++){\n                if(i == s) continue;\n                if((int)st[i].size() < besth){\n                    besth = st[i].size();\n                    t = i;\n                }\n            }\n            // record operation: move box w and all above to stack t\n            ops.emplace_back(w, t+1);\n            // perform the move in our simulation\n            vector<int> segment;\n            segment.reserve(above);\n            for(int p = j+1; p < sz; p++){\n                segment.push_back(st[s][p]);\n            }\n            st[s].resize(j+1);\n            for(int x: segment) st[t].push_back(x);\n        }\n        // 3) now v is at the top of stack s; carry it out\n        ops.emplace_back(v, 0);\n        st[s].pop_back();\n    }\n\n    // Output\n    for(auto &op: ops){\n        cout << op.first << \" \" << op.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int,int>;\nconst int INF = 1e9;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<string> h(N-1), v(N);\n    for(int i = 0; i < N-1; i++) cin >> h[i];\n    for(int i = 0; i < N; i++) cin >> v[i];\n    vector<int> d(N*N);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> d[i*N + j];\n        }\n    }\n\n    // build graph\n    int V = N*N;\n    vector<vector<int>> adj(V);\n    auto id = [&](int i,int j){ return i*N + j; };\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            int u = id(i,j);\n            if(i+1 < N && h[i][j]=='0'){\n                int v2 = id(i+1,j);\n                adj[u].push_back(v2);\n                adj[v2].push_back(u);\n            }\n            if(j+1 < N && v[i][j]=='0'){\n                int v2 = id(i,j+1);\n                adj[u].push_back(v2);\n                adj[v2].push_back(u);\n            }\n        }\n    }\n\n    // Dijkstra from 0 with cost = C - d[v]\n    const int C = 1001;\n    vector<int> dist(V, INF), parent(V, -1);\n    dist[0] = 0;\n    priority_queue<pii, vector<pii>, greater<pii>> pq;\n    pq.emplace(0, 0);\n    while(!pq.empty()){\n        auto [du,u] = pq.top(); pq.pop();\n        if(du > dist[u]) continue;\n        for(int v2: adj[u]){\n            int w = C - d[v2];\n            if(dist[v2] > du + w){\n                dist[v2] = du + w;\n                parent[v2] = u;\n                pq.emplace(dist[v2], v2);\n            }\n        }\n    }\n\n    // build tree\n    vector<vector<int>> children(V);\n    for(int v2 = 1; v2 < V; v2++){\n        int p = parent[v2];\n        if(p >= 0) children[p].push_back(v2);\n    }\n\n    // compute subtree max-d and sort children\n    vector<int> submx(V);\n    function<int(int)> dfs2 = [&](int u){\n        int mx = d[u];\n        for(int &c: children[u]){\n            int cmx = dfs2(c);\n            mx = max(mx, cmx);\n        }\n        submx[u] = mx;\n        auto &ch = children[u];\n        sort(ch.begin(), ch.end(), [&](int a,int b){\n            return submx[a] > submx[b];\n        });\n        return mx;\n    };\n    dfs2(0);\n\n    // DFS tour & output\n    string ans;\n    ans.reserve(2*(V-1));\n    function<void(int)> dfs3 = [&](int u){\n        int ui = u / N, uj = u % N;\n        for(int c: children[u]){\n            int ci = c / N, cj = c % N;\n            char mv, rev;\n            if(ci == ui+1){ mv = 'D'; rev = 'U'; }\n            else if(ci == ui-1){ mv = 'U'; rev = 'D'; }\n            else if(cj == uj+1){ mv = 'R'; rev = 'L'; }\n            else { mv = 'L'; rev = 'R'; }\n            ans.push_back(mv);\n            dfs3(c);\n            ans.push_back(rev);\n        }\n    };\n    dfs3(0);\n\n    // we are back at 0\n    cout << ans << \"\\n\";\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int,int>;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M;\n    cin >> N >> M;\n    int si, sj;\n    cin >> si >> sj;\n    vector<string> A(N);\n    for(int i = 0; i < N; i++){\n        cin >> A[i];\n    }\n    vector<string> t(M);\n    for(int i = 0; i < M; i++){\n        cin >> t[i];\n    }\n\n    // Precompute positions of each letter\n    vector<vector<pii>> pos(26);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            char c = A[i][j];\n            pos[c-'A'].emplace_back(i, j);\n        }\n    }\n\n    vector<bool> used(M, false);\n    vector<pii> moves;\n    moves.reserve(M * 5);\n\n    int cur_i = si, cur_j = sj;\n\n    // We will pick the next word by nearest first-letter\n    for(int iter = 0; iter < M; iter++){\n        int best_k = -1;\n        int best_dist = INT_MAX;\n\n        // Find the unused word whose first-letter is closest\n        for(int k = 0; k < M; k++){\n            if(used[k]) continue;\n            char first_c = t[k][0];\n            int ci = first_c - 'A';\n            // search nearest occurrence\n            int local_best = INT_MAX;\n            for(auto &p : pos[ci]){\n                int d = abs(cur_i - p.first) + abs(cur_j - p.second);\n                if(d < local_best) local_best = d;\n            }\n            if(local_best < best_dist){\n                best_dist = local_best;\n                best_k = k;\n            }\n        }\n\n        // Mark it used\n        used[best_k] = true;\n\n        // Type the 5 letters of t[best_k], greedy nearest for each\n        for(char c : t[best_k]){\n            int ci = c - 'A';\n            int pick_i = -1, pick_j = -1;\n            int pick_dist = INT_MAX;\n            for(auto &p : pos[ci]){\n                int d = abs(cur_i - p.first) + abs(cur_j - p.second);\n                if(d < pick_dist){\n                    pick_dist = d;\n                    pick_i = p.first;\n                    pick_j = p.second;\n                }\n            }\n            // move finger and type\n            moves.emplace_back(pick_i, pick_j);\n            cur_i = pick_i;\n            cur_j = pick_j;\n        }\n    }\n\n    // Output the move sequence\n    // We are guaranteed moves.size() == M*5 <= 1000 <= 5000\n    for(auto &mv : moves){\n        cout << mv.first << \" \" << mv.second << \"\\n\";\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    cin >> N >> M >> eps;\n    // Read (and ignore) the shapes\n    for(int k = 0; k < M; k++){\n        int d;\n        cin >> d;\n        for(int t = 0; t < d; t++){\n            int ii, jj;\n            cin >> ii >> jj;\n        }\n    }\n\n    vector<pair<int,int>> hasOil;\n    // Drill every cell\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cout << \"q 1 \" << i << \" \" << j << \"\\n\" << flush;\n            int v;\n            if(!(cin >> v)){\n                // Judge terminated unexpectedly\n                return 0;\n            }\n            if(v > 0){\n                hasOil.emplace_back(i, j);\n            }\n        }\n    }\n\n    // Answer with all cells that had v>0\n    cout << \"a \" << hasOil.size();\n    for(auto &p : hasOil){\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << \"\\n\" << flush;\n\n    // Read final verdict (1 = correct, 0 = wrong)\n    int verdict;\n    cin >> verdict;\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int W = 1000;\n    int D, N;\n    cin >> ws >> W >> D >> N;\n    // Note: W is given as 1000, we can ignore re-reading it\n    vector<vector<int>> a(D, vector<int>(N));\n    for(int d = 0; d < D; d++){\n        for(int k = 0; k < N; k++){\n            cin >> a[d][k];\n        }\n    }\n\n    // Precompute f[k][w] = total shortage over days if strip k has width w:\n    //     f[k][w] = sum_d max(0, a[d][k] - W*w)\n    // We only need w up to W (1000), since beyond that no shortage.\n    vector<vector<ll>> f(N, vector<ll>(W+2, 0));\n    for(int k = 0; k < N; k++){\n        for(int w = 1; w <= W; w++){\n            ll sum = 0;\n            ll cap = (ll)W * w;\n            for(int d = 0; d < D; d++){\n                if(a[d][k] > cap) sum += (a[d][k] - cap);\n            }\n            f[k][w] = sum;\n        }\n        // f[k][W+1] = 0 (no shortage if width > W)\n        f[k][W+1] = 0;\n    }\n\n    // Greedy resource allocation:\n    // start with width[k]=1, total used = N\n    vector<int> width(N, 1);\n    int used = N;\n    int K_rem = W - used;  // extra columns we can assign\n\n    // Precompute for each k the current marginal benefit delta[k] = f[k][w] - f[k][w+1]\n    vector<ll> delta(N, 0);\n    for(int k = 0; k < N; k++){\n        delta[k] = f[k][1] - f[k][2];\n    }\n\n    // Greedily assign each of the K_rem extra columns\n    for(int it = 0; it < K_rem; it++){\n        // find k with max delta[k]\n        int best = -1;\n        ll bestVal = 0;\n        for(int k = 0; k < N; k++){\n            if(delta[k] > bestVal){\n                bestVal = delta[k];\n                best = k;\n            }\n        }\n        if(best < 0) break; // no more benefit => stop early\n\n        // assign one extra column to strip 'best'\n        width[best]++;\n        used++;\n\n        int w = width[best];\n        if(w <= W) {\n            delta[best] = f[best][w] - f[best][w+1];\n        } else {\n            delta[best] = 0;\n        }\n    }\n\n    // Compute the X-coordinates of each strip\n    vector<int> X(N+1, 0);\n    for(int k = 0; k < N; k++){\n        X[k+1] = X[k] + width[k];\n    }\n    // X[N] <= W; we leave the tail unused if X[N]<W\n\n    // Output the same N rectangles each day:\n    // strip k => rectangle [0..W]\u00d7[X[k]..X[k+1]]\n    // i0=0, j0=X[k], i1=W, j1=X[k+1]\n    for(int d = 0; d < D; d++){\n        for(int k = 0; k < N; k++){\n            cout << 0 << ' ' << X[k] << ' ' << W << ' ' << X[k+1] << \"\\n\";\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\nstatic const int MOD = 998244353;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    cin >> N >> M >> K;\n    vector<vector<int>> b(N, vector<int>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            long long x;\n            cin >> x;\n            b[i][j] = int(x % MOD);\n        }\n    }\n    // stamps[m][i][j]\n    vector<array<array<int,3>,3>> stamps(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                long long x;\n                cin >> x;\n                stamps[m][i][j] = int(x % MOD);\n            }\n        }\n    }\n\n    struct Op { int m, p, q; };\n    vector<Op> ops;\n    ops.reserve(K);\n\n    // Greedy: up to K steps\n    for(int step = 0; step < K; step++){\n        long long best_delta = 0;\n        int best_m = -1, best_p = -1, best_q = -1;\n        // Try every stamp and every placement\n        for(int m = 0; m < M; m++){\n            auto &S = stamps[m];\n            for(int p = 0; p + 2 < N; p++){\n                for(int q = 0; q + 2 < N; q++){\n                    long long delta = 0;\n                    // compute delta in score\n                    for(int di = 0; di < 3; di++){\n                        for(int dj = 0; dj < 3; dj++){\n                            int oldv = b[p+di][q+dj];\n                            int nv = oldv + S[di][dj];\n                            if(nv >= MOD) nv -= MOD;\n                            delta += (nv - oldv);\n                        }\n                    }\n                    if(delta > best_delta){\n                        best_delta = delta;\n                        best_m = m;\n                        best_p = p;\n                        best_q = q;\n                    }\n                }\n            }\n        }\n        // if no positive gain, stop\n        if(best_delta <= 0) break;\n        // apply best move\n        auto &S = stamps[best_m];\n        for(int di = 0; di < 3; di++){\n            for(int dj = 0; dj < 3; dj++){\n                int &cell = b[best_p+di][best_q+dj];\n                cell += S[di][dj];\n                if(cell >= MOD) cell -= MOD;\n            }\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    cin >> N;\n    // Read & ignore the arrival permutation\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            int x; \n            cin >> x;\n        }\n    }\n\n    // We will build for each of the N cranes (one per row)\n    // a sequence of moves that repeats 5 times:\n    //   P         // pick at (i,0)\n    //   R R R R   // move to (i,4)\n    //   Q         // drop \u2192 dispatch immediately\n    //   L L L L   // return to (i,0)\n    //\n    // Total length = 5 * 10 = 50 turns, all cranes in parallel.\n    vector<string> S(N, \"\");\n    string seq = \"PRRRRQLLLL\";\n    for(int i = 0; i < N; i++){\n        for(int t = 0; t < N; t++){\n            S[i] += seq;\n        }\n    }\n\n    // Output\n    for(int i = 0; i < N; i++){\n        cout << S[i] << \"\\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(NULL);\n\n    int N;\n    cin >> N;\n    vector<vector<int>> h(N, vector<int>(N));\n    for(int i = 0; i < N; i++)\n        for(int j = 0; j < N; j++)\n            cin >> h[i][j];\n\n    vector<pair<int,int>> path;\n    // Build snake path over all cells\n    for(int i = 0; i < N; i++){\n        if(i % 2 == 0){\n            for(int j = 0; j < N; j++)\n                path.emplace_back(i,j);\n        } else {\n            for(int j = N-1; j >= 0; j--)\n                path.emplace_back(i,j);\n        }\n    }\n\n    vector<string> ops;\n    long long content = 0;\n    int cx = 0, cy = 0;\n\n    auto move_to = [&](int nx, int ny){\n        // simple grid Manhattan moves\n        while(cx < nx){ ops.emplace_back(\"D\"); cx++; }\n        while(cx > nx){ ops.emplace_back(\"U\"); cx--; }\n        while(cy < ny){ ops.emplace_back(\"R\"); cy++; }\n        while(cy > ny){ ops.emplace_back(\"L\"); cy--; }\n    };\n\n    // Phase 1: traverse and load all positive h\n    for(int k = 0; k < (int)path.size(); k++){\n        int nx = path[k].first, ny = path[k].second;\n        move_to(nx, ny);\n        if(h[nx][ny] > 0){\n            int d = h[nx][ny];\n            ops.emplace_back(\"+\" + to_string(d));\n            content += d;\n            h[nx][ny] = 0;\n        }\n    }\n\n    // Return to (0,0)\n    move_to(0, 0);\n\n    // Phase 2: traverse and unload all negative h\n    for(int k = 0; k < (int)path.size(); k++){\n        int nx = path[k].first, ny = path[k].second;\n        move_to(nx, ny);\n        if(h[nx][ny] < 0){\n            int d = -h[nx][ny];\n            ops.emplace_back(\"-\" + to_string(d));\n            content -= d;\n            h[nx][ny] = 0;\n        }\n    }\n\n    // Output\n    for(auto &s : ops)\n        cout << s << \"\\n\";\n\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    cin >> N >> M >> T;\n    const int SEED = 2 * N * (N - 1); // =60 when N=6\n\n    // read initial seeds\n    vector<vector<int>> X(SEED, vector<int>(M));\n    for(int i = 0; i < SEED; i++){\n        for(int j = 0; j < M; j++){\n            cin >> X[i][j];\n        }\n    }\n\n    // each turn\n    for(int t = 0; t < T; t++){\n        // compute sums\n        vector<pair<int,int>> V(SEED);\n        for(int i = 0; i < SEED; i++){\n            int s = 0;\n            for(int x : X[i]) s += x;\n            V[i] = {s, i};\n        }\n        // pick top N*N seeds by sum\n        sort(V.begin(), V.end(), greater<>());\n        vector<int> pick(N*N);\n        for(int i = 0; i < N*N; i++){\n            pick[i] = V[i].second;\n        }\n        // plant in row-major order\n        for(int i = 0, idx = 0; i < N; i++){\n            for(int j = 0; j < N; j++){\n                cout << pick[idx++] << (j+1 < N ? ' ' : '\\n');\n            }\n        }\n        cout << flush;\n\n        // read back the 60 new seeds\n        for(int i = 0; i < SEED; i++){\n            for(int j = 0; j < M; j++){\n                cin >> X[i][j];\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Directions: 0=right,1=down,2=left,3=up\nconst int dx[4] = {0, 1, 0, -1};\nconst int dy[4] = {1, 0, -1, 0};\nconst char DIRC[4] = {'R','D','L','U'};\n\n// Append the sequence of turns to move the fingertip to (tx,ty), ending with a 'P'\nvoid move_fingertip(int tx, int ty,\n                    int N,\n                    int &rx, int &ry, int &dir,\n                    vector<string> &ops) {\n    // Find the best new orientation d and root position (rx',ry')\n    int bestT = INT_MAX, bestD = -1, bestRx=0, bestRy=0, bestRot = 0, bestCW = 0;\n    for(int d = 0; d < 4; d++){\n        int nrx = tx - dx[d];\n        int nry = ty - dy[d];\n        if(nrx < 0 || nrx >= N || nry < 0 || nry >= N) continue;\n        int dist = abs(nrx - rx) + abs(nry - ry);\n        int cw = (d - dir + 4) % 4;\n        int ccw = (dir - d + 4) % 4;\n        int rot = min(cw, ccw);\n        int T = max(dist, rot);\n        if(T < bestT){\n            bestT = T;\n            bestD = d;\n            bestRx = nrx;\n            bestRy = nry;\n            bestRot = rot;\n            bestCW = (cw <= ccw ? 1 : 0); // 1 for CW ('R'), 0 for CCW ('L')\n        }\n    }\n    int need_dx = bestRx - rx;\n    int need_dy = bestRy - ry;\n    int moves = abs(need_dx) + abs(need_dy);\n    int rotCnt = bestRot;\n    char rotChar = bestCW ? 'R' : 'L';\n    int T = max(moves, rotCnt);\n\n    int rem_dx = need_dx, rem_dy = need_dy, rem_rot = rotCnt;\n    for(int step = 0; step < T; step++){\n        char m = '.', r = '.', a0 = '.', a1 = '.';\n        // Movement\n        if(step < moves){\n            if(rem_dx > 0){ m = 'D'; rem_dx--; rx++; }\n            else if(rem_dx < 0){ m = 'U'; rem_dx++; rx--; }\n            else if(rem_dy > 0){ m = 'R'; rem_dy--; ry++; }\n            else if(rem_dy < 0){ m = 'L'; rem_dy++; ry--; }\n        }\n        // Rotation\n        if(step < rotCnt){\n            r = rotChar;\n            if(rotChar == 'R') dir = (dir + 1) & 3;\n            else           dir = (dir + 3) & 3;\n        }\n        // On the final step, pick/place with fingertip (vertex 1)\n        if(step == T-1) a1 = 'P';\n        // Build the 2*V' = 4-character turn string: [move][rotate for v=1][action v=0][action v=1]\n        string S(4, '.');\n        S[0] = m;\n        S[1] = r;\n        S[2] = a0; // root (v=0) is never a leaf\n        S[3] = a1; // fingertip\n        ops.push_back(S);\n    }\n    // After this, (rx,ry,dir) == (bestRx,bestRy,bestD) and we have done the 'P'\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Vmax;\n    cin >> N >> M >> Vmax;\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 sources and targets\n    vector<pair<int,int>> src, dst;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(S[i][j] == '1') src.emplace_back(i,j);\n            if(T[i][j] == '1') dst.emplace_back(i,j);\n        }\n    }\n    sort(src.begin(), src.end());\n    sort(dst.begin(), dst.end());\n\n    // Output the simplest 2-node arm: 0 (root) --1--> 1 (fingertip), length=1\n    int Vp = 2;\n    cout << Vp << \"\\n\";\n    cout << 0 << \" \" << 1 << \"\\n\"; // parent of 1 is 0, edge length =1\n    // Initial root position: (0,0)\n    int rx = 0, ry = 0, dir = 0; // dir=0 means finger points right\n    cout << rx << \" \" << ry << \"\\n\";\n\n    vector<string> ops;\n    // We are never holding at the start\n    // For each takoyaki: move to source, P (pickup), move to target, P (drop)\n    for(int k = 0; k < M; k++){\n        move_fingertip(src[k].first, src[k].second, N, rx, ry, dir, ops);\n        move_fingertip(dst[k].first, dst[k].second, N, rx, ry, dir, ops);\n    }\n\n    // Emit all turns\n    for(auto &s: ops) {\n        cout << s << \"\\n\";\n    }\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\nstruct Pt { int x, y, w; };\nstatic constexpr int HMAX = 100000;\nstatic constexpr int CG = 200;  // coarse grid size\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<Pt> pts;\n    pts.reserve(2*N);\n    for(int i = 0; i < 2*N; i++){\n        int x,y; \n        cin >> x >> y;\n        int w = (i < N ? +1 : -1);\n        pts.push_back({x,y,w});\n    }\n\n    // 1) Compress X,Y globally\n    vector<int> xs, ys;\n    xs.reserve(2*N);\n    ys.reserve(2*N);\n    for(auto &p: pts){\n        xs.push_back(p.x);\n        ys.push_back(p.y);\n    }\n    sort(xs.begin(), xs.end());\n    xs.erase(unique(xs.begin(), xs.end()), xs.end());\n    sort(ys.begin(), ys.end());\n    ys.erase(unique(ys.begin(), ys.end()), ys.end());\n    int MX = xs.size(), MY = ys.size();\n\n    vector<int> compX(2*N), compY(2*N);\n    for(int i = 0; i < 2*N; i++){\n        compX[i] = int(lower_bound(xs.begin(), xs.end(), pts[i].x) - xs.begin());\n        compY[i] = int(lower_bound(ys.begin(), ys.end(), pts[i].y) - ys.begin());\n    }\n\n    // Bins by compressed X\n    vector<vector<pair<int,int>>> binsX(MX);\n    for(int i = 0; i < 2*N; i++){\n        binsX[compX[i]].emplace_back(compY[i], pts[i].w);\n    }\n\n    // 2) Initial global sliding\u2010window 2D max\u2010subarray\n    //    We pick Ni1 random left\u2010edges, window width Kx1\n    const int Ni1 = 45, Kx1 = 333;\n    int bestA1 = INT_MIN;\n    int bx1=0, bx2=0, by1=0, by2=0;\n    vector<int> W(MY,0);\n    mt19937 rng(123456);\n    uniform_int_distribution<int> distL(0, max(0,MX - Kx1));\n    for(int _ = 0; _ < Ni1; _++){\n        int L = (MX > Kx1 ? distL(rng) : 0);\n        fill(W.begin(), W.end(), 0);\n        int Rmax = min(MX, L + Kx1);\n        for(int R = L; R < Rmax; R++){\n            for(auto &pr: binsX[R]){\n                W[pr.first] += pr.second;\n            }\n            // Kadane on W[]\n            int cur = W[0], t0 = 0;\n            int best = cur, sy = 0, ey = 0;\n            for(int y = 1; y < MY; y++){\n                if(cur > 0) cur += W[y];\n                else { cur = W[y]; t0 = y; }\n                if(cur > best){\n                    best = cur;\n                    sy = t0;\n                    ey = y;\n                }\n            }\n            if(best > bestA1){\n                bestA1 = best;\n                bx1 = L; bx2 = R;\n                by1 = sy; by2 = ey;\n            }\n        }\n    }\n\n    // 3) Coarse grid DP on 200\u00d7200 to find a promising cell\u2010range\n    int CW = (HMAX+1 + CG-1)/CG; // ~501\n    static int cgrid[CG][CG];\n    for(int i = 0; i < CG; i++)\n        for(int j = 0; j < CG; j++)\n            cgrid[i][j] = 0;\n    for(auto &p: pts){\n        int xi = min(CG-1, p.x / CW);\n        int yi = min(CG-1, p.y / CW);\n        cgrid[xi][yi] += p.w;\n    }\n    static int tmpCG[CG];\n    int bestA2 = INT_MIN;\n    int cx1=0, cx2=0, cy1=0, cy2=0;\n    for(int Lx = 0; Lx < CG; Lx++){\n        fill(tmpCG, tmpCG+CG, 0);\n        for(int Rx = Lx; Rx < CG; Rx++){\n            for(int y = 0; y < CG; y++){\n                tmpCG[y] += cgrid[Rx][y];\n            }\n            // Kadane in Y\n            int cur = tmpCG[0], t0 = 0;\n            int best = cur, sy = 0, ey = 0;\n            for(int y = 1; y < CG; y++){\n                if(cur > 0) cur += tmpCG[y];\n                else { cur = tmpCG[y]; t0 = y; }\n                if(cur > best){\n                    best = cur;\n                    sy = t0; ey = y;\n                }\n            }\n            if(best > bestA2){\n                bestA2 = best;\n                cx1 = Lx; cx2 = Rx;\n                cy1 = sy; cy2 = ey;\n            }\n        }\n    }\n\n    // 4) Build the fine\u2010region of points in that coarse rectangle\n    int X0 = cx1*CW;\n    int X1 = min(HMAX, (cx2+1)*CW - 1);\n    int Y0 = cy1*CW;\n    int Y1 = min(HMAX, (cy2+1)*CW - 1);\n\n    vector<Pt> rpts;\n    rpts.reserve(2000);\n    for(auto &p: pts){\n        if(p.x >= X0 && p.x <= X1 && p.y >= Y0 && p.y <= Y1)\n            rpts.push_back(p);\n    }\n    int Rn = rpts.size();\n\n    int bestA3 = INT_MIN, rx1=0, rx2=0, ry1=0, ry2=0;\n    vector<int> xs3, ys3;\n    if(Rn){\n        xs3.reserve(Rn);\n        ys3.reserve(Rn);\n        for(auto &p: rpts){\n            xs3.push_back(p.x);\n            ys3.push_back(p.y);\n        }\n        sort(xs3.begin(), xs3.end());\n        xs3.erase(unique(xs3.begin(), xs3.end()), xs3.end());\n        sort(ys3.begin(), ys3.end());\n        ys3.erase(unique(ys3.begin(), ys3.end()), ys3.end());\n        int RX = xs3.size(), RY = ys3.size();\n\n        vector<int> cX(Rn), cY(Rn);\n        for(int i = 0; i < Rn; i++){\n            cX[i] = int(lower_bound(xs3.begin(), xs3.end(), rpts[i].x) - xs3.begin());\n            cY[i] = int(lower_bound(ys3.begin(), ys3.end(), rpts[i].y) - ys3.begin());\n        }\n        vector<vector<pair<int,int>>> bX(RX);\n        for(int i = 0; i < Rn; i++){\n            bX[cX[i]].emplace_back(cY[i], rpts[i].w);\n        }\n\n        // If the region X\u2010width \u2264 500, do the exact O(RX^2*RY) DP\n        if(RX <= 500){\n            vector<int> tmp(RY);\n            for(int Lx = 0; Lx < RX; Lx++){\n                fill(tmp.begin(), tmp.end(), 0);\n                for(int Rx = Lx; Rx < RX; Rx++){\n                    for(auto &pr: bX[Rx])\n                        tmp[pr.first] += pr.second;\n                    // Kadane\n                    int cur = tmp[0], t0 = 0;\n                    int best = cur, sy = 0, ey = 0;\n                    for(int y = 1; y < RY; y++){\n                        if(cur > 0) cur += tmp[y];\n                        else { cur = tmp[y]; t0 = y; }\n                        if(cur > best){\n                            best = cur; sy = t0; ey = y;\n                        }\n                    }\n                    if(best > bestA3){\n                        bestA3 = best;\n                        rx1 = Lx; rx2 = Rx;\n                        ry1 = sy; ry2 = ey;\n                    }\n                }\n            }\n        } else {\n            // Otherwise another sliding\u2010window on this subproblem\n            const int Ni2 = 40, Kx2 = 250;\n            uniform_int_distribution<int> dist2(0, max(0,RX - Kx2));\n            vector<int> tmp(RY), Ls(Ni2);\n            for(int i = 0; i < Ni2; i++){\n                Ls[i] = (RX > Kx2 ? dist2(rng) : 0);\n            }\n            for(int Lx: Ls){\n                fill(tmp.begin(), tmp.end(), 0);\n                int Rmax = min(RX, Lx + Kx2);\n                for(int Rx = Lx; Rx < Rmax; Rx++){\n                    for(auto &pr: bX[Rx])\n                        tmp[pr.first] += pr.second;\n                    int cur = tmp[0], t0 = 0;\n                    int best = cur, sy = 0, ey = 0;\n                    for(int y = 1; y < RY; y++){\n                        if(cur > 0) cur += tmp[y];\n                        else { cur = tmp[y]; t0 = y; }\n                        if(cur > best){\n                            best = cur; sy = t0; ey = y;\n                        }\n                    }\n                    if(best > bestA3){\n                        bestA3 = best;\n                        rx1 = Lx; rx2 = Rx;\n                        ry1 = sy; ry2 = ey;\n                    }\n                }\n            }\n        }\n    }\n\n    // 5) Compare the two candidates\n    int A1 = bestA1;\n    int x1 = xs[bx1], x2 = xs[bx2];\n    int y1 = ys[by1], y2 = ys[by2];\n\n    int A2 = bestA3;\n    int xx1=0, xx2=0, yy1=0, yy2=0;\n    if(Rn && bestA3 > INT_MIN/2){\n        xx1 = xs3[rx1];\n        xx2 = xs3[rx2];\n        yy1 = ys3[ry1];\n        yy2 = ys3[ry2];\n    }\n\n    int finalA = A1;\n    int FX1 = x1, FX2 = x2, FY1 = y1, FY2 = y2;\n    if(A2 > A1){\n        finalA = A2;\n        FX1 = xx1; FX2 = xx2; FY1 = yy1; FY2 = yy2;\n    }\n\n    // If non\u2010positive or degenerate, fall back to [0,0]\u2192[1,1]\n    if(finalA <= 0 || FX2 <= FX1 || FY2 <= FY1){\n        FX1 = 0; FY1 = 0;\n        FX2 = 1; FY2 = 1;\n    }\n\n    // 6) Output the rectangle\n    //      (FX1,FY1)->(FX1,FY2)->(FX2,FY2)->(FX2,FY1)\n    cout << 4 << \"\\n\";\n    cout << FX1 << \" \" << FY1 << \"\\n\";\n    cout << FX1 << \" \" << FY2 << \"\\n\";\n    cout << FX2 << \" \" << FY2 << \"\\n\";\n    cout << FX2 << \" \" << FY1 << \"\\n\";\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    ll sigma;\n    cin >> N >> T >> sigma;\n    vector<ll> w(N), h(N);\n    for(int i = 0; i < N; i++){\n        cin >> w[i] >> h[i];\n    }\n\n    // We'll place all N rectangles in a single horizontal row.\n    // Orientation: choose r_i = 1 if rotating makes the (measured) width smaller.\n    // Placement: for i=0, (d,b)=('U',-1) => x=0, y=0;\n    //            for i>0, (d,b)=('U',i-1) => left edge aligned to right edge of i-1, then y=0.\n\n    for(int turn = 0; turn < T; turn++){\n        // 1) output our placement\n        cout << N << \"\\n\";\n        for(int i = 0; i < N; i++){\n            int r = (h[i] < w[i]) ? 1 : 0;  // rotate if height<width to make width smaller\n            char d = 'U';\n            int b = (i == 0 ? -1 : i - 1);\n            cout << i << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        }\n        cout << flush;\n\n        // 2) read back the noisy measurements and ignore them\n        ll Wp, Hp;\n        if(!(cin >> Wp >> Hp)){\n            // in case input ends unexpectedly\n            break;\n        }\n    }\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    cin >> N >> M >> H;\n    vector<int> A(N);\n    for(int i = 0; i < N; i++) cin >> A[i];\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    // skip coordinates\n    for(int i = 0; i < N; i++){\n        int x,y; \n        cin >> x >> y;\n    }\n\n    vector<bool> covered(N, false);\n    vector<int> parent(N, -1), depth(N, 0);\n\n    vector<int> distCand(N, -1), q(N);\n    auto evalRoot = [&](int r)->long long {\n        // BFS on the *uncovered* subgraph up to depth H, sum (d+1)*A\n        long long sum = 0;\n        int ql = 0, qr = 0;\n        distCand[r] = 0;\n        q[qr++] = r;\n        sum += (long long)(1) * A[r];\n        vector<int> seen; \n        seen.push_back(r);\n        while(ql < qr){\n            int u = q[ql++];\n            if(distCand[u] == H) continue;\n            for(int w: adj[u]){\n                if(!covered[w] && distCand[w] == -1){\n                    distCand[w] = distCand[u] + 1;\n                    sum += (long long)(distCand[w] + 1) * A[w];\n                    q[qr++] = w;\n                    seen.push_back(w);\n                }\n            }\n        }\n        // reset distCand\n        for(int v: seen) distCand[v] = -1;\n        return sum;\n    };\n\n    int uncovered = N;\n    while(uncovered > 0){\n        // 1) pick best root among uncovered\n        long long bestScore = -1;\n        int bestR = -1;\n        for(int r = 0; r < N; r++){\n            if(covered[r]) continue;\n            long long sc = evalRoot(r);\n            if(sc > bestScore){\n                bestScore = sc;\n                bestR = r;\n            }\n        }\n        // 2) BFS from bestR, record parent[] and depth[], mark covered\n        int ql = 0, qr = 0;\n        vector<int> distAct(N, -1), parAct(N, -1), seenAct;\n        distAct[bestR] = 0;\n        parAct[bestR]  = -1;\n        q[qr++] = bestR;\n        seenAct.push_back(bestR);\n        covered[bestR] = true;\n        parent[bestR] = -1;\n        depth[bestR]  = 0;\n        uncovered--;\n\n        while(ql < qr){\n            int u = q[ql++];\n            if(distAct[u] == H) continue;\n            for(int w: adj[u]){\n                if(!covered[w] && distAct[w] == -1){\n                    distAct[w] = distAct[u] + 1;\n                    parAct[w]  = u;\n                    q[qr++] = w;\n                    seenAct.push_back(w);\n                    covered[w] = true;\n                    parent[w] = u;\n                    depth[w]  = distAct[w];\n                    uncovered--;\n                }\n            }\n        }\n        // next iteration until all covered\n    }\n\n    // Output the parent array\n    // If parent[v] = -1, it's a root; otherwise it's the parent vertex.\n    for(int i = 0; i < N; i++){\n        cout << parent[i] << (i+1==N?'\\n':' ');\n    }\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Segment {\n    char dir;           // 'L','R','U','D'\n    int idx;            // row or column index\n    int k;              // number of shifts in that direction\n    int cost;           // = 2*k\n    vector<int> cover;  // which Oni (by id) this segment removes\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;                // N is always 20\n    vector<string> B(N);\n    for(int i = 0; i < N; i++) {\n        cin >> B[i];\n    }\n\n    // 1) collect all Oni positions and give them IDs 0..M-1\n    vector<pair<int,int>> oni_pos;\n    oni_pos.reserve(2*N);\n    vector<vector<int>> pos2id(N, vector<int>(N, -1));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(B[i][j] == 'x'){\n                int id = (int)oni_pos.size();\n                pos2id[i][j] = id;\n                oni_pos.emplace_back(i,j);\n            }\n        }\n    }\n    int M = oni_pos.size(); // should be 2N = 40\n\n    // 2) precompute, for each row/col, where the nearest 'o' is\n    const int INF = 1000000;\n    vector<int> row_min_o(N, INF), row_max_o(N, -INF);\n    vector<int> col_min_o(N, INF), col_max_o(N, -INF);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(B[i][j] == 'o'){\n                row_min_o[i] = min(row_min_o[i], j);\n                row_max_o[i] = max(row_max_o[i], j);\n                col_min_o[j] = min(col_min_o[j], i);\n                col_max_o[j] = max(col_max_o[j], i);\n            }\n        }\n    }\n    // if a row has no 'o', row_min_o stays INF, row_max_o = -INF, etc.\n\n    // 3) build all valid segments\n    vector<Segment> segs;\n    segs.reserve(4*N);\n    auto add_segment = [&](char d, int idx, int k){\n        if(k <= 0) return;\n        Segment s;\n        s.dir = d; s.idx = idx; s.k = k; s.cost = 2*k;\n        // collect which Oni lie in that segment\n        if(d == 'L'){\n            // row idx, columns [0..k-1]\n            for(int j = 0; j < k; j++){\n                int id = pos2id[idx][j];\n                if(id >= 0) s.cover.push_back(id);\n            }\n        } else if(d == 'R'){\n            // row idx, columns [N-k..N-1]\n            for(int j = N-k; j < N; j++){\n                int id = pos2id[idx][j];\n                if(id >= 0) s.cover.push_back(id);\n            }\n        } else if(d == 'U'){\n            // col idx, rows [0..k-1]\n            for(int i = 0; i < k; i++){\n                int id = pos2id[i][idx];\n                if(id >= 0) s.cover.push_back(id);\n            }\n        } else { // 'D'\n            // col idx, rows [N-k..N-1]\n            for(int i = N-k; i < N; i++){\n                int id = pos2id[i][idx];\n                if(id >= 0) s.cover.push_back(id);\n            }\n        }\n        if(!s.cover.empty()){\n            segs.push_back(move(s));\n        }\n    };\n\n    // row-left and row-right\n    for(int i = 0; i < N; i++){\n        int L = (row_min_o[i] == INF ? N : row_min_o[i]);\n        if(L > 0) add_segment('L', i, L);\n        int R = (row_max_o[i] == -INF ? -1 : row_max_o[i]);\n        if(R < N-1) add_segment('R', i, N - (R+1));\n    }\n    // col-up and col-down\n    for(int j = 0; j < N; j++){\n        int U = (col_min_o[j] == INF ? N : col_min_o[j]);\n        if(U > 0) add_segment('U', j, U);\n        int D = (col_max_o[j] == -INF ? -1 : col_max_o[j]);\n        if(D < N-1) add_segment('D', j, N - (D+1));\n    }\n\n    int S = segs.size();\n    vector<bool> used(S,false), covered(M,false);\n    int covered_cnt = 0;\n    vector<int> chosen; chosen.reserve(S);\n\n    // 4) greedy set\u2010cover: each step pick segment with best (newly\u2010covered Oni) / cost\n    while(covered_cnt < M){\n        double best_ratio = -1.0;\n        int best_s = -1, best_new = 0;\n        for(int s = 0; s < S; s++){\n            if(used[s]) continue;\n            int newc = 0;\n            for(int id: segs[s].cover){\n                if(!covered[id]) newc++;\n            }\n            if(newc == 0) continue;\n            double ratio = double(newc) / segs[s].cost;\n            if(ratio > best_ratio){\n                best_ratio = ratio;\n                best_s = s;\n                best_new = newc;\n            }\n        }\n        if(best_s < 0){\n            // should never happen, because each Oni has at least one clear direction\n            break;\n        }\n        used[best_s] = true;\n        chosen.push_back(best_s);\n        for(int id: segs[best_s].cover){\n            if(!covered[id]){\n                covered[id] = true;\n                covered_cnt++;\n            }\n        }\n    }\n\n    // 5) emit operations for each chosen segment\n    //    we can do them in any order\u2014each (k shifts in dir, then k in the opposite) is independent\n    auto opposite = [&](char d)->char{\n        if(d=='L') return 'R';\n        if(d=='R') return 'L';\n        if(d=='U') return 'D';\n        return 'U';\n    };\n\n    vector<pair<char,int>> ops;\n    ops.reserve(1600);\n\n    for(int si: chosen){\n        auto &Sg = segs[si];\n        for(int t = 0; t < Sg.k; t++){\n            ops.emplace_back(Sg.dir, Sg.idx);\n        }\n        char od = opposite(Sg.dir);\n        for(int t = 0; t < Sg.k; t++){\n            ops.emplace_back(od, Sg.idx);\n        }\n    }\n\n    // Just in case (should be <= 4*N*N = 1600)\n    // but we know sum(2*k) <= 1600 by construction.\n    // Output:\n    for(auto &op: ops){\n        cout << op.first << \" \" << op.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    long long L;\n    cin >> N >> L;\n    vector<long long> T(N);\n    for(int i = 0; i < N; i++){\n        cin >> T[i];\n    }\n\n    // Baseline: one big cycle of length N.\n    // We set a[i] = b[i] = (i+1)%N so that the walker cycles\n    // around 0\u21921\u21922\u2192...\u2192N-1\u21920\u2192...\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;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for(int i = 0; i < M; i++) cin >> G[i];\n\n    vector<int> lx(N), rx(N), ly(N), ry(N);\n    for(int i = 0; i < N; i++){\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n\n    // Compute rectangle centers\n    vector<pair<double,double>> center(N);\n    for(int i = 0; i < N; i++){\n        center[i].first  = (lx[i] + rx[i]) * 0.5;\n        center[i].second = (ly[i] + ry[i]) * 0.5;\n    }\n\n    // Sort cities by center (lex order)\n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](int a, int b){\n        if(center[a].first != center[b].first)\n            return center[a].first < center[b].first;\n        return center[a].second < center[b].second;\n    });\n\n    // Split into M groups according to G[]\n    vector<vector<int>> groups;\n    groups.reserve(M);\n    int p = 0;\n    for(int k = 0; k < M; k++){\n        vector<int> g;\n        g.reserve(G[k]);\n        for(int t = 0; t < G[k]; t++){\n            g.push_back(idx[p++]);\n        }\n        groups.push_back(move(g));\n    }\n\n    // Prepare storage for the edges of each group\n    vector<vector<pair<int,int>>> answer_edges(M);\n\n    // For each group, run Prim's MST on the approximate centers\n    for(int k = 0; k < M; k++){\n        auto &g = groups[k];\n        int K = g.size();\n        if(K <= 1) continue;\n        vector<bool> in_mst(K,false);\n        vector<double> min_d(K, 1e18);\n        vector<int> parent(K, -1);\n\n        min_d[0] = 0.0;\n        for(int it = 0; it < K; it++){\n            // find next u with smallest min_d[u]\n            int u = -1;\n            double best = 1e18;\n            for(int i = 0; i < K; i++){\n                if(!in_mst[i] && min_d[i] < best){\n                    best = min_d[i];\n                    u = i;\n                }\n            }\n            // add it\n            in_mst[u] = true;\n            if(parent[u] != -1){\n                int a = g[u], b = g[parent[u]];\n                answer_edges[k].emplace_back(a, b);\n            }\n            // relax neighbors\n            for(int v = 0; v < K; v++){\n                if(in_mst[v]) continue;\n                double dx = center[g[u]].first  - center[g[v]].first;\n                double dy = center[g[u]].second - center[g[v]].second;\n                double d = floor(sqrt(dx*dx + dy*dy));\n                if(d < min_d[v]){\n                    min_d[v] = d;\n                    parent[v] = u;\n                }\n            }\n        }\n    }\n\n    // Output final answer: no queries\n    cout << \"!\\n\";\n    for(int k = 0; k < M; k++){\n        // list cities in group k\n        for(int i = 0; i < (int)groups[k].size(); i++){\n            if(i) cout << ' ';\n            cout << groups[k][i];\n        }\n        cout << \"\\n\";\n        // list the G[k]-1 edges\n        for(auto &e : answer_edges[k]){\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(NULL);\n\n    int N, M;\n    cin >> N >> M;\n    vector<pair<int,int>> pts(M);\n    for(int i = 0; i < M; i++){\n        cin >> pts[i].first >> pts[i].second;\n    }\n    int ci = pts[0].first, cj = pts[0].second;\n    vector<pair<char,char>> ans;\n    // Targets are pts[1] ... pts[M-1]\n    for(int k = 1; k < M; k++){\n        int ti = pts[k].first, tj = pts[k].second;\n        // Move vertically\n        while(ci < ti){\n            ans.emplace_back('M','D');\n            ci++;\n        }\n        while(ci > ti){\n            ans.emplace_back('M','U');\n            ci--;\n        }\n        // Move horizontally\n        while(cj < tj){\n            ans.emplace_back('M','R');\n            cj++;\n        }\n        while(cj > tj){\n            ans.emplace_back('M','L');\n            cj--;\n        }\n    }\n    // Output\n    for(auto &p : ans){\n        cout << p.first << \" \" << p.second << \"\\n\";\n    }\n    return 0;\n}"},"2":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Rect { int x1,y1,x2,y2; };\n\nstatic inline bool canMerge(const Rect &a, const Rect &b, Rect &out) {\n    // vertical merge?\n    if(a.x1==b.x1 && a.x2==b.x2) {\n        if(a.y2==b.y1) { out={a.x1,a.y1,a.x2,b.y2}; return true; }\n        if(b.y2==a.y1) { out={a.x1,b.y1,a.x2,a.y2}; return true; }\n    }\n    // horizontal merge?\n    if(a.y1==b.y1 && a.y2==b.y2) {\n        if(a.x2==b.x1) { out={a.x1,a.y1,b.x2,a.y2}; return true; }\n        if(b.x2==a.x1) { out={b.x1,a.y1,a.x2,a.y2}; return true; }\n    }\n    return false;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n;\n    cin >> n;\n    vector<int> x(n), y(n);\n    vector<long long> r(n);\n    for(int i=0;i<n;i++){\n        cin >> x[i] >> y[i] >> r[i];\n    }\n\n    // order: largest r first; ties \u21d2 seed nearer border goes first\n    vector<int> order(n);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int a,int b){\n             if(r[a]!=r[b]) return r[a]>r[b];\n             int da = min( min(x[a],9999-x[a]), min(y[a],9999-y[a]) );\n             int db = min( min(x[b],9999-x[b]), min(y[b],9999-y[b]) );\n             return da<db;\n         });\n\n    // answer rectangles\n    vector<array<int,4>> ans(n);\n\n    // free\u2010space list (disjoint), in half\u2010open coords [x1,x2)x[y1,y2)\n    vector<Rect> freeRects;\n    freeRects.reserve(2000);\n    freeRects.push_back({0,0,10000,10000});\n\n    // helper: remove index i from freeRects (swap\u2010pop)\n    auto removeRect = [&](int i){\n        freeRects[i] = freeRects.back();\n        freeRects.pop_back();\n    };\n\n    // helper: add a new free rect *with merging* against all existing\n    auto addFree = [&](Rect r0){\n        // throw away empty\n        if(r0.x1>=r0.x2 || r0.y1>=r0.y2) return;\n        // try to merge repeatedly\n        bool again = true;\n        while(again){\n            again = false;\n            for(int i=0;i<(int)freeRects.size();i++){\n                Rect m;\n                if(canMerge(r0, freeRects[i], m)){\n                    // merge them\n                    removeRect(i);\n                    r0 = m;\n                    again = true;\n                    break;\n                }\n            }\n        }\n        freeRects.push_back(r0);\n    };\n\n    // main greedy\n    for(int idx: order){\n        long long ri = r[idx];\n        int xi = x[idx], yi = y[idx];\n\n        // 1) ideal dims near sqrt(ri)\n        int w0 = (int)floor(sqrt((long double)ri));\n        while(1LL*w0*w0 > ri) --w0;\n        while(1LL*(w0+1)*(w0+1) <= ri) ++w0;\n        w0 = max(1, min(w0,10000));\n        int h0 = (ri + w0 - 1)/w0;\n        if(h0>10000){\n            h0=10000;\n            w0 = (ri + h0 - 1)/h0;\n        }\n\n        // try both orientations\n        vector<pair<int,int>> dims;\n        dims.emplace_back(w0,h0);\n        if(h0!=w0) dims.emplace_back(h0,w0);\n\n        struct Cand { int ridx,w,h,L,R,D,U,waste; };\n        vector<Cand> cands;\n        cands.reserve(freeRects.size()*2);\n\n        // scan free rects\n        for(auto &d: dims){\n            int w=d.first, h=d.second;\n            for(int j=0;j<(int)freeRects.size();j++){\n                auto &R = freeRects[j];\n                int Rw=R.x2-R.x1, Rh=R.y2-R.y1;\n                if(Rw<w||Rh<h) continue;\n                // to contain (xi,yi) in [a,a+w)\u00d7[b,b+h):\n                int L = max(R.x1, xi - w + 1);\n                int Rg= min(xi,    R.x2 - w);\n                if(L>Rg) continue;\n                int D = max(R.y1, yi - h + 1);\n                int U = min(yi,    R.y2 - h);\n                if(D>U) continue;\n                int area = Rw*Rh;\n                int waste= area - w*h;\n                cands.push_back({j,w,h,L,Rg,D,U,waste});\n            }\n        }\n\n        if(!cands.empty()){\n            // pick minimal waste, tie\u2192smaller area free\u2010rect\n            int best=0;\n            int bestW = cands[0].waste;\n            int bestA = (freeRects[cands[0].ridx].x2 - freeRects[cands[0].ridx].x1)*\n                        (freeRects[cands[0].ridx].y2 - freeRects[cands[0].ridx].y1);\n            for(int i=1;i<(int)cands.size();i++){\n                int wst = cands[i].waste;\n                int A   = (freeRects[cands[i].ridx].x2 - freeRects[cands[i].ridx].x1)*\n                          (freeRects[cands[i].ridx].y2 - freeRects[cands[i].ridx].y1);\n                if(wst<bestW || (wst==bestW && A<bestA)){\n                    best = i; bestW=wst; bestA=A;\n                }\n            }\n            auto &c = cands[best];\n            // center as much as possible\n            int a0 = xi - c.w/2;\n            a0 = min(max(a0, c.L), c.R);\n            int b0 = yi - c.h/2;\n            b0 = min(max(b0, c.D), c.U);\n            ans[idx] = {a0, b0, a0+c.w, b0+c.h};\n\n            // split out the chosen free\u2010rect\n            Rect R = freeRects[c.ridx];\n            removeRect(c.ridx);\n            int X1=R.x1, Y1=R.y1, X2=R.x2, Y2=R.y2;\n            // up to four new pieces\n            addFree({X1,      Y1,      a0,       Y2});\n            addFree({a0+c.w,  Y1,      X2,       Y2});\n            addFree({a0,      Y1,      a0+c.w,   b0});\n            addFree({a0,      b0+c.h,  a0+c.w,   Y2});\n        }\n        else {\n            // fallback #1: grab entire free\u2010rect covering seed (best r\u2010ratio)\n            double bestR=-1;\n            int bestJ=-1;\n            for(int j=0;j<(int)freeRects.size();j++){\n                auto &R=freeRects[j];\n                if(R.x1<=xi && xi<R.x2 && R.y1<=yi && yi<R.y2){\n                    long long w=R.x2-R.x1, h=R.y2-R.y1;\n                    long long s=w*h;\n                    double ratio = (double)min(s,ri)/max(s,ri);\n                    if(ratio>bestR){\n                        bestR=ratio; bestJ=j;\n                    }\n                }\n            }\n            if(bestJ!=-1){\n                Rect R = freeRects[bestJ];\n                ans[idx] = {R.x1,R.y1,R.x2,R.y2};\n                removeRect(bestJ);\n            }\n            else {\n                // fallback #2: should be very rare\n                Rect R = freeRects.back();\n                int j = (int)freeRects.size()-1;\n                int a = R.x1, b = R.y1;\n                ans[idx] = {a,b,a+1,b+1};\n                removeRect(j);\n                // split off the 1\u00d71\n                addFree({R.x1,      R.y1,    a,       R.y2});\n                addFree({a+1,       R.y1,    R.x2,    R.y2});\n                addFree({a,         R.y1,    a+1,     b});\n                addFree({a,         b+1,     a+1,     R.y2});\n            }\n        }\n    }\n\n    // output in original order\n    for(int i=0;i<n;i++){\n        auto &a = ans[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\nstatic constexpr int H = 50, W = 50;\nstatic constexpr int DX[4] = {-1,1,0,0};\nstatic constexpr int DY[4] = {0,0,-1,1};\nstatic constexpr char DC[4] = {'U','D','L','R'};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si,sj;\n    cin >> si >> sj;\n\n    static int t[H][W], pval[H][W];\n    int maxTile = 0;\n    for(int i=0;i<H;i++){\n      for(int j=0;j<W;j++){\n        cin >> t[i][j];\n        maxTile = max(maxTile, t[i][j]);\n      }\n    }\n    for(int i=0;i<H;i++){\n      for(int j=0;j<W;j++){\n        cin >> pval[i][j];\n      }\n    }\n    int M = maxTile+1;\n\n    // visited\u2010stamp trick: avoid memset per run\n    vector<int> visitedStamp(M, 0);\n    int stamp = 1;\n\n    // RNG\n    uint64_t seed = chrono::high_resolution_clock::now()\n                      .time_since_epoch().count();\n    mt19937_64 rng(seed ^ (seed<<13));\n\n    // best\u2010found path & score\n    vector<char> bestPath;\n    long long bestScore = -1;\n\n    // For time\u2010limiting\n    auto t0 = chrono::steady_clock::now();\n    constexpr double TIME_LIMIT = 1.85; // seconds\n\n    // Containers for one run\n    vector<char> curPath;\n    curPath.reserve(H*W);\n\n    // Multi\u2010start loop\n    for(int iter=0;;iter++){\n      // time check every 32 iters\n      if((iter & 31)==0){\n        auto now = chrono::steady_clock::now();\n        double elapsed = double((now - t0).count()) * 1e-9;\n        if(elapsed > TIME_LIMIT) break;\n      }\n\n      // Randomize weights\n      int wd = int(rng() % 20001);      // [0..20000]\n      int wp = int(rng() % 201);        // [0..200]\n\n      // clear for this run\n      curPath.clear();\n      int ci = si, cj = sj;\n      long long curScore = pval[ci][cj];\n      visitedStamp[ t[ci][cj] ] = stamp;\n\n      // one\u2010step\u2010lookahead greedy\n      while(true){\n        int bestW = INT_MIN, bestD = -1, ni=-1, nj=-1;\n\n        for(int d=0;d<4;d++){\n          int ti = ci + DX[d];\n          int tj = cj + DY[d];\n          if(ti<0||ti>=H||tj<0||tj>=W) continue;\n          int tid = t[ti][tj];\n          if(visitedStamp[tid] == stamp) continue;\n\n          // compute deg = number of unvisited neighbors\n          int deg = 0;\n          for(int d2=0;d2<4;d2++){\n            int xi = ti + DX[d2];\n            int xj = tj + DY[d2];\n            if(xi<0||xi>=H||xj<0||xj>=W) continue;\n            if(visitedStamp[ t[xi][xj] ] != stamp)\n              deg++;\n          }\n\n          int w = deg * wd + pval[ti][tj] * wp;\n          if(w > bestW){\n            bestW = w;\n            bestD = d;\n            ni = ti; nj = tj;\n          }\n        }\n\n        if(bestD < 0) break; // dead\u2010end\n        // take step\n        ci = ni; cj = nj;\n        visitedStamp[ t[ci][cj] ] = stamp;\n        curScore += pval[ci][cj];\n        curPath.push_back( DC[bestD] );\n      }\n\n      // record if best\n      if(curScore > bestScore){\n        bestScore = curScore;\n        bestPath = curPath;\n      }\n      stamp++;\n    }\n\n    // output the best found\n    for(char c : bestPath) \n      cout << c;\n    cout << \"\\n\";\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nstatic constexpr int N = 30;\nstatic constexpr int VERTS = N * N;\n\n// Tunable hyper\u2010parameters\nstatic constexpr double INIT_W = 5000.0;\nstatic constexpr double ALPHA  = 0.20;    // base learning rate\nstatic constexpr double EXPL   = 200.0;   // exploration bonus\n\n// Directions: U, D, L, R\nint dr[4] = {-1, +1,  0,  0};\nint dc[4] = { 0,  0, -1, +1};\nchar dch[4] = {'U','D','L','R'};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // Estimated weights and visit\u2010counts\n    static double w_h[N][N-1], w_v[N-1][N];\n    static int    cnt_h[N][N-1], cnt_v[N-1][N];\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N-1;j++){\n            w_h[i][j] = INIT_W;\n            cnt_h[i][j] = 0;\n        }\n    }\n    for(int i=0;i<N-1;i++){\n        for(int j=0;j<N;j++){\n            w_v[i][j] = INIT_W;\n            cnt_v[i][j] = 0;\n        }\n    }\n\n    // Dijkstra buffers\n    static double distArr[VERTS];\n    static bool   done[VERTS];\n    static int    prevNode[VERTS];\n    static char   prevDir[VERTS];\n\n    auto idx = [&](int r,int c){ return r * N + c; };\n\n    // rng for neighbor\u2010shuffle\n    mt19937 rng(712687126);\n\n    for(int qi=0;qi<1000;qi++){\n        int si,sj,ti,tj;\n        if(!(cin>>si>>sj>>ti>>tj)) return 0;\n\n        // shuffle neighbor order to break lex\u2010bias\n        array<int,4> dirs = {0,1,2,3};\n        shuffle(dirs.begin(), dirs.end(), rng);\n\n        // init Dijkstra\n        const double INF = 1e18;\n        for(int i=0;i<VERTS;i++){\n            distArr[i] = INF;\n            done[i] = false;\n        }\n        int s_id = idx(si,sj), t_id = idx(ti,tj);\n        distArr[s_id] = 0.0;\n        priority_queue<pair<double,int>,\n                       vector<pair<double,int>>,\n                       greater<pair<double,int>>> pq;\n        pq.push({0.0, s_id});\n\n        // Dijkstra with exploration bonus\n        while(!pq.empty()){\n            auto [cd,u] = pq.top(); pq.pop();\n            if(done[u]) continue;\n            done[u] = true;\n            if(u == t_id) break;\n            int ur = u / N, uc = u % N;\n            for(int d: dirs){\n                int vr = ur + dr[d], vc = uc + dc[d];\n                if(vr<0||vr>=N||vc<0||vc>=N) continue;\n                double w_e, bonus;\n                if(d==0){        // U: edge v[vr][vc]\n                    w_e   = w_v[vr][vc];\n                    bonus = EXPL / sqrt(double(cnt_v[vr][vc] + 1));\n                }\n                else if(d==1){   // D: edge v[ur][uc]\n                    w_e   = w_v[ur][uc];\n                    bonus = EXPL / sqrt(double(cnt_v[ur][uc] + 1));\n                }\n                else if(d==2){   // L: edge h[vr][vc]\n                    w_e   = w_h[vr][vc];\n                    bonus = EXPL / sqrt(double(cnt_h[vr][vc] + 1));\n                }\n                else {           // R: edge h[ur][uc]\n                    w_e   = w_h[ur][uc];\n                    bonus = EXPL / sqrt(double(cnt_h[ur][uc] + 1));\n                }\n                double cst = w_e - bonus;\n                if(cst < 1.0) cst = 1.0;  // clamp to positive\n                int v = idx(vr,vc);\n                double nd = cd + cst;\n                if(nd < distArr[v]){\n                    distArr[v] = nd;\n                    prevNode[v] = u;\n                    prevDir[v]  = dch[d];\n                    pq.push({nd, v});\n                }\n            }\n        }\n\n        // Reconstruct path\n        vector<char> rev;\n        {\n            int cur = t_id;\n            while(cur != s_id){\n                rev.push_back(prevDir[cur]);\n                cur = prevNode[cur];\n            }\n        }\n        int L = rev.size();\n        string path; path.reserve(L);\n        for(int i=L-1;i>=0;i--) path.push_back(rev[i]);\n\n        // Output & flush\n        cout << path << \"\\n\" << flush;\n\n        // Read noisy total length\n        int b_obs;\n        cin >> b_obs;\n\n        // Compute s_est & collect edges\n        double s_est = 0.0;\n        struct Edge { bool horiz; int r,c; };\n        vector<Edge> edges; edges.reserve(L);\n        int cr = si, cc = sj;\n        for(char mv: path){\n            if(mv=='U'){\n                edges.push_back({false, cr-1, cc});\n                s_est += w_v[cr-1][cc];\n                cr--;\n            }\n            else if(mv=='D'){\n                edges.push_back({false, cr, cc});\n                s_est += w_v[cr][cc];\n                cr++;\n            }\n            else if(mv=='L'){\n                edges.push_back({true, cr, cc-1});\n                s_est += w_h[cr][cc-1];\n                cc--;\n            }\n            else { // 'R'\n                edges.push_back({true, cr, cc});\n                s_est += w_h[cr][cc];\n                cc++;\n            }\n        }\n\n        // Distribute the residual proportionally to w_e\n        double err = double(b_obs) - s_est;\n        if(L>0 && fabs(err) > 1e-9){\n            for(auto &e: edges){\n                if(e.horiz){\n                    double &w = w_h[e.r][e.c];\n                    int    &ct= cnt_h[e.r][e.c];\n                    ct++;\n                    double lr = ALPHA / sqrt(double(ct));\n                    // proportional update:\n                    w += w * lr * (err / s_est);\n                    if(w < 1.0) w = 1.0;\n                } else {\n                    double &w = w_v[e.r][e.c];\n                    int    &ct= cnt_v[e.r][e.c];\n                    ct++;\n                    double lr = ALPHA / sqrt(double(ct));\n                    w += w * lr * (err / s_est);\n                    if(w < 1.0) w = 1.0;\n                }\n            }\n        }\n    }\n\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// fast xorshift RNG\nstatic uint64_t rng_state = chrono::steady_clock::now().time_since_epoch().count();\ninline uint32_t xorshift32() {\n    rng_state ^= rng_state << 13;\n    rng_state ^= rng_state >> 7;\n    rng_state ^= rng_state << 17;\n    return (uint32_t)rng_state;\n}\ninline int randInt(int l, int r) {\n    return l + (xorshift32() % (r - l + 1));\n}\ninline double randDouble() {\n    // 24\u2010bit uniform\n    return (xorshift32() & 0xFFFFFF) / double(1<<24);\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const double TL = 2.95;     // leave a small margin\n    const int N = 20;\n    int M;\n    cin >> M;\n    vector<string> s(M);\n    for(int i = 0; i < M; i++){\n        cin >> s[i];\n    }\n    // convert strings to 0..7\n    vector<vector<int>> sChars(M);\n    for(int i = 0; i < M; i++){\n        int L = s[i].size();\n        sChars[i].resize(L);\n        for(int j = 0; j < L; j++){\n            sChars[i][j] = s[i][j] - 'A';\n        }\n    }\n\n    // Build all placements\n    struct Placement {\n        int si;\n        int len;\n        vector<int> coord; // (i,j) pairs flattened: coord[2*p],coord[2*p+1]\n    };\n    vector<Placement> placements;\n    placements.reserve(M * 2 * N);\n    const int CELL = N * N;\n    vector<vector<int>> byCell(CELL);\n    for(int c = 0; c < CELL; c++){\n        byCell[c].reserve(600);\n    }\n\n    for(int si = 0; si < M; si++){\n        int L = sChars[si].size();\n        for(int dir = 0; dir < 2; dir++){ // 0=H,1=V\n            for(int x = 0; x < N; x++){\n                for(int st = 0; st < N; st++){\n                    Placement P;\n                    P.si = si;\n                    P.len = L;\n                    P.coord.resize(2 * L);\n                    for(int p = 0; p < L; p++){\n                        int i,j;\n                        if(dir == 0){\n                            i = x;\n                            j = (st + p) % N;\n                        } else {\n                            i = (st + p) % N;\n                            j = x;\n                        }\n                        P.coord[2*p] = i;\n                        P.coord[2*p+1] = j;\n                    }\n                    int pid = placements.size();\n                    placements.push_back(move(P));\n                    // index into byCell\n                    auto &C = placements.back().coord;\n                    for(int p = 0; p < placements.back().len; p++){\n                        int i = C[2*p], j = C[2*p+1];\n                        byCell[i*N + j].push_back(pid);\n                    }\n                }\n            }\n        }\n    }\n\n    int Pn = placements.size();\n\n    // current grid as ints 0..7\n    vector<int> grid(CELL);\n    vector<int> bestGrid(CELL);\n\n    // valid flags for placements\n    vector<char> valid(Pn, 0);\n    // match count per string\n    vector<int> matchCount(M, 0);\n\n    // initialize grid randomly\n    for(int i = 0; i < CELL; i++){\n        grid[i] = randInt(0,7);\n    }\n    // compute initial valid[] and matchCount[]\n    for(int pid = 0; pid < Pn; pid++){\n        auto &P = placements[pid];\n        bool ok = true;\n        for(int p = 0; p < P.len; p++){\n            int i = P.coord[2*p], j = P.coord[2*p+1];\n            if(grid[i*N+j] != sChars[P.si][p]){\n                ok = false;\n                break;\n            }\n        }\n        if(ok){\n            valid[pid] = 1;\n            matchCount[P.si]++;\n        }\n    }\n    int curC = 0;\n    for(int i = 0; i < M; i++) if(matchCount[i] > 0) curC++;\n    int bestC = curC;\n    bestGrid = grid;\n\n    // buffers for delta computations\n    vector<pair<int,char>> changed; changed.reserve(1000);\n    vector<int> sis; sis.reserve(1000);\n    vector<int> oldMatch(M);\n    vector<char> seen(M,0);\n\n    auto start = chrono::steady_clock::now();\n    int iter = 0;\n    const double T0 = 5.0, T1 = 0.1;\n\n    while(true){\n        iter++;\n        if((iter & 511) == 0){\n            auto now = chrono::steady_clock::now();\n            double t = chrono::duration<double>(now - start).count();\n            if(t > TL) break;\n        }\n        // temperature\n        auto now = chrono::steady_clock::now();\n        double t = chrono::duration<double>(now - start).count() / TL;\n        if(t > 1.0) t = 1.0;\n        double T = T0 + (T1 - T0) * t;\n\n        // pick a random cell\n        int c = randInt(0, CELL-1);\n        int oldL = grid[c];\n        int newL = randInt(0,7);\n        if(newL == oldL) continue;\n\n        changed.clear();\n        sis.clear();\n        int newC = curC;\n\n        int ci = c / N, cj = c % N;\n\n        // try the change\n        for(int pid : byCell[c]){\n            auto &P = placements[pid];\n            int si = P.si;\n            bool prev = valid[pid];\n            bool nowv = true;\n            // check validity if we change this cell to newL\n            for(int p = 0; p < P.len; p++){\n                int ii = P.coord[2*p], jj = P.coord[2*p+1];\n                int gv = (ii==ci && jj==cj ? newL : grid[ii*N+jj]);\n                if(gv != sChars[si][p]){\n                    nowv = false;\n                    break;\n                }\n            }\n            if(prev != nowv){\n                changed.emplace_back(pid, prev);\n                if(!seen[si]){\n                    seen[si] = 1;\n                    sis.push_back(si);\n                    oldMatch[si] = matchCount[si];\n                }\n                if(prev){\n                    matchCount[si]--;\n                    if(oldMatch[si] > 0 && matchCount[si] == 0) newC--;\n                } else {\n                    matchCount[si]++;\n                    if(oldMatch[si] == 0 && matchCount[si] == 1) newC++;\n                }\n                valid[pid] = nowv;\n            }\n        }\n\n        int delta = newC - curC;\n        bool accept = false;\n        if(delta >= 0) accept = true;\n        else {\n            double p = exp(delta / T);\n            if(randDouble() < p) accept = true;\n        }\n\n        if(accept){\n            grid[c] = newL;\n            curC = newC;\n            if(curC > bestC){\n                bestC = curC;\n                bestGrid = grid;\n            }\n        } else {\n            // revert\n            for(auto &pc : changed){\n                valid[pc.first] = pc.second;\n            }\n            for(int si : sis){\n                matchCount[si] = oldMatch[si];\n            }\n        }\n        for(int si : sis) seen[si] = 0;\n    }\n\n    // output bestGrid\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            char ch = char('A' + bestGrid[i*N+j]);\n            cout << ch;\n        }\n        cout << \"\\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    cin >> N >> si >> sj;\n    vector<string> C(N);\n    for(int i = 0; i < N; i++) {\n        cin >> C[i];\n    }\n\n    // 1) Flatten road cells, assign IDs, record cost and position.\n    vector<int> id_map(N*N, -1);\n    vector<pair<int,int>> id2pos;\n    vector<int> id2cost;\n    id2pos.reserve(N*N);\n    id2cost.reserve(N*N);\n    int r = 0;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            char ch = C[i][j];\n            if(ch != '#'){\n                id_map[i*N + j] = r++;\n                id2pos.emplace_back(i,j);\n                id2cost.push_back(ch - '0');\n            }\n        }\n    }\n    if(r == 0){\n        // No roads at all (degenerate) \u2014 just print empty.\n        cout << \"\\n\";\n        return 0;\n    }\n    int startId = id_map[si*N + sj];\n\n    // 2) Build 4\u2010nbr graph with symmetric weights w(u,v)=cost[u]+cost[v].\n    vector<vector<pair<int,int>>> graph(r);\n    static const int di[4] = {-1,1,0,0}, dj[4] = {0,0,-1,1};\n    for(int u = 0; u < r; u++){\n        auto [i,j] = id2pos[u];\n        int cu = id2cost[u];\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            int v = id_map[ni*N + nj];\n            if(v<0) continue;\n            int cv = id2cost[v];\n            graph[u].emplace_back(v, cu+cv);\n        }\n    }\n\n    // 3) MST via Prim from startId.\n    const int INF = 1e9;\n    vector<int> key(r, INF), parent(r, -1);\n    vector<char> used(r,0);\n    key[startId] = 0;\n    priority_queue<pair<int,int>,\n        vector<pair<int,int>>,\n        greater<pair<int,int>>> pq;\n    pq.emplace(0, startId);\n    while(!pq.empty()){\n        auto [cw,u] = pq.top(); pq.pop();\n        if(used[u]) continue;\n        used[u] = 1;\n        for(auto &e: graph[u]){\n            int v = e.first, wuv = e.second;\n            if(!used[v] && wuv < key[v]){\n                key[v] = wuv;\n                parent[v] = u;\n                pq.emplace(wuv, v);\n            }\n        }\n    }\n\n    // 4) Build undirected MST adjacency.\n    vector<vector<int>> treeAdj(r);\n    for(int v = 0; v < r; v++){\n        int u = parent[v];\n        if(u >= 0){\n            treeAdj[u].push_back(v);\n            treeAdj[v].push_back(u);\n        }\n    }\n\n    // 5) Compute original MST\u2010degree and detect \"turn\" nodes (deg==2 & non\u2010collinear).\n    vector<int> deg(r);\n    for(int u = 0; u < r; u++){\n        deg[u] = (int)treeAdj[u].size();\n    }\n    vector<char> is_turn(r, 0);\n    for(int u = 0; u < r; u++){\n        if(deg[u] == 2){\n            int a = treeAdj[u][0], b = treeAdj[u][1];\n            auto [ui,uj] = id2pos[u];\n            auto [ai,aj] = id2pos[a];\n            auto [bi,bj] = id2pos[b];\n            // collinear if same row or same col\n            bool col = (ai==ui && bi==ui) || (aj==uj && bj==uj);\n            if(!col) is_turn[u] = 1;\n        }\n    }\n    // keep[u] = start || junction (deg>=3) || turn (deg==2 & non\u2010collinear)\n    vector<char> keep(r,0);\n    for(int u = 0; u < r; u++){\n        if(u == startId || deg[u] >= 3 || is_turn[u]) keep[u] = 1;\n    }\n\n    // 6) Root the MST at startId, build children[].\n    vector<int> parentT(r, -1);\n    vector<vector<int>> children(r);\n    parentT[startId] = -1;\n    {\n        // simple DFS stack\n        vector<int> stk;\n        stk.reserve(r);\n        stk.push_back(startId);\n        while(!stk.empty()){\n            int u = stk.back(); stk.pop_back();\n            for(int v: treeAdj[u]){\n                if(v == parentT[u]) continue;\n                parentT[v] = u;\n                children[u].push_back(v);\n                stk.push_back(v);\n            }\n        }\n    }\n\n    // 7) Compute hasImportantSubtree[u]\n    vector<char> hasImp(r,0);\n    function<void(int)> dfs_imp = [&](int u){\n        char h = keep[u];\n        for(int v: children[u]){\n            dfs_imp(v);\n            if(hasImp[v]) h = 1;\n        }\n        hasImp[u] = h;\n    };\n    dfs_imp(startId);\n\n    // 8) Euler\u2010style DFS on the *pruned* tree, emitting moves only into subtrees\n    //    that contain some keep\u2010node.\n    string ans;\n    ans.reserve(r*2);\n\n    auto dirChar = [&](int ui,int uj,int vi,int vj){\n        if(vi == ui-1 && vj == uj) return 'U';\n        if(vi == ui+1 && vj == uj) return 'D';\n        if(vi == ui && vj == uj-1) return 'L';\n        return 'R';\n    };\n    auto rev = [&](char c){\n        if(c=='U') return 'D';\n        if(c=='D') return 'U';\n        if(c=='L') return 'R';\n        return 'L';\n    };\n\n    function<void(int)> dfs_euler = [&](int u){\n        auto [ui,uj] = id2pos[u];\n        for(int v: children[u]){\n            if(!hasImp[v]) continue;  // prune entire subtree\n            auto [vi,vj] = id2pos[v];\n            char mv = dirChar(ui,uj,vi,vj);\n            ans.push_back(mv);\n            dfs_euler(v);\n            ans.push_back(rev(mv));\n        }\n    };\n    dfs_euler(startId);\n\n    // 9) Output\n    cout << ans << \"\\n\";\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Interactive scheduler with simple skill\u2010estimation.\n\nstruct Node {\n    int depth;\n    int best_pred;\n    int id;\n};\nstruct PQCmp {\n    bool operator()(Node const &a, Node const &b) const {\n        if(a.depth != b.depth) return a.depth < b.depth;        // deeper first\n        if(a.best_pred != b.best_pred) return a.best_pred < b.best_pred; // larger best_pred first\n        return a.id > b.id;                                      // smaller id first\n    }\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n    vector<vector<int>> d(N, vector<int>(K));\n    for(int i = 0; i < N; i++)\n        for(int j = 0; j < K; j++)\n            cin >> d[i][j];\n\n    vector<vector<int>> adj(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        adj[u].push_back(v);\n        indeg[v]++;\n    }\n\n    // 1) Compute \"depth\" = 1 + max depth of children\n    vector<int> depth(N, -1);\n    function<int(int)> dfs = [&](int u){\n        if(depth[u] != -1) return depth[u];\n        int best = 0;\n        for(int v: adj[u])\n            best = max(best, dfs(v));\n        return depth[u] = best + 1;\n    };\n    for(int i = 0; i < N; i++)\n        if(depth[i] < 0)\n            dfs(i);\n\n    // Skill estimates: lower bounds of s[j][k]\n    vector<vector<int>> s_est(M, vector<int>(K, 0));\n\n    // Track state\n    vector<bool> done(N,false), started(N,false);\n    vector<int> assigned_task(M,-1), assign_day(M,0);\n    vector<char> worker_free(M,1);\n    vector<int> free_list;\n    free_list.reserve(M);\n    for(int j=0;j<M;j++) free_list.push_back(j);\n\n    // Priority queue of ready tasks\n    priority_queue<Node,vector<Node>,PQCmp> pq;\n\n    // Compute best_pred for a task i under current s_est[]\n    auto compute_best_pred = [&](int i){\n        int best = INT_MAX;\n        for(int j=0;j<M;j++){\n            int sumd = 0;\n            // compute sum of max(0, d[i][k] - s_est[j][k])\n            for(int k2=0;k2<K;k2++){\n                int delta = d[i][k2] - s_est[j][k2];\n                if(delta>0) sumd += delta;\n            }\n            if(sumd < best) best = sumd;\n        }\n        return best==INT_MAX?0:best;\n    };\n\n    // Initially push indegree\u2010zero tasks\n    for(int i=0;i<N;i++){\n        if(indeg[i]==0){\n            int bp = compute_best_pred(i);\n            pq.push({depth[i], bp, i});\n        }\n    }\n\n    int cur_day = 1;\n    while(true){\n        // 1) morning: assign as many as possible\n        vector<pair<int,int>> out;\n        out.reserve(M);\n        // Pop tasks and match to best free worker\n        while(!free_list.empty() && !pq.empty()){\n            // pop a valid task with up\u2010to\u2010date best_pred\n            Node nd;\n            while(true){\n                if(pq.empty()) break;\n                nd = pq.top(); pq.pop();\n                int i = nd.id;\n                if(started[i]) continue; // already assigned\n                int bp_now = compute_best_pred(i);\n                if(bp_now != nd.best_pred){\n                    // stale, re\u2010push fresh\n                    pq.push({depth[i], bp_now, i});\n                    continue;\n                }\n                // got a good one\n                break;\n            }\n            if(started[nd.id]) break;\n            int i = nd.id;\n            // pick best free worker for task i\n            int best_w = -1, best_cost = INT_MAX;\n            for(int idx=0;idx<(int)free_list.size();idx++){\n                int j = free_list[idx];\n                int sumd = 0;\n                for(int k2=0;k2<K;k2++){\n                    int delta = d[i][k2] - s_est[j][k2];\n                    if(delta>0) sumd += delta;\n                }\n                if(sumd < best_cost){\n                    best_cost = sumd;\n                    best_w = idx;\n                }\n            }\n            int w = free_list[best_w];\n            // remove worker w from free_list\n            free_list[best_w] = free_list.back();\n            free_list.pop_back();\n\n            // assign\n            started[i] = true;\n            worker_free[w] = 0;\n            assigned_task[w] = i;\n            assign_day[w] = cur_day;\n            out.emplace_back(w+1, i+1);\n        }\n\n        // print assignment\n        cout << (int)out.size();\n        for(auto &pr: out){\n            cout << \" \" << pr.first << \" \" << pr.second;\n        }\n        cout << \"\\n\" << flush;\n\n        // 2) read who finished at end of day\n        int cnt;\n        cin >> cnt;\n        if(!cin || cnt<0) break;\n        for(int _=0;_<cnt;_++){\n            int f; cin >> f;\n            int w = f-1;\n            int i = assigned_task[w];\n            // compute observed t\n            int t = cur_day - assign_day[w] + 1;\n            int w_est = t>1 ? t-1 : 0;\n            // update skill\u2010estimate\n            if(i>=0){\n                for(int k2=0;k2<K;k2++){\n                    int lb = d[i][k2] - w_est;\n                    if(lb> s_est[w][k2])\n                        s_est[w][k2] = lb;\n                }\n            }\n            // free worker\n            worker_free[w] = 1;\n            assigned_task[w] = -1;\n            free_list.push_back(w);\n            // mark task done and push children if ready\n            if(i>=0 && !done[i]){\n                done[i] = true;\n                for(int nx: adj[i]){\n                    if(--indeg[nx]==0){\n                        int bp = compute_best_pred(nx);\n                        pq.push({depth[nx], bp, nx});\n                    }\n                }\n            }\n        }\n        cur_day++;\n    }\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\n#include <chrono>\nusing namespace std;\nusing ll = long long;\n\nint manh(int x1,int y1,int x2,int y2){\n    return abs(x1-x2)+abs(y1-y2);\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // 1) Read input\n    struct Order{int a,b,c,d,dist;};\n    vector<Order> ord(1000);\n    for(int i=0;i<1000;i++){\n        cin>>ord[i].a>>ord[i].b>>ord[i].c>>ord[i].d;\n        ord[i].dist = manh(ord[i].a,ord[i].b,ord[i].c,ord[i].d);\n    }\n\n    // 2) Select 50 orders with smallest internal distance\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 ord[i].dist < ord[j].dist; });\n    idx.resize(50);\n    // Now idx[0..49] are our selected order\u2010indices (unsorted).\n\n    // 3) Build cost matrices for the 50 nodes numbered 0..49\n    const int M = 50;\n    vector<int> sel = idx; // sel[k] = original order index\n    // Precompute coordinates\n    vector<int> px(M), py(M), dx(M), dy(M);\n    for(int i=0;i<M;i++){\n        px[i]=ord[sel[i]].a;\n        py[i]=ord[sel[i]].b;\n        dx[i]=ord[sel[i]].c;\n        dy[i]=ord[sel[i]].d;\n    }\n    // start/end costs\n    vector<int> start_cost(M), end_cost(M);\n    for(int i=0;i<M;i++){\n        start_cost[i]=manh(400,400,px[i],py[i]);\n        end_cost[i]  =manh(dx[i],dy[i],400,400);\n    }\n    // transition cost\n    static int trans[50][50];\n    for(int i=0;i<M;i++){\n        for(int j=0;j<M;j++){\n            trans[i][j]=manh(dx[i],dy[i],px[j],py[j]);\n        }\n    }\n\n    // 4) Multi\u2010start greedy to get an initial permutation\n    vector<int> order_by_start(M);\n    iota(order_by_start.begin(), order_by_start.end(), 0);\n    sort(order_by_start.begin(), order_by_start.end(),\n         [&](int i,int j){ return start_cost[i]<start_cost[j]; });\n\n    ll best_cost = LLONG_MAX;\n    vector<int> best_path;\n\n    for(int s=0; s<min(10,M); s++){\n        int st = order_by_start[s];\n        vector<char> used(M,false);\n        vector<int> path;\n        path.reserve(M);\n        path.push_back(st);\n        used[st]=1;\n        int cur=st;\n        // greedy nearest\u2010neighbor\n        for(int step=1;step<M;step++){\n            int best_j=-1, best_c=INT_MAX;\n            for(int j=0;j<M;j++){\n                if(!used[j]){\n                    int c = trans[cur][j];\n                    if(c<best_c){\n                        best_c=c;\n                        best_j=j;\n                    }\n                }\n            }\n            path.push_back(best_j);\n            used[best_j]=1;\n            cur=best_j;\n        }\n        // compute its cost\n        ll cost = start_cost[path[0]];\n        for(int i=0;i+1<M;i++) cost += trans[path[i]][path[i+1]];\n        cost += end_cost[path[M-1]];\n        if(cost<best_cost){\n            best_cost=cost;\n            best_path=path;\n        }\n    }\n\n    // 5) Asymmetric 2\u2010opt on best_path\n    auto t_start = chrono::steady_clock::now();\n    ll cur_cost = best_cost;\n    vector<int> &P = best_path;\n    const double TIME_LIMIT = 1.9; // sec\n    while(true){\n        auto t_now = chrono::steady_clock::now();\n        double elapsed = chrono::duration<double>(t_now - t_start).count();\n        if(elapsed > TIME_LIMIT) break;\n\n        bool improved=false;\n        // positions 0..M-1 in P; keep P[0] fixed as start\n        for(int i=1;i<M-1 && !improved;i++){\n            int A = P[i-1], B = P[i];\n            int orig1 = trans[A][B];\n            for(int j=i+1;j<M && !improved;j++){\n                int C = P[j];\n                int D = (j+1<M ? P[j+1] : -1);\n                int orig2 = (D>=0 ? trans[C][D] : end_cost[C]);\n                int new1  = trans[A][C];\n                int new2  = (D>=0 ? trans[B][D] : end_cost[B]);\n                int delta = (new1 + new2) - (orig1 + orig2);\n                if(delta<0){\n                    // apply reversal of segment [i..j]\n                    reverse(P.begin()+i, P.begin()+j+1);\n                    cur_cost += delta;\n                    improved = true;\n                }\n            }\n        }\n        if(!improved) break;\n    }\n\n    // 6) Output\n    // First line: m = 50, r_1..r_50 (1-based original order indices)\n    cout<<M;\n    for(int id:P){\n        cout<<\" \"<<(sel[id]+1);\n    }\n    cout<<\"\\n\";\n\n    // Second line: the route length n and the coordinates\n    // We do: (400,400) \u2192 [pickup,delivery]\u00d750 in best_path order \u2192 (400,400)\n    vector<pair<int,int>> route;\n    route.reserve(2*M+2);\n    route.emplace_back(400,400);\n    for(int id:P){\n        route.emplace_back(px[id], py[id]);\n        route.emplace_back(dx[id], dy[id]);\n    }\n    route.emplace_back(400,400);\n\n    cout<<route.size();\n    for(auto &pt:route){\n        cout<<\" \"<<pt.first<<\" \"<<pt.second;\n    }\n    cout<<\"\\n\";\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Disjoint\u2010set union (union by rank + path compression)\nstruct DSU {\n    int n;\n    vector<int> p, r;\n    DSU(int _n): n(_n), p(n,-1), r(n,0) {\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        return p[x]==x ? x : 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    vector<pair<int,int>> coord(N);\n    for(int i = 0; i < N; i++){\n        cin >> coord[i].first >> coord[i].second;\n    }\n    struct Edge { int u,v,id; int d; };\n    vector<Edge> edges;\n    edges.reserve(M);\n    for(int i = 0; i < M; i++){\n        int u,v;\n        cin >> u >> v;\n        int dx = coord[u].first  - coord[v].first;\n        int dy = coord[u].second - coord[v].second;\n        // rounded Euclidean distance\n        int di = int( round( sqrt(double(dx*dx + dy*dy)) ) );\n        edges.push_back({u,v,i,di});\n    }\n\n    // Kruskal on weights = d_i\n    vector<bool> choose(M,false);\n    DSU dsu(N);\n    sort(edges.begin(), edges.end(),\n         [&](auto &A, auto &B){\n             return A.d < B.d;\n         });\n    int taken = 0;\n    for(auto &e: edges){\n        if(taken == N-1) break;\n        if(dsu.unite(e.u, e.v)){\n            choose[e.id] = true;\n            taken++;\n        }\n    }\n    // Now process the stream\n    for(int i = 0; i < M; i++){\n        int l;\n        if(!(cin >> l)) return 0;  // safety\n        if(choose[i]){\n            cout << 1 << '\\n';\n        } else {\n            cout << 0 << '\\n';\n        }\n        cout.flush();  // must flush after each decision\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    vector<int> px(N), py(N), pt(N);\n    for(int i = 0; i < N; i++){\n        cin >> px[i] >> py[i] >> pt[i];\n    }\n    int M;\n    cin >> M;\n    vector<int> hx(M), hy(M);\n    for(int i = 0; i < M; i++){\n        cin >> hx[i] >> hy[i];\n    }\n\n    const int TURNS = 300;\n    string action(M, '.');\n    for(int turn = 0; turn < TURNS; turn++){\n        // 1) Output M actions: here we do nothing for all humans\n        cout << action << \"\\n\" << flush;\n\n        // 2) Read N pet\u2010movement strings (we ignore them)\n        for(int i = 0; i < N; i++){\n            string mv;\n            cin >> mv;\n        }\n        // repeat\n    }\n    return 0;\n}","ahc009":"#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,ti,tj;\n    double p;\n    cin>>si>>sj>>ti>>tj>>p;\n    vector<string> h(20), v(19);\n    for(int i=0;i<20;i++) cin>>h[i];\n    for(int i=0;i<19;i++) cin>>v[i];\n\n    // BFS\n    static int dist[20][20];\n    static int pi_[20][20], pj_[20][20];\n    static char pm_[20][20];\n    for(int i=0;i<20;i++) for(int j=0;j<20;j++) dist[i][j]=1e9;\n    queue<pair<int,int>> q;\n    dist[si][sj]=0;\n    q.push({si,sj});\n    // dir order: U,D,L,R\n    int dx[4]={-1,1,0,0}, dy[4]={0,0,-1,1};\n    char dc[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        for(int d=0;d<4;d++){\n            int ni=i+dx[d], nj=j+dy[d];\n            bool ok=false;\n            if(d==0){\n                if(i>=1 && v[i-1][j]=='0') ok=true;\n            } else if(d==1){\n                if(i<=18 && v[i][j]=='0') ok=true;\n            } else if(d==2){\n                if(j>=1 && h[i][j-1]=='0') ok=true;\n            } else {\n                if(j<=18 && h[i][j]=='0') ok=true;\n            }\n            if(!ok) continue;\n            if(dist[ni][nj]>dist[i][j]+1){\n                dist[ni][nj]=dist[i][j]+1;\n                pi_[ni][nj]=i;\n                pj_[ni][nj]=j;\n                pm_[ni][nj]=dc[d];\n                q.push({ni,nj});\n            }\n        }\n    }\n\n    // Reconstruct path\n    vector<char> path;\n    int ci=ti, cj=tj;\n    while(!(ci==si && cj==sj)){\n        char c = pm_[ci][cj];\n        path.push_back(c);\n        int ti2 = pi_[ci][cj], tj2 = pj_[ci][cj];\n        ci=ti2; cj=tj2;\n    }\n    reverse(path.begin(), path.end());\n    int D = path.size();\n    if(D==0){\n        // Already at office: just output a dummy move\n        cout<<\"U\\n\";\n        return 0;\n    }\n\n    // Choose repetition factor k\n    int k_cap = 200 / D;\n    if(k_cap<=0) k_cap=1;\n    // want p^k <= 0.1  =>  k >= log(0.1)/log(p)\n    double thresh = 0.1;\n    double tmp = log(thresh) / log(p);\n    int k_base = (int)ceil(tmp);\n    if(k_base<1) k_base=1;\n    int k = min(k_base, k_cap);\n\n    // Output each direction k times\n    string out;\n    out.reserve(D*k);\n    for(char c:path){\n        for(int i=0;i<k;i++) out.push_back(c);\n    }\n    cout<<out<<\"\\n\";\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\n/*\n  Solve the 30\u00d730 rail-tile rotation problem by\n   1) Multi-start greedy edge-matching\n   2) Local hill climb on the \"local match\" score\n\n  Scoring proxy: for each tile, (# of matched open ends with neighbors)\n                 minus (# of open ends that hit the boundary).\n  We maximize the sum of these over all tiles.\n\n  Finally we output the rotations r[i][j] (0..3) as a 900-char string.\n*/\n\nstatic const int H = 30, W = 30;\n// Directions: 0=left,1=up,2=right,3=down\nint di[4] = {0, -1, 0, 1}, dj[4] = {-1, 0, 1, 0};\ninline int opp(int d){ return (d + 2) & 3; }\n\n// to_dir[s][d]: if a train enters tile-state s from side d,\n// what side it exits (or -1 if no track there).\nstatic const int to_dir[8][4] = {\n  {1, 0, -1, -1},\n  {3,-1, -1,  0},\n  {-1,-1, 3,  2},\n  {-1, 2, 1, -1},\n  {1, 0, 3,  2},\n  {3, 2, 1,  0},\n  {2, -1,0, -1},\n  {-1, 3, -1,1}\n};\n\n// Fast splitmix64 RNG\nstatic uint64_t rnd_state;\ninline uint64_t splitmix64(){\n  uint64_t z = (rnd_state += 0x9e3779b97f4a7c15ULL);\n  z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;\n  z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;\n  return z ^ (z >> 31);\n}\n\n// Compute the tile-state after r CCW 90\u00b0 rotations.\ninline int rotateState(int s, int r){\n  if(s < 4)          return (s + r) & 3; // single\u2010curve 0..3\n  else if(r & 1)     return s ^ 1;       // double\u2010curve (4<->5) or straight (6<->7)\n  else               return s;\n}\n\nint main(){\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n\n  // Seed RNG from clock\n  rnd_state = chrono::steady_clock::now().time_since_epoch().count();\n\n  // Read input tile\u2010states\n  int orig[H][W];\n  for(int i = 0; i < H; i++){\n    string s; \n    cin >> s;\n    for(int j = 0; j < W; j++){\n      orig[i][j] = s[j] - '0';\n    }\n  }\n\n  // Precompute for each of the 8 states a 4-bit mask of open sides.\n  int openMask[8];\n  for(int s = 0; s < 8; s++){\n    int m = 0;\n    for(int d = 0; d < 4; d++){\n      if(to_dir[s][d] != -1) m |= 1 << d;\n    }\n    openMask[s] = m;\n  }\n\n  // Timing\n  auto now = chrono::steady_clock::now;\n  auto t0 = now();\n  const double TOTAL_TIME   = 1.90; // overall seconds\n  const double GREEDY_TIME  = 0.20; // for multi-start greedy\n\n  // Rotation arrays\n  static int rot[H][W], bestRot[H][W], curMask[H][W];\n\n  // Greedy edge-matching sweep: tries up to 'passes' full sweeps\n  auto greedy_sweep = [&](int passes){\n    for(int pass = 0; pass < passes; pass++){\n      bool anyChange = false;\n      for(int i = 0; i < H; i++){\n        for(int j = 0; j < W; j++){\n          int curR = rot[i][j];\n          int curS = rotateState(orig[i][j], curR);\n          int curM = openMask[curS];\n          // Compute current local\u2010match score\n          int bestScore = 0;\n          {\n            int sc = 0;\n            for(int d = 0; d < 4; d++){\n              if(curM & (1<<d)){\n                int ni = i + di[d], nj = j + dj[d];\n                if(ni>=0&&ni<H&&nj>=0&&nj<W){\n                  int ns = rotateState(orig[ni][nj], rot[ni][nj]);\n                  if(openMask[ns] & (1<<opp(d))) sc++;\n                } else {\n                  sc--; // boundary penalty\n                }\n              }\n            }\n            bestScore = sc;\n          }\n          int bestR = curR;\n          // Try the other 3 rotations\n          for(int r = 0; r < 4; r++){\n            if(r == curR) continue;\n            int s = rotateState(orig[i][j], r);\n            int m = openMask[s];\n            int sc = 0;\n            for(int d = 0; d < 4; d++){\n              if(m & (1<<d)){\n                int ni = i + di[d], nj = j + dj[d];\n                if(ni>=0&&ni<H&&nj>=0&&nj<W){\n                  int ns = rotateState(orig[ni][nj], rot[ni][nj]);\n                  if(openMask[ns] & (1<<opp(d))) sc++;\n                } else {\n                  sc--;\n                }\n              }\n            }\n            if(sc > bestScore){\n              bestScore = sc;\n              bestR = r;\n            }\n          }\n          if(bestR != curR){\n            rot[i][j] = bestR;\n            anyChange = true;\n          }\n        }\n      }\n      if(!anyChange) break;\n    }\n  };\n\n  // Compute the global \"local match\" sum over all tiles\n  auto computeLocalSum = [&](){\n    int sum = 0;\n    for(int i = 0; i < H; i++){\n      for(int j = 0; j < W; j++){\n        int s = rotateState(orig[i][j], rot[i][j]);\n        int m = openMask[s];\n        for(int d = 0; d < 4; d++){\n          if(m & (1<<d)){\n            int ni = i + di[d], nj = j + dj[d];\n            if(ni>=0&&ni<H&&nj>=0&&nj<W){\n              int ns = rotateState(orig[ni][nj], rot[ni][nj]);\n              if(openMask[ns] & (1<<opp(d))) sum++;\n            } else {\n              sum--;\n            }\n          }\n        }\n      }\n    }\n    return sum;\n  };\n\n  // ========== 1) Multi-start greedy ==========\n  int bestSum = INT_MIN;\n\n  // Start #0: all rotations = 0\n  for(int i=0;i<H;i++) for(int j=0;j<W;j++) rot[i][j]=0;\n  greedy_sweep(10);\n  bestSum = computeLocalSum();\n  for(int i=0;i<H;i++) for(int j=0;j<W;j++) bestRot[i][j]=rot[i][j];\n\n  // Additional random starts\n  const int N_STARTS = 10;\n  for(int st = 1; st < N_STARTS; st++){\n    if( chrono::duration<double>(now() - t0).count() > GREEDY_TIME ) \n      break;\n    // randomize\n    for(int i=0;i<H;i++){\n      for(int j=0;j<W;j++){\n        rot[i][j] = (int)(splitmix64() & 3);\n      }\n    }\n    greedy_sweep(10);\n    int s = computeLocalSum();\n    if(s > bestSum){\n      bestSum = s;\n      for(int i=0;i<H;i++) for(int j=0;j<W;j++) bestRot[i][j]=rot[i][j];\n    }\n  }\n\n  // ========== 2) Hill-climb on localSum ==========\n  // Initialize\n  for(int i=0;i<H;i++){\n    for(int j=0;j<W;j++){\n      rot[i][j] = bestRot[i][j];\n      int st = rotateState(orig[i][j], rot[i][j]);\n      curMask[i][j] = openMask[st];\n    }\n  }\n  int currentSum = bestSum;\n\n  // Hill-climb until no improvement for many tries or time's up\n  const int MAX_NO_IMPROVE = 200000;\n  int noImpr = 0;\n  uint64_t iter = 0;\n\n  while(true){\n    // pick random tile & a different rotation\n    int i = splitmix64() % H;\n    int j = splitmix64() % W;\n    int oldR = rot[i][j];\n    int rNew = (oldR + 1 + int(splitmix64() % 3)) & 3;\n    int oldMask = curMask[i][j];\n    int newState = rotateState(orig[i][j], rNew);\n    int newMask  = openMask[newState];\n\n    // compute \u0394localSum from changing that one tile\n    int delta = 0;\n    for(int d=0; d<4; d++){\n      int oH = (oldMask >> d) & 1;\n      int nH = (newMask >> d) & 1;\n      int ni = i + di[d], nj = j + dj[d];\n      if(ni>=0 && ni<H && nj>=0 && nj<W){\n        int neighM = curMask[ni][nj];\n        int neighH = (neighM >> opp(d)) & 1;\n        if(neighH){\n          delta += 2 * (nH - oH);\n        }\n      } else {\n        // boundary penalty\n        delta += (oH - nH);\n      }\n    }\n\n    if(delta > 0){\n      // accept\n      rot[i][j] = rNew;\n      curMask[i][j] = newMask;\n      currentSum += delta;\n      noImpr = 0;\n      if(currentSum > bestSum){\n        bestSum = currentSum;\n        for(int x=0;x<H;x++) for(int y=0;y<W;y++) bestRot[x][y] = rot[x][y];\n      }\n    } else {\n      noImpr++;\n    }\n\n    // stop if stuck or out of time\n    iter++;\n    if(noImpr > MAX_NO_IMPROVE) break;\n    if((iter & 2047) == 0){\n      if( chrono::duration<double>(now() - t0).count() > TOTAL_TIME )\n        break;\n    }\n  }\n\n  // ========== Output ==========\n  // Flatten bestRot into 900-char string\n  string out;\n  out.reserve(H*W);\n  for(int i=0;i<H;i++){\n    for(int j=0;j<W;j++){\n      out.push_back(char('0' + bestRot[i][j]));\n    }\n  }\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, T;\n    cin >> N >> T;\n    vector<string> grid(N);\n    for(int i = 0; i < N; i++){\n        cin >> grid[i];\n    }\n\n    // Baseline: perform zero moves.\n    // This is always legal (K = 0 <= T), so we get score = round(500000 * S/(N^2-1)),\n    // where S is computed on the input position.\n    // A real submission would implement a heuristic here.\n    cout << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstatic const int OFF = 10000;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, K;\n    cin >> N >> K;\n    vector<int> a(11);\n    for(int d=1; d<=10; d++) cin >> a[d];\n    vector<pair<int,int>> P(N);\n    // mark all strawberry x's and y's so we never cut through one:\n    vector<bool> xmark(2*OFF+1,false), ymark(2*OFF+1,false);\n    for(int i=0;i<N;i++){\n        int x,y;\n        cin >> x >> y;\n        P[i]={x,y};\n        if(-OFF<=x && x<=OFF) xmark[x+OFF]=true;\n        if(-OFF<=y && y<=OFF) ymark[y+OFF]=true;\n    }\n\n    // Precompute factorials up to 10:\n    double fact[11];\n    fact[0]=1;\n    for(int i=1;i<=10;i++) fact[i]=fact[i-1]*i;\n\n    // Meta\u2010search over (lambda, v, h)\n    double best_score=-1;\n    int best_v=1, best_h=1;\n\n    const double Lmin = 0.5, Lmax = 10.0, Lstep = 0.1;\n    int Lcnt = int((Lmax - Lmin)/Lstep + 1.0 + 1e-9);\n    for(int li=0; li<Lcnt; li++){\n        double lambda = Lmin + li*Lstep;\n        if(lambda<=0) continue;\n        // compute Poisson P[d] = e^{-\u03bb} \u03bb^d / d!\n        double exp_neg = exp(-lambda);\n        double Pp[11];\n        Pp[0] = exp_neg;\n        for(int d=1; d<=10; d++){\n            // Pp[d] = Pp[d-1] * \u03bb / d\n            Pp[d] = Pp[d-1] * lambda / double(d);\n        }\n        // target total pieces\n        double m_target = double(N) / lambda;\n\n        // try all v=1..K-1, h so that v+h<=K\n        for(int v=1; v<K; v++){\n            int h_max = K - v;\n            if(h_max<1) break;\n            double hv = m_target / double(v);\n            // consider floor and ceil of hv\n            int h1 = int(floor(hv));\n            int h2 = h1 + 1;\n            for(int h : {h1,h2}) {\n                if(h<1 || h>h_max) continue;\n                // approximate total pieces\n                double m_grid = double(v)*double(h);\n                // approximate b_d and score\n                double sc = 0;\n                for(int d=1; d<=10; d++){\n                    double bd = m_grid * Pp[d];\n                    sc += min(double(a[d]), bd);\n                }\n                if(sc > best_score){\n                    best_score = sc;\n                    best_v = v;\n                    best_h = h;\n                }\n            }\n        }\n    }\n\n    // Now best_v vertical and best_h horizontal cuts\n    int v = best_v, h = best_h;\n    // A tiny fallback\n    if(v<1) v=1;\n    if(h<1) h=1;\n    if(v+h > K){\n        v = K/2;\n        h = K - v;\n    }\n\n    // pick v vertical lines, h horizontal lines,\n    // evenly spaced in [-OFF,OFF], shifting to avoid xmark/ymark.\n    vector<int> vx, vy;\n    auto pick_lines = [&](bool vertical, int steps, vector<bool> &mark, vector<int> &out){\n        // we want steps-1 lines\n        for(int j=1; j<steps; j++){\n            double raw = -double(OFF) + (2.0*OFF * j)/double(steps);\n            int target = int(round(raw));\n            int found = target;\n            for(int delta=0; delta<=2*OFF; delta++){\n                int cands[2] = { target - delta, target + delta };\n                bool ok=false;\n                for(int t=0; t<2; t++){\n                    int c = cands[t];\n                    if(c < -OFF || c > OFF) continue;\n                    if(mark[c+OFF]) continue;\n                    bool dup=false;\n                    for(int x: out) if(x==c){ dup=true; break; }\n                    if(dup) continue;\n                    found = c;\n                    ok = true;\n                    break;\n                }\n                if(ok) break;\n            }\n            out.push_back(found);\n        }\n    };\n\n    pick_lines(true,  v+1, xmark, vx);\n    pick_lines(false, h+1, ymark, vy);\n\n    int k = vx.size() + vy.size();\n    // safety\n    if(k > K) k = K;\n\n    cout << k << \"\\n\";\n    // vertical\n    for(int i=0; i<(int)vx.size() && i<k; i++){\n        ll c = vx[i];\n        // line x=c\n        cout << c << \" \" << -OFF*2 << \" \" << c << \" \" << OFF*2 << \"\\n\";\n    }\n    // horizontal\n    int rem = k - (int)vx.size();\n    for(int i=0; i<rem; i++){\n        ll c = vy[i];\n        cout << -OFF*2 << \" \" << c << \" \" << OFF*2 << \" \" << c << \"\\n\";\n    }\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\n// A single operation: we place a new dot at (x1,y1), using existing dots\n// at (x2,y2),(x3,y3),(x4,y4) in that cyclic order.\nstruct Op { \n    int x1,y1, x2,y2, x3,y3, x4,y4; \n};\n\nint N, M;\nstatic bool dotp[65][65];\nstatic bool used_h[65][65], used_v[65][65];\n// Precompute the weight of each grid point\nstatic long long wgt[65][65];\n\n// Check whether the rectangle p1->p2->p3->p4 is a valid axis-aligned\n// rectangle: no other dots on its perimeter and no previously used edges.\nbool validate_rect(int x1,int y1,int x2,int y2,int x3,int y3,int x4,int y4){\n    // We assume (p1,p2,p3,p4) go around the rectangle in order.\n    int xs[4] = {x1,x2,x3,x4}, ys[4] = {y1,y2,y3,y4};\n    for(int i=0;i<4;i++){\n        int j=(i+1)&3;\n        int sx=xs[i], sy=ys[i], ex=xs[j], ey=ys[j];\n        if(sx==ex){\n            // vertical side\n            int x = sx;\n            int y0 = min(sy,ey), y1 = max(sy,ey);\n            // no used edge\n            for(int y=y0; y<y1; y++){\n                if(used_v[y][x]) return false;\n            }\n            // no other dots on interior points\n            for(int y=y0+1; y<y1; y++){\n                if(dotp[x][y]) return false;\n            }\n        } else if(sy==ey){\n            // horizontal side\n            int y = sy;\n            int x0 = min(sx,ex), x1 = max(sx,ex);\n            for(int x=x0; x<x1; x++){\n                if(used_h[y][x]) return false;\n            }\n            for(int x=x0+1; x<x1; x++){\n                if(dotp[x][y]) return false;\n            }\n        } else {\n            // not axis-aligned\n            return false;\n        }\n    }\n    return true;\n}\n\n// After we choose a rectangle, mark its 4 sides' unit-edges as used.\nvoid mark_rect(int x1,int y1,int x2,int y2,int x3,int y3,int x4,int y4){\n    int xs[4] = {x1,x2,x3,x4}, ys[4] = {y1,y2,y3,y4};\n    for(int i=0;i<4;i++){\n        int j=(i+1)&3;\n        int sx=xs[i], sy=ys[i], ex=xs[j], ey=ys[j];\n        if(sx==ex){\n            int x=sx, y0=min(sy,ey), y1=max(sy,ey);\n            for(int y=y0; y<y1; y++){\n                used_v[y][x] = true;\n            }\n        } else {\n            int y=sy, x0=min(sx,ex), x1=max(sx,ex);\n            for(int x=x0; x<x1; x++){\n                used_h[y][x] = true;\n            }\n        }\n    }\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M;\n    vector<pair<int,int>> E;\n    E.reserve(N*N);\n\n    for(int i=0;i<M;i++){\n        int x,y; cin >> x >> y;\n        dotp[x][y] = true;\n        E.emplace_back(x,y);\n    }\n\n    // center coordinate\n    int C = (N-1)/2;\n    // precompute weights\n    for(int x=0;x<N;x++){\n        for(int y=0;y<N;y++){\n            long long dx = x - C, dy = y - C;\n            wgt[x][y] = dx*dx + dy*dy + 1;\n        }\n    }\n\n    // Random engine\n    mt19937_64 rng(1234567);\n\n    // record operations\n    vector<Op> ops;\n    ops.reserve(N*N);\n\n    // time\u2010limit guard\n    clock_t start = clock();\n    const double TL = 4.8;  // leave a small margin\n\n    while(true){\n        double used = double(clock() - start)/CLOCKS_PER_SEC;\n        if(used > TL) break;\n        int Esz = (int)E.size();\n        if(Esz < 2) break;\n\n        // sample up to T random diagonals per iteration\n        int T = min(1000, Esz*2);\n        long long bestW = -1;\n        Op    bestOp{};\n\n        for(int t=0;t<T; t++){\n            if((t & 511)==0 && double(clock() - start)/CLOCKS_PER_SEC > TL)\n                break;\n\n            int i = rng() % Esz;\n            int j = rng() % Esz;\n            if(i==j) continue;\n            auto [x2,y2] = E[i];\n            auto [x4,y4] = E[j];\n            // must form a proper diagonal\n            if(x2==x4 || y2==y4) continue;\n\n            // option 1: missing corner p1 = (x4,y2), opposite p3=(x2,y4)\n            int x1 = x4, y1 = y2;\n            int x3 = x2, y3 = y4;\n            if(!dotp[x1][y1] && dotp[x3][y3]){\n                if(validate_rect(x1,y1, x2,y2, x3,y3, x4,y4)){\n                    long long W = wgt[x1][y1];\n                    if(W > bestW){\n                        bestW = W;\n                        bestOp = {x1,y1, x2,y2, x3,y3, x4,y4};\n                    }\n                }\n            }\n            // option 2: missing corner p1 = (x2,y4), opposite p3=(x4,y2)\n            int x1b = x2, y1b = y4;\n            int x3b = x4, y3b = y2;\n            if(!dotp[x1b][y1b] && dotp[x3b][y3b]){\n                if(validate_rect(x1b,y1b, x2,y2, x3b,y3b, x4,y4)){\n                    long long W = wgt[x1b][y1b];\n                    if(W > bestW){\n                        bestW = W;\n                        bestOp = {x1b,y1b, x2,y2, x3b,y3b, x4,y4};\n                    }\n                }\n            }\n        }\n\n        // if we found a valid rectangle, commit it\n        if(bestW >= 0){\n            auto &o = bestOp;\n            dotp[o.x1][o.y1] = true;\n            E.emplace_back(o.x1,o.y1);\n            mark_rect(o.x1,o.y1, o.x2,o.y2, o.x3,o.y3, o.x4,o.y4);\n            ops.push_back(o);\n        } else {\n            // no more valid sample\u2192stop\n            break;\n        }\n    }\n\n    // Output\n    cout << ops.size() << \"\\n\";\n    for(auto &o: ops){\n        cout\n          << o.x1 << \" \" << o.y1 << \" \"\n          << o.x2 << \" \" << o.y2 << \" \"\n          << o.x3 << \" \" << o.y3 << \" \"\n          << o.x4 << \" \" << o.y4 << \"\\n\";\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n// simulate one tilt on a 10\u00d710 grid\n// dir = 'F','B','L','R'\nstatic void tilt(const int in[10][10], int out[10][10], char dir){\n    // temp buffer for one line\n    int buf[10];\n    if(dir=='F'){\n        // push everything to i=0\n        for(int j=0;j<10;j++){\n            int m=0;\n            for(int i=0;i<10;i++) if(in[i][j]) buf[m++] = in[i][j];\n            for(int i=0;i<10;i++){\n                out[i][j] = (i<m ? buf[i] : 0);\n            }\n        }\n    } else if(dir=='B'){\n        // push everything to i=9\n        for(int j=0;j<10;j++){\n            int m=0;\n            for(int i=9;i>=0;i--) if(in[i][j]) buf[m++] = in[i][j];\n            for(int i=9, k=0;i>=0;i--,k++){\n                out[i][j] = (k<m ? buf[k] : 0);\n            }\n        }\n    } else if(dir=='L'){\n        // push everything to j=0\n        for(int i=0;i<10;i++){\n            int m=0;\n            for(int j=0;j<10;j++) if(in[i][j]) buf[m++] = in[i][j];\n            for(int j=0;j<10;j++){\n                out[i][j] = (j<m ? buf[j] : 0);\n            }\n        }\n    } else { // 'R'\n        // push everything to j=9\n        for(int i=0;i<10;i++){\n            int m=0;\n            for(int j=9;j>=0;j--) if(in[i][j]) buf[m++] = in[i][j];\n            for(int j=9,k=0;j>=0;j--,k++){\n                out[i][j] = (k<m ? buf[k] : 0);\n            }\n        }\n    }\n}\n\n// compute sum of (component size)^2 on a 10\u00d710 grid\nstatic int calcScore(const int g[10][10]){\n    bool vis[10][10]={0};\n    int qx[100], qy[100];\n    int total = 0;\n    static const int di[4]={-1,1,0,0}, dj[4]={0,0,-1,1};\n    for(int i=0;i<10;i++) for(int j=0;j<10;j++){\n        if(g[i][j] && !vis[i][j]){\n            int f = g[i][j];\n            int head=0, tail=0;\n            vis[i][j]=true;\n            qx[tail]=i; qy[tail]=j; tail++;\n            while(head<tail){\n                int x=qx[head], y=qy[head]; head++;\n                for(int d=0;d<4;d++){\n                    int ni=x+di[d], nj=y+dj[d];\n                    if(ni>=0&&ni<10&&nj>=0&&nj<10\n                       && !vis[ni][nj] && g[ni][nj]==f){\n                        vis[ni][nj]=true;\n                        qx[tail]=ni; qy[tail]=nj; tail++;\n                    }\n                }\n            }\n            total += tail*tail;\n        }\n    }\n    return total;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // read in the 100 flavors\n    int F[101];\n    for(int i=1;i<=100;i++){\n        cin >> F[i];\n    }\n\n    // the board, 0=empty, 1/2/3=flavor\n    int grid[10][10]={0};\n\n    // our \u201cdefault\u201d mapping so we only break it if there's a real gain\n    char defdir[4] = {0,'L','R','F',};\n\n    for(int t=1;t<=100;t++){\n        int p; \n        if(!(cin>>p)) break;\n        // locate the p-th empty cell in row-major (front-to-back, left-to-right)\n        int cnt=0, si=0, sj=0;\n        for(int i=0;i<10;i++){\n            for(int j=0;j<10;j++){\n                if(grid[i][j]==0){\n                    cnt++;\n                    if(cnt==p){\n                        si=i; sj=j;\n                        goto FOUND;\n                    }\n                }\n            }\n        }\n    FOUND:\n        grid[si][sj] = F[t];\n\n        // build candidate list: default first, then the other 3\n        char cand[4];\n        cand[0] = defdir[F[t]];\n        int m=1;\n        for(char c: {'F','B','L','R'}){\n            if(c!=cand[0]) cand[m++]=c;\n        }\n\n        // greedy pick\n        int bestScore = -1;\n        char bestDir = cand[0];\n        int tmp[10][10];\n        for(int k=0;k<4;k++){\n            char d = cand[k];\n            tilt(grid, tmp, d);\n            int sc = calcScore(tmp);\n            if(sc > bestScore){\n                bestScore = sc;\n                bestDir = d;\n            }\n        }\n\n        // apply bestDir to our real grid\n        tilt(grid, tmp, bestDir);\n        for(int i=0;i<10;i++)\n            for(int j=0;j<10;j++)\n                grid[i][j] = tmp[i][j];\n\n        // output & flush\n        cout << bestDir << '\\n' << flush;\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    // Choose the smallest N so that L = N*(N-1)/2 >= M-1\n    int N = 4;\n    int L = N*(N-1)/2;\n    while(L < M-1){\n        ++N;\n        L = N*(N-1)/2;\n    }\n    cout<<N<<\"\\n\";\n\n    // Emit G_k: exactly k ones in the lex\u2010order bitstring\n    // (so G_k has exactly k edges)\n    for(int k=0;k<M;k++){\n        int ones = min(k, L);\n        // first `ones` bits = '1', rest = '0'\n        cout<<string(ones,'1')<<string(L-ones,'0')<<\"\\n\";\n    }\n    cout<<flush;\n\n    // Now handle 100 queries:\n    // For each H we read the L\u2010bit string, count '1's, de-bias\n    // and round to the nearest k in [0..M-1].\n    for(int qi=0;qi<100;qi++){\n        string H;\n        cin>>H;\n        if(!cin)break;\n        int cnt=0;\n        for(char c:H) if(c=='1') ++cnt;\n        int t;\n        if(eps==0.0){\n            // no noise \u2192 direct\n            t = min(cnt, M-1);\n        } else {\n            // invert: cnt \u2248 eps*L + (1-2eps)*k\n            double x = ( (double)cnt - eps*(double)L ) / (1.0 - 2.0*eps );\n            t = int( round(x) );\n            if(t<0) t=0;\n            else if(t>=M) t=M-1;\n        }\n        cout<<t<<\"\\n\"<<flush;\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll INF = (ll)4e18;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n    vector<int> U(M), V(M);\n    vector<ll> 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    // discard coordinates\n    for(int i = 0; i < N; i++){\n        int x,y; \n        cin >> x >> y;\n    }\n\n    // build adjacency: (neighbor, edge_id)\n    vector<vector<pair<int,int>>> adj(N);\n    adj.reserve(N);\n    vector<int> degree(N, 0);\n    for(int e = 0; e < M; e++){\n        adj[U[e]].push_back({V[e], e});\n        adj[V[e]].push_back({U[e], e});\n        degree[U[e]]++;\n        degree[V[e]]++;\n    }\n\n    // Decide B = number of sources for approximate Brandes\n    int B = min(N, 100);\n    vector<int> sources;\n    sources.reserve(B);\n\n    // 1) take top B/2 by degree\n    vector<int> ordV(N);\n    iota(ordV.begin(), ordV.end(), 0);\n    sort(ordV.begin(), ordV.end(), [&](int a, int b){\n        return degree[a] > degree[b];\n    });\n    for(int i = 0; i < B/2; i++){\n        sources.push_back(ordV[i]);\n    }\n    // 2) plus B/2 uniform random\n    mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());\n    shuffle(ordV.begin(), ordV.end(), rng);\n    for(int i = 0; (int)sources.size() < B; i++){\n        int v = ordV[i];\n        // skip if already taken\n        if(degree[v] < 0) continue;\n        sources.push_back(v);\n    }\n    // mark to avoid duplicates\n    for(int v : sources) degree[v] = -1;\n\n    // centrality accumulator\n    vector<double> central(M, 0.0);\n\n    // temporaries for one run\n    vector<ll> dist(N);\n    vector<double> sigma(N), delta(N);\n    vector<vector<pair<int,int>>> pred(N);\n    vector<int> S; S.reserve(N);\n\n    // Brandes for weighted graph, from each source\n    for(int s : sources){\n        // init\n        fill(dist.begin(), dist.end(), INF);\n        fill(sigma.begin(), sigma.end(), 0.0);\n        for(int i = 0; i < N; i++){\n            pred[i].clear();\n        }\n        dist[s] = 0;\n        sigma[s] = 1.0;\n        S.clear();\n\n        // Dijkstra\n        using pli = pair<ll,int>;\n        priority_queue<pli, vector<pli>, greater<pli>> pq;\n        pq.push({0, s});\n        while(!pq.empty()){\n            auto [d,u] = pq.top(); pq.pop();\n            if(d != dist[u]) continue;\n            S.push_back(u);\n            for(auto &ed : adj[u]){\n                int v = ed.first, e = ed.second;\n                ll nd = d + W[e];\n                if(nd < dist[v]){\n                    dist[v] = nd;\n                    sigma[v] = sigma[u];\n                    pred[v].clear();\n                    pred[v].push_back({u,e});\n                    pq.push({nd, v});\n                } else if(nd == dist[v]){\n                    sigma[v] += sigma[u];\n                    pred[v].push_back({u,e});\n                }\n            }\n        }\n\n        // accumulate dependencies\n        fill(delta.begin(), delta.end(), 0.0);\n        for(int idx = (int)S.size() - 1; idx >= 0; idx--){\n            int w = S[idx];\n            for(auto &pp : pred[w]){\n                int v = pp.first, e = pp.second;\n                double c = (sigma[v]/sigma[w]) * (1.0 + delta[w]);\n                delta[v] += c;\n                central[e] += c;\n            }\n        }\n    }\n\n    // build a weighted\u2010centrality vector\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    vector<double> wscore(M);\n    for(int e = 0; e < M; e++){\n        // prefer edges that are both highly \u201cbetween\u201d and long\n        wscore[e] = central[e] * (double)W[e];\n    }\n    sort(order.begin(), order.end(),\n         [&](int a, int b){\n             return wscore[a] > wscore[b];\n         });\n\n    // zig\u2010zag assignment across D days\n    vector<int> ans(M);\n    for(int i = 0; i < M; i++){\n        int e = order[i];\n        int block = i / D;\n        int pos   = i % D;\n        int day;\n        if((block & 1) == 0){\n            // left\u2192right\n            day = pos + 1;\n        } else {\n            // right\u2192left\n            day = D - pos;\n        }\n        ans[e] = day;\n    }\n\n    // output\n    for(int i = 0; i < M; i++){\n        cout << ans[i] << (i+1<M ? ' ' : '\\n');\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\n    int D;\n    cin >> D;\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for(int i = 0; i < D; i++) cin >> f1[i];\n    for(int i = 0; i < D; i++) cin >> r1[i];\n    for(int i = 0; i < D; i++) cin >> f2[i];\n    for(int i = 0; i < D; i++) cin >> r2[i];\n\n    int N = D * D * D;\n    // Flatten index: idx = x*D*D + y*D + z\n    auto idx = [&](int x, int y, int z){\n        return x * D * D + y * D + z;\n    };\n\n    // Compute need1[x][y][z], need2[x][y][z]\n    vector<char> need1(N, 0), need2(N, 0), visited(N, 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 n1 = (f1[z][x]=='1' && r1[z][y]=='1');\n                bool n2 = (f2[z][x]=='1' && r2[z][y]=='1');\n                need1[idx(x,y,z)] = n1;\n                need2[idx(x,y,z)] = n2;\n            }\n        }\n    }\n\n    vector<int> b1(N, 0), b2(N, 0);\n    int block_id = 0;\n    // Directions for 6-neighborhood\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    // 1) Group all voxels needed in *both* silhouettes by connected component\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                int id0 = idx(x,y,z);\n                if(need1[id0] && need2[id0] && !visited[id0]){\n                    // BFS this component\n                    vector<int> comp;\n                    queue<tuple<int,int,int>> q;\n                    q.emplace(x,y,z);\n                    visited[id0] = 1;\n                    while(!q.empty()){\n                        auto [cx,cy,cz] = q.front(); q.pop();\n                        int cidx = idx(cx,cy,cz);\n                        comp.push_back(cidx);\n                        for(int d = 0; d < 6; d++){\n                            int nx = cx + dx[d];\n                            int ny = cy + dy[d];\n                            int nz = cz + dz[d];\n                            if(nx<0||nx>=D||ny<0||ny>=D||nz<0||nz>=D) continue;\n                            int nidx = idx(nx,ny,nz);\n                            if(!visited[nidx] && need1[nidx] && need2[nidx]){\n                                visited[nidx] = 1;\n                                q.emplace(nx,ny,nz);\n                            }\n                        }\n                    }\n                    // Assign one block to the entire component\n                    ++block_id;\n                    for(int v : comp){\n                        b1[v] = block_id;\n                        b2[v] = block_id;\n                    }\n                }\n            }\n        }\n    }\n\n    // 2) Voxels unique to shape 1\n    for(int i = 0; i < N; i++){\n        if(need1[i] && !need2[i]){\n            ++block_id;\n            b1[i] = block_id;\n        }\n    }\n    // 3) Voxels unique to shape 2\n    for(int i = 0; i < N; i++){\n        if(need2[i] && !need1[i]){\n            ++block_id;\n            b2[i] = block_id;\n        }\n    }\n\n    // Output\n    cout << block_id << \"\\n\";\n    for(int i = 0; i < N; i++){\n        cout << b1[i] << (i+1==N?'\\n':' ');\n    }\n    for(int i = 0; i < N; i++){\n        cout << b2[i] << (i+1==N?'\\n':' ');\n    }\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll INF = (1LL<<60);\n\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n): p(n,-1), r(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\n    int N,M,K;\n    cin>>N>>M>>K;\n    vector<ll> x(N), y(N);\n    for(int i=0;i<N;i++) cin>>x[i]>>y[i];\n\n    vector<vector<pair<int,pair<ll,int>>>> g(N);\n    vector<int> U(M), V(M);\n    vector<ll> W(M);\n    for(int j=0;j<M;j++){\n        int u,v; ll w;\n        cin>>u>>v>>w;\n        --u; --v;\n        U[j]=u; V[j]=v; W[j]=w;\n        g[u].push_back({v,{w,j}});\n        g[v].push_back({u,{w,j}});\n    }\n\n    vector<ll> a(K), b(K);\n    for(int k=0;k<K;k++){\n        cin>>a[k]>>b[k];\n    }\n\n    // 1) For each station, find max squared\u2010distance to any resident\n    vector<ll> max_d2(N,0);\n    for(int k=0;k<K;k++){\n        ll best=LLONG_MAX; int bi=0;\n        for(int i=0;i<N;i++){\n            ll dx = x[i]-a[k], dy = y[i]-b[k];\n            ll d2=dx*dx+dy*dy;\n            if(d2<best){ best=d2; bi=i; }\n        }\n        max_d2[bi] = max(max_d2[bi], best);\n    }\n\n    // 2) Set P[i] = ceil(sqrt(max_d2[i]))\n    vector<int> P(N,0);\n    for(int i=0;i<N;i++){\n        if(max_d2[i]>0){\n            ll d2=max_d2[i];\n            ll s=(ll)floor(sqrt((long double)d2));\n            while(s*s<d2) s++;\n            while(s>0 && (s-1)*(s-1)>=d2) s--;\n            P[i]=(int)s;\n        }\n    }\n\n    // 3) Gather terminals = { station 1 (0) } U { i | P[i]>0, i>0 }\n    vector<int> sourceList;\n    sourceList.push_back(0);\n    for(int i=1;i<N;i++){\n        if(P[i]>0) sourceList.push_back(i);\n    }\n    int T = (int)sourceList.size();\n\n    // 4) Run Dijkstra from each terminal to build dist & parent pointers\n    vector<vector<ll>> distFrom(T, vector<ll>(N, INF));\n    vector<vector<int>> parentEdge(T, vector<int>(N,-1)), parentNode(T, vector<int>(N,-1));\n    for(int si=0;si<T;si++){\n        int src = sourceList[si];\n        auto &dist = distFrom[si];\n        dist[src]=0;\n        priority_queue<pair<ll,int>,\n          vector<pair<ll,int>>, greater<pair<ll,int>>> pq;\n        pq.push({0,src});\n        while(!pq.empty()){\n            auto [cd,u]=pq.top(); pq.pop();\n            if(cd>dist[u]) continue;\n            for(auto &ed : g[u]){\n                int v=ed.first, id=ed.second.second;\n                ll w=ed.second.first;\n                if(dist[v] > cd + w){\n                    dist[v] = cd + w;\n                    parentEdge[si][v] = id;\n                    parentNode[si][v] = u;\n                    pq.push({dist[v], v});\n                }\n            }\n        }\n    }\n\n    // 5) Build the complete\u2010graph edges on terminals\n    struct E{ ll w; int i,j; };\n    vector<E> edges;\n    edges.reserve((T*(T-1))/2);\n    for(int i=0;i<T;i++){\n        for(int j=i+1;j<T;j++){\n            ll d = distFrom[i][ sourceList[j] ];\n            edges.push_back({d,i,j});\n        }\n    }\n    sort(edges.begin(), edges.end(),\n         [](auto &A, auto &B){ return A.w < B.w; });\n\n    // 6) Kruskal\u2010MST on the terminals\n    DSU dsu(T);\n    vector<pair<int,int>> steinerEdges;\n    steinerEdges.reserve(T-1);\n    for(auto &e : edges){\n        if(dsu.unite(e.i, e.j)){\n            steinerEdges.emplace_back(e.i, e.j);\n            if((int)steinerEdges.size() == T-1) break;\n        }\n    }\n\n    // 7) Reconstruct the actual graph\u2010edges B[]\n    vector<int> B(M,0);\n    for(auto &pp : steinerEdges){\n        int si = pp.first;\n        int sj = pp.second;\n        int u = sourceList[si];\n        int v = sourceList[sj];\n        // walk back from v to u along parent[] of source si\n        int cur = v;\n        while(cur != u){\n            int eid = parentEdge[si][cur];\n            B[eid] = 1;\n            cur = parentNode[si][cur];\n        }\n    }\n\n    // 8) Output\n    for(int i=0;i<N;i++){\n        cout<<P[i]<<(i+1<N?' ':'\\n');\n    }\n    for(int j=0;j<M;j++){\n        cout<<B[j]<<(j+1<M?' ':'\\n');\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    const int N = 30;\n    const int M = N*(N+1)/2; // 465\n    vector<int> posBall(M), curPos(M);\n    // read input\n    for(int x=0, idx=0; x<N; x++){\n        for(int y=0; y<=x; y++, idx++){\n            int b; \n            cin >> b;\n            posBall[idx] = b;\n            curPos[b] = idx;\n        }\n    }\n    // build (x,y)<->id mappings\n    vector<pair<int,int>> id2xy(M);\n    auto xy2id = [&](int x,int y){\n        return x*(x+1)/2 + y;\n    };\n    for(int x=0, idx=0; x<N; x++){\n        for(int y=0; y<=x; y++, idx++){\n            id2xy[idx] = {x,y};\n        }\n    }\n    // adjacency lists on the triangular grid\n    vector<vector<int>> adj(M);\n    for(int id=0; id<M; id++){\n        auto [x,y] = id2xy[id];\n        if(x>0 && y>0)       adj[id].push_back(xy2id(x-1,y-1));\n        if(x>0 && y<=x-1)    adj[id].push_back(xy2id(x-1,y));\n        if(y>0)              adj[id].push_back(xy2id(x,y-1));\n        if(y< x)             adj[id].push_back(xy2id(x,y+1));\n        if(x+1< N)          {\n            adj[id].push_back(xy2id(x+1,y));\n            adj[id].push_back(xy2id(x+1,y+1));\n        }\n    }\n\n    vector<bool> locked(M,false), vis(M);\n    vector<int> parent(M);\n    struct Move { int x1,y1,x2,y2; };\n    vector<Move> moves;\n    moves.reserve(M * 12);\n\n    // for each label L=0..M-1, BFS in the subgraph { id>=L }\n    for(int L=0; L<M; L++){\n        int s = curPos[L];\n        int t = L; // target id = L\n        if(s!=t){\n            // BFS from s to t, only visiting id>=L\n            fill(vis.begin(), vis.end(), false);\n            fill(parent.begin(), parent.end(), -1);\n            queue<int> q;\n            q.push(s);\n            vis[s]=true;\n            while(!q.empty() && !vis[t]){\n                int u=q.front(); q.pop();\n                for(int v: adj[u]){\n                    if(vis[v]) continue;\n                    if(v< L) continue; // skip locked region\n                    vis[v]=true;\n                    parent[v]=u;\n                    q.push(v);\n                    if(v==t) break;\n                }\n            }\n            // reconstruct path s->...->t\n            vector<int> path;\n            int u = t;\n            while(u!=-1){\n                path.push_back(u);\n                if(u==s) break;\n                u = parent[u];\n            }\n            reverse(path.begin(), path.end());\n            // bubble L along that path\n            for(int i=1; i<int(path.size()); i++){\n                int u0=path[i-1], v0=path[i];\n                int A = posBall[u0], B = posBall[v0];\n                // swap them\n                posBall[u0]=B; posBall[v0]=A;\n                curPos[A]=v0;  curPos[B]=u0;\n                auto [x1,y1]=id2xy[u0];\n                auto [x2,y2]=id2xy[v0];\n                moves.push_back({x1,y1,x2,y2});\n            }\n        }\n        // lock the target cell so it never moves again\n        locked[t]=true;\n    }\n\n    // output\n    cout << moves.size() << \"\\n\";\n    for(auto &m: moves){\n        cout << m.x1 << \" \" << m.y1 << \" \"\n             << m.x2 << \" \" << m.y2 << \"\\n\";\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\n// We know D==9 always\nstatic const int MAXD = 9;\nstatic int D, N, C;\nstatic bool isObs[MAXD][MAXD];\nstatic int dist0[MAXD][MAXD], maxDist;\nstatic int occ[MAXD][MAXD], posT[MAXD][MAXD];\nstatic int ex, ey;\nstatic int dx[4] = {1,-1,0,0}, dy[4] = {0,0,1,-1};\n\n// For BFS\nstruct P { int x,y; };\nstatic P Q[MAXD*MAXD];\n\n// For AP\u2010finding\nstatic bool visitedAP[MAXD*MAXD], isAP[MAXD*MAXD];\nstatic int disc[MAXD*MAXD], low[MAXD*MAXD], parentAP[MAXD*MAXD], dfsTime;\n\nvoid dfs_art(int u){\n    visitedAP[u] = true;\n    disc[u] = low[u] = ++dfsTime;\n    int ux = u / D, uy = u % D;\n    int child = 0;\n    for(int k=0;k<4;k++){\n        int vx = ux + dx[k], vy = uy + dy[k];\n        if(vx<0||vx>=D||vy<0||vy>=D) continue;\n        if(occ[vx][vy]!=0) continue; // only traverse free squares\n        int v = vx*D + vy;\n        if(!visitedAP[v]){\n            parentAP[v] = u;\n            ++child;\n            dfs_art(v);\n            low[u] = min(low[u], low[v]);\n            // non\u2010root condition\n            if(parentAP[u]!=-1 && low[v]>=disc[u]){\n                isAP[u] = true;\n            }\n        } else if(v != parentAP[u]){\n            low[u] = min(low[u], disc[v]);\n        }\n    }\n    // root condition\n    if(parentAP[u]==-1 && child>1){\n        isAP[u] = true;\n    }\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> D >> N;\n    // entrance\n    ex = 0; \n    ey = (D-1)/2;\n    // obstacles\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        isObs[i][j] = false;\n    }\n    for(int i=0;i<N;i++){\n        int r,c; \n        cin >> r >> c;\n        isObs[r][c] = true;\n    }\n    // precompute static BFS\u2010distances from entrance\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        dist0[i][j] = -1;\n    }\n    int qs=0, qe=0;\n    dist0[ex][ey] = 0;\n    Q[qe++] = {ex,ey};\n    while(qs<qe){\n        auto [x,y] = Q[qs++];\n        for(int k=0;k<4;k++){\n            int nx=x+dx[k], ny=y+dy[k];\n            if(nx<0||nx>=D||ny<0||ny>=D) continue;\n            if(isObs[nx][ny]) continue;\n            if(dist0[nx][ny]!=-1) continue;\n            dist0[nx][ny] = dist0[x][y] + 1;\n            Q[qe++] = {nx,ny};\n        }\n    }\n    maxDist = 0;\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        if(!isObs[i][j] && !(i==ex && j==ey)){\n            maxDist = max(maxDist, dist0[i][j]);\n        }\n    }\n\n    C = D*D - 1 - N;  // total containers\n    // occ: -1=obstacle, 0=free, 1=occupied\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        occ[i][j]   = isObs[i][j] ? -1 : 0;\n        posT[i][j] = -1;\n    }\n\n    // --- Storing phase (interactive) ---\n    for(int step=0; step<C; step++){\n        int t; \n        cin >> t;\n\n        // 1) BFS to find currently reachable FREE squares\n        static bool vis[MAXD][MAXD];\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++) vis[i][j]=false;\n        qs=0; qe=0;\n        vis[ex][ey] = true;\n        Q[qe++] = {ex,ey};\n        while(qs<qe){\n            auto [x,y] = Q[qs++];\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(vis[nx][ny]) continue;\n                if(occ[nx][ny]!=0) continue;   // only walk on free\n                vis[nx][ny] = true;\n                Q[qe++] = {nx,ny};\n            }\n        }\n\n        // 2) find articulation points in *this* free\u2010graph\n        //    so we never break connectivity\n        int totalNodes = D*D;\n        for(int id=0; id<totalNodes; id++){\n            visitedAP[id] = false;\n            isAP[id]      = false;\n            parentAP[id] = -1;\n        }\n        dfsTime = 0;\n        int root = ex*D + ey;\n        dfs_art(root);\n        // (we trust the graph is still connected)\n\n        // 3) pick among non\u2010AP reachable free squares\n        double target = (C>1 ? (double)t/(C-1)*maxDist : 0.0);\n        double bestErr = 1e100;\n        int bestX=-1, bestY=-1, bestD0=-1;\n\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            if(i==ex && j==ey) continue;\n            if(!vis[i][j])       continue;  // not reachable\n            if(occ[i][j]!=0)     continue;  // not free\n            int id = i*D + j;\n            if(isAP[id])         continue;  // would disconnect!\n\n            int d0 = dist0[i][j];\n            double e = fabs(d0 - target);\n            if(e + 1e-9 < bestErr ||\n               (fabs(e - bestErr)<1e-9 && d0 < bestD0))\n            {\n                bestErr = e;\n                bestD0  = d0;\n                bestX   = i;\n                bestY   = j;\n            }\n        }\n        // Fallback (should never really be needed):\n        if(bestX<0){\n            for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n                if(i==ex && j==ey) continue;\n                if(!vis[i][j])       continue;\n                if(occ[i][j]!=0)     continue;\n                int d0 = dist0[i][j];\n                double e = fabs(d0 - target);\n                if(e + 1e-9 < bestErr ||\n                   (fabs(e - bestErr)<1e-9 && d0 < bestD0))\n                {\n                    bestErr = e;\n                    bestD0  = d0;\n                    bestX   = i;\n                    bestY   = j;\n                }\n            }\n        }\n        // commit\n        occ[bestX][bestY] = 1;\n        posT[bestX][bestY] = t;\n        // output + flush\n        cout << bestX << \" \" << bestY << \"\\n\" << flush;\n    }\n\n    // --- Retrieval phase (offline) ---\n    vector<pair<int,int>> ans;\n    ans.reserve(C);\n    for(int iter=0; iter<C; iter++){\n        // BFS over empty squares\n        static bool vis2[MAXD][MAXD];\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++) vis2[i][j]=false;\n        qs=0; qe=0;\n        vis2[ex][ey] = true;\n        Q[qe++] = {ex,ey};\n        while(qs<qe){\n            auto [x,y] = Q[qs++];\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(vis2[nx][ny]) continue;\n                if(occ[nx][ny]!=0) continue;\n                vis2[nx][ny] = true;\n                Q[qe++] = {nx,ny};\n            }\n        }\n        // among occupied neighbours pick smallest tag\n        int pickT = INT_MAX, px=-1, py=-1;\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            if(occ[i][j]!=1) continue;\n            bool reachable = false;\n            for(int k=0;k<4 && !reachable;k++){\n                int nx=i+dx[k], ny=j+dy[k];\n                if(nx>=0&&nx<D&&ny>=0&&ny<D && vis2[nx][ny]){\n                    reachable = true;\n                }\n            }\n            if(!reachable) continue;\n            int tt = posT[i][j];\n            if(tt < pickT){\n                pickT = tt;\n                px = i; py = j;\n            }\n        }\n        // remove it\n        occ[px][py] = 0;\n        ans.emplace_back(px,py);\n    }\n\n    // print all retrieval moves\n    for(auto &p: ans){\n        cout << p.first << \" \" << p.second << \"\\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    cin >> n >> m;\n    vector<vector<int>> c(n, vector<int>(n));\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < n; j++){\n            cin >> c[i][j];\n        }\n    }\n    // Baseline: just reproduce the input map verbatim.\n    // This preserves all ward-to-ward and ward-to-outside adjacencies,\n    // and keeps every color's region connected.\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < n; j++){\n            cout << c[i][j] << (j+1 < n ? ' ' : '\\n');\n        }\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, D, Q;\nint usedQ = 0;\nvector<int> comp_cache; // flatten N\u00d7N, value = -2 unknown, >0 means i>j, <0 means i<j, 0 means equal\n\n// do one compare of item i vs j, cache it, return +1 if w[i]>w[j], -1 if w[i]<w[j], 0 if equal\nint compare_raw(int i, int j){\n    if(i==j) return 0;\n    int &c = comp_cache[i*N + j];\n    if(c != -2) return c;\n    // issue one query\n    cout << 1 << ' ' << 1 << ' ' << i << ' ' << j << '\\n' << flush;\n    char resp;\n    cin >> resp;\n    usedQ++;\n    int res = (resp=='>' ? 1 : (resp=='<' ? -1 : 0));\n    c = res;\n    comp_cache[j*N + i] = -res;\n    return res;\n}\n// comparator for mergesort: true if i should come before j, i.e. w[i] > w[j], break ties by i<j\nbool cmp_items(int i, int j){\n    int v = compare_raw(i,j);\n    if(v>0) return true;\n    if(v<0) return false;\n    return i<j;\n}\n\n// simple recursive mergesort on vector of IDs\nvector<int> interactive_mergesort(const vector<int> &a){\n    int n = a.size();\n    if(n<=1) return a;\n    int m = n/2;\n    vector<int> left(a.begin(), a.begin()+m), right(a.begin()+m, a.end());\n    left  = interactive_mergesort(left);\n    right = interactive_mergesort(right);\n    vector<int> res; res.reserve(n);\n    int i=0, j=0;\n    while(i<(int)left.size() && j<(int)right.size()){\n        if(cmp_items(left[i], right[j])) res.push_back(left[i++]);\n        else                                   res.push_back(right[j++]);\n    }\n    while(i<(int)left.size())  res.push_back(left[i++]);\n    while(j<(int)right.size()) res.push_back(right[j++]);\n    return res;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> D >> Q;\n    comp_cache.assign(N*N, -2);\n\n    // compute ceil(log2 N)\n    int LG = 0;\n    while((1<<LG) < N) LG++;\n    long long needSortQ = 1LL * N * LG;\n\n    vector<int> final_assign(N,0);\n\n    if(Q >= needSortQ){\n        // 1) fully sort all items\n        vector<int> items(N);\n        iota(items.begin(), items.end(), 0);\n        vector<int> sorted = interactive_mergesort(items);\n        // usedQ <= needSortQ <= Q\n\n        // 2) waste out any remaining queries with harmless dummy compares\n        for(; usedQ < Q; usedQ++){\n            cout << 1 << ' ' << 1 << ' ' << 0 << ' ' << 1 << '\\n' << flush;\n            char _; cin >> _;\n        }\n\n        // 3) greedy LPT on pseudo-weights = (N - rank)\n        vector<long long> bin_sum(D, 0);\n        for(int rank = 0; rank < N; rank++){\n            int id = sorted[rank];\n            // find bin with minimal sum\n            int best = 0;\n            for(int b = 1; b < D; b++){\n                if(bin_sum[b] < bin_sum[best]) best = b;\n            }\n            final_assign[id] = best;\n            bin_sum[best] += (N - rank);\n        }\n    }\n    else {\n        // fallback: Q too small to guarantee full sort\n        // do exactly Q dummy queries, then round-robin\n        for(int q = 0; q < Q; q++){\n            cout << 1 << ' ' << 1 << ' ' << 0 << ' ' << 1 << '\\n' << flush;\n            char _; cin >> _;\n        }\n        for(int i = 0; i < N; i++){\n            final_assign[i] = i % D;\n        }\n    }\n\n    // 4) output final assignment\n    for(int i = 0; i < N; i++){\n        cout << final_assign[i] << (i+1==N?'\\n':' ');\n    }\n    cout << flush;\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int,int>;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int INF = 1000000;\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> st(m);\n    for(int i = 0; i < m; i++){\n        st[i].resize(n/m);\n        for(int j = 0; j < n/m; j++){\n            cin >> st[i][j];\n        }\n    }\n\n    // min_content[i] = minimum label currently in stack i (or INF if empty)\n    vector<int> min_content(m, INF);\n    for(int i = 0; i < m; i++){\n        if(!st[i].empty()){\n            int mn = INF;\n            for(int x: st[i]) mn = min(mn, x);\n            min_content[i] = mn;\n        }\n    }\n\n    vector<pii> ops;\n    ops.reserve(2*n);\n\n    // For each v=1..n we need to expose and remove it.\n    for(int v = 1; v <= n; v++){\n        // 1) find v in some stack s at depth j\n        int s = -1, j = -1;\n        for(int i = 0; i < m && s==-1; i++){\n            for(int k = 0; k < (int)st[i].size(); k++){\n                if(st[i][k] == v){\n                    s = i; j = k;\n                    break;\n                }\n            }\n        }\n        int sz = st[s].size();\n        int above = sz - (j+1);\n        // 2) if there are boxes above it, move that entire segment\n        if(above > 0){\n            // collect the segment and its minimum\n            vector<int> segment;\n            segment.reserve(above);\n            int segment_min = INF;\n            for(int p = j+1; p < sz; p++){\n                segment.push_back(st[s][p]);\n                segment_min = min(segment_min, st[s][p]);\n            }\n            // choose destination stack t != s\n            int best_t = -1;\n            // 2a) first try to find \"safe\" stacks whose min_content > segment_min\n            //     among those pick the one of minimal height\n            int best_h = INT_MAX;\n            for(int t = 0; t < m; t++){\n                if(t == s) continue;\n                if(min_content[t] > segment_min){\n                    int h = st[t].size();\n                    if(h < best_h){\n                        best_h = h;\n                        best_t = t;\n                    }\n                }\n            }\n            // 2b) if no safe stack found, pick t with maximal min_content[t],\n            //     tie\u2010break on minimal height\n            if(best_t == -1){\n                int best_min = -1;\n                best_h = INT_MAX;\n                for(int t = 0; t < m; t++){\n                    if(t == s) continue;\n                    int mc = min_content[t];\n                    if(mc > best_min || (mc == best_min && (int)st[t].size() < best_h)){\n                        best_min = mc;\n                        best_h = st[t].size();\n                        best_t = t;\n                    }\n                }\n            }\n            // perform the move: we must specify the box immediately above v\n            int w = st[s][j+1];\n            ops.emplace_back(w, best_t+1);\n            // physically move it in our simulation\n            st[s].resize(j+1);\n            min_content[s] = INF;\n            for(int x: st[s]) min_content[s] = min(min_content[s], x);\n            for(int x: segment){\n                st[best_t].push_back(x);\n                min_content[best_t] = min(min_content[best_t], x);\n            }\n        }\n        // 3) now v is at the top of stack s, carry it out\n        ops.emplace_back(v, 0);\n        st[s].pop_back();\n        // update min_content[s]\n        min_content[s] = INF;\n        for(int x: st[s]) min_content[s] = min(min_content[s], x);\n    }\n\n    // output all operations\n    for(auto &op: ops){\n        cout << op.first << \" \" << op.second << \"\\n\";\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int,int>;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<string> h(N-1), v(N);\n    for(int i=0;i<N-1;i++) cin >> h[i];\n    for(int i=0;i<N;i++)   cin >> v[i];\n    int V = N*N;\n    vector<int> d(V);\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            cin >> d[i*N+j];\n        }\n    }\n    // build adjacency + move\u2010labels\n    vector<vector<pair<int,char>>> nbr(V);\n    auto id = [&](int i,int j){return i*N+j;};\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            int u = id(i,j);\n            if(i+1<N && h[i][j]=='0'){\n                int v2 = id(i+1,j);\n                nbr[u].emplace_back(v2,'D');\n                nbr[v2].emplace_back(u,'U');\n            }\n            if(j+1<N && v[i][j]=='0'){\n                int v2 = id(i,j+1);\n                nbr[u].emplace_back(v2,'R');\n                nbr[v2].emplace_back(u,'L');\n            }\n        }\n    }\n    // Precompute all\u2010pairs BFS distances + first\u2010move pointers\n    // dist[src*V + x] = distance, fm[src*V + x] = first move from src toward x\n    vector<int16_t> dist(V*V, -1);\n    vector<char> fm(V*V, 0);\n    deque<int> q;\n    for(int src=0;src<V;src++){\n        int base = src*V;\n        // reset\n        for(int i=0;i<V;i++) dist[base+i] = -1;\n        // BFS init\n        dist[base+src] = 0;\n        q.clear();\n        // push neighbors\n        for(auto &pc: nbr[src]){\n            int to = pc.first;\n            char c = pc.second;\n            if(dist[base+to]==-1){\n                dist[base+to] = 1;\n                fm[base+to] = c;\n                q.push_back(to);\n            }\n        }\n        // BFS\n        while(!q.empty()){\n            int u = q.front(); q.pop_front();\n            int du = dist[base+u];\n            for(auto &pc: nbr[u]){\n                int to = pc.first;\n                if(dist[base+to]==-1){\n                    dist[base+to] = du + 1;\n                    fm[base+to]   = fm[base+u];\n                    q.push_back(to);\n                }\n            }\n        }\n    }\n\n    // Greedy \u201cdirt\u2010density\u201d TSP: always go next to the unvisited j maximizing d[j]/dist[cur][j]\n    vector<char> used(V,0);\n    vector<int> order;\n    order.reserve(V);\n    int cur = 0;\n    used[cur]=1;\n    order.push_back(cur);\n    for(int step=1; step<V; step++){\n        double bestScore = -1.0;\n        int bestJ = -1;\n        int base = cur*V;\n        for(int j=0;j<V;j++){\n            if(!used[j]){\n                int dj = d[j];\n                int dij = dist[base+j];\n                // graph is connected so dij>=1\n                double sc = double(dj)/double(dij);\n                if(sc > bestScore){\n                    bestScore = sc;\n                    bestJ = j;\n                }\n            }\n        }\n        used[bestJ]=1;\n        order.push_back(bestJ);\n        cur = bestJ;\n    }\n    // build the move string\n    string ans;\n    ans.reserve(V*30);\n    auto apply_path = [&](int u, int v){\n        int cu = u;\n        while(cu != v){\n            char c = fm[cu*V + v];\n            ans.push_back(c);\n            int i = cu / N, j = cu % N;\n            if(c=='U')      i--;\n            else if(c=='D') i++;\n            else if(c=='L') j--;\n            else /*R**/     j++;\n            cu = id(i,j);\n        }\n    };\n    for(int i=0;i+1<V;i++){\n        apply_path(order[i], order[i+1]);\n    }\n    // return to origin\n    apply_path(order[V-1], 0);\n\n    // safety: if too long or something weird, fallback to a simple Euler tour\n    if((int)ans.size() > 100000){\n        // simple DFS\u2010Euler on a DFS\u2010spanning tree\n        vector<vector<bool>> vis(N, vector<bool>(N,false));\n        static const int di[4]={0,1,0,-1}, dj[4]={1,0,-1,0};\n        static const char dc[4]={'R','D','L','U'};\n        string ans2;\n        ans2.reserve(2*(V-1));\n        function<void(int,int)> dfs = [&](int i,int j){\n            vis[i][j]=true;\n            for(int ddir=0;ddir<4;ddir++){\n                int ni=i+di[ddir], nj=j+dj[ddir];\n                if(ni<0||ni>=N||nj<0||nj>=N) continue;\n                if(vis[ni][nj]) continue;\n                // check wall\n                if(ddir==0){ // R\n                    if(v[i][j]!='0') continue;\n                } else if(ddir==1){ // D\n                    if(h[i][j]!='0') continue;\n                } else if(ddir==2){ // L\n                    if(v[i][nj]!='0') continue;\n                } else {      // U\n                    if(h[ni][j]!='0') continue;\n                }\n                ans2.push_back(dc[ddir]);\n                dfs(ni,nj);\n                ans2.push_back(dc[(ddir+2)%4]);\n            }\n        };\n        dfs(0,0);\n        cout << ans2 << \"\\n\";\n    } else {\n        cout << ans << \"\\n\";\n    }\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\nstatic const int INF = 1e9;\nstatic const int MAXN = 15;\nstatic const int MAXP = MAXN * MAXN; // 225\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int N, M;\n    cin >> N >> M;\n    int cur_i, cur_j;\n    cin >> cur_i >> cur_j;\n    vector<string> A(N);\n    for(int i = 0; i < N; i++){\n        cin >> A[i];\n    }\n    vector<string> t(M);\n    for(int i = 0; i < M; i++){\n        cin >> t[i];\n    }\n\n    // positions of each letter\n    vector<pair<int,int>> pos[26];\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            pos[A[i][j] - 'A'].emplace_back(i, j);\n        }\n    }\n\n    vector<bool> used(M, false);\n    string lastS;               // keep up to the last 4 typed chars\n    vector<pair<int,int>> moves;\n    moves.reserve(5000);\n\n    // temporary arrays for the \"candidate\" DP (no back-pointers)\n    static int dp1[MAXP], dp2[MAXP];\n\n    // arrays for the \"reconstruct\" DP (with back-pointers)\n    static int dpArr[5][MAXP], parentArr[5][MAXP], occSz[5];\n\n    for(int done = 0; done < M; done++){\n        int bestK = -1;\n        int bestCost = INF;\n        int bestOv = 0;\n\n        // 1) scan all unused words, compute minimal cost = travel + (#letters after overlap)\n        for(int k = 0; k < M; k++){\n            if(used[k]) continue;\n            const string &w = t[k];\n            // compute overlap with lastS\n            int maxOv = min((int)lastS.size(), 5);\n            int ov = 0;\n            for(int o = maxOv; o >= 1; o--){\n                bool ok = true;\n                for(int i = 0; i < o; i++){\n                    if(lastS[lastS.size() - o + i] != w[i]){ ok = false; break; }\n                }\n                if(ok){ ov = o; break; }\n            }\n            int rem = 5 - ov;\n            int travel = 0;\n            if(rem > 0){\n                // DP over the rem letters w[ov..4]\n                //  dp1 = distances to first letter\n                int c0 = w[ov] - 'A';\n                int sz0 = pos[c0].size();\n                for(int j = 0; j < sz0; j++){\n                    dp1[j] = abs(cur_i - pos[c0][j].first)\n                           + abs(cur_j - pos[c0][j].second);\n                }\n                int prevSz = sz0;\n                // transitions\n                for(int i2 = 1; i2 < rem; i2++){\n                    int ccur = w[ov + i2] - 'A';\n                    int cursz = pos[ccur].size();\n                    // init\n                    for(int j = 0; j < cursz; j++) dp2[j] = INF;\n                    int cprev = w[ov + i2 - 1] - 'A';\n                    // relax\n                    for(int u = 0; u < prevSz; u++){\n                        int pi = pos[cprev][u].first;\n                        int pj = pos[cprev][u].second;\n                        int base = dp1[u];\n                        for(int v = 0; v < cursz; v++){\n                            int di = pos[ccur][v].first;\n                            int dj = pos[ccur][v].second;\n                            int cand = base + abs(pi - di) + abs(pj - dj);\n                            if(cand < dp2[v]) dp2[v] = cand;\n                        }\n                    }\n                    // swap in dp2 \u2192 dp1\n                    for(int j = 0; j < cursz; j++) dp1[j] = dp2[j];\n                    prevSz = cursz;\n                }\n                // find min\n                travel = INF;\n                for(int j = 0; j < prevSz; j++){\n                    if(dp1[j] < travel) travel = dp1[j];\n                }\n            }\n            int cost = travel + rem;  // include +1 per letter typed\n            if(cost < bestCost){\n                bestCost = cost;\n                bestK = k;\n                bestOv = ov;\n            }\n        }\n\n        // 2) \"commit\" to bestK, re\u2010DP with back-pointers, generate moves\n        used[bestK] = true;\n        const string &w = t[bestK];\n        // recompute overlap\n        int maxOv = min((int)lastS.size(), 5);\n        int ov = 0;\n        for(int o = maxOv; o >= 1; o--){\n            bool ok = true;\n            for(int i = 0; i < o; i++){\n                if(lastS[lastS.size() - o + i] != w[i]){ ok = false; break; }\n            }\n            if(ok){ ov = o; break; }\n        }\n        int rem = 5 - ov;\n        if(rem > 0){\n            // build occSz[] for these rem letters\n            for(int i2 = 0; i2 < rem; i2++){\n                occSz[i2] = pos[w[ov + i2] - 'A'].size();\n            }\n            // dpArr + parentArr\n            // i2=0\n            {\n                int c0 = w[ov] - 'A';\n                for(int j = 0; j < occSz[0]; j++){\n                    auto &p = pos[c0][j];\n                    dpArr[0][j] = abs(cur_i - p.first) + abs(cur_j - p.second);\n                    parentArr[0][j] = -1;\n                }\n            }\n            // i2=1..rem-1\n            for(int i2 = 1; i2 < rem; i2++){\n                int ccur = w[ov + i2] - 'A';\n                int cprev = w[ov + i2 - 1] - 'A';\n                for(int j = 0; j < occSz[i2]; j++){\n                    dpArr[i2][j] = INF;\n                    parentArr[i2][j] = -1;\n                    auto &pc = pos[ccur][j];\n                    int di = pc.first, dj = pc.second;\n                    for(int u = 0; u < occSz[i2 - 1]; u++){\n                        auto &pp = pos[cprev][u];\n                        int cand = dpArr[i2 - 1][u]\n                                 + abs(pp.first - di)\n                                 + abs(pp.second - dj);\n                        if(cand < dpArr[i2][j]){\n                            dpArr[i2][j] = cand;\n                            parentArr[i2][j] = u;\n                        }\n                    }\n                }\n            }\n            // find best end\n            int bestEnd = -1, bestVal = INF;\n            for(int j = 0; j < occSz[rem - 1]; j++){\n                if(dpArr[rem - 1][j] < bestVal){\n                    bestVal = dpArr[rem - 1][j];\n                    bestEnd = j;\n                }\n            }\n            // backtrack indices\n            vector<int> idx(rem);\n            int cur = bestEnd;\n            for(int i2 = rem - 1; i2 >= 0; i2--){\n                idx[i2] = cur;\n                cur = parentArr[i2][cur];\n            }\n            // emit moves\n            for(int i2 = 0; i2 < rem; i2++){\n                int c = w[ov + i2] - 'A';\n                auto &pp = pos[c][ idx[i2] ];\n                moves.emplace_back(pp.first, pp.second);\n                cur_i = pp.first;\n                cur_j = pp.second;\n                // update lastS\n                lastS.push_back(w[ov + i2]);\n                if((int)lastS.size() > 4){\n                    // keep only last 4 chars\n                    lastS.erase(lastS.begin(), lastS.end() - 4);\n                }\n            }\n        }\n        // if rem==0 we typed nothing (rare, since lastS.len<=4), but still mark used\n    }\n\n    // output\n    for(auto &mv : moves){\n        cout << mv.first << \" \" << mv.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    cin >> N >> M >> eps;\n    // Read and ignore the shapes\n    for(int k = 0; k < M; k++){\n        int d; cin >> d;\n        for(int t = 0; t < d; t++){\n            int ii, jj;\n            cin >> ii >> jj;\n        }\n    }\n\n    vector<vector<int>> vgrid(N, vector<int>(N, -1));\n    auto drill = [&](int i, int j){\n        cout << \"q 1 \" << i << \" \" << j << \"\\n\" << flush;\n        int v;\n        if(!(cin >> v)){\n            // Judge aborted\n            exit(0);\n        }\n        vgrid[i][j] = v;\n    };\n\n    // 1) Drill all even\u2010parity cells\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(((i + j) & 1) == 0){\n                drill(i, j);\n            }\n        }\n    }\n\n    // 2) For odd\u2010parity cells, only drill those that\n    //    have >=1 even\u2010parity neighbor with v>0\n    const int di[4] = {1,-1,0,0};\n    const int dj[4] = {0,0,1,-1};\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(((i + j) & 1) == 1){\n                bool need = false;\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){\n                        // this neighbor is even\u2010parity and already drilled\n                        if(vgrid[ni][nj] > 0){\n                            need = true;\n                            break;\n                        }\n                    }\n                }\n                if(need){\n                    drill(i, j);\n                } else {\n                    // we infer vgrid[i][j] = 0\n                    vgrid[i][j] = 0;\n                }\n            }\n        }\n    }\n\n    // 3) Collect and answer all 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(vgrid[i][j] > 0){\n                ans.emplace_back(i, j);\n            }\n        }\n    }\n\n    cout << \"a \" << ans.size();\n    for(auto &p : ans){\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << \"\\n\" << flush;\n\n    int ok;\n    if(cin >> ok){\n        // ok == 1 means correct; 0 means wrong\n    }\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int W, D, N;\n    cin >> W >> D >> N;\n    // W will be 1000, but we read it to match the input format.\n\n    vector<vector<int>> a(D, vector<int>(N));\n    for(int d = 0; d < D; d++)\n        for(int k = 0; k < N; k++)\n            cin >> a[d][k];\n\n    // f[k][w] = total shortage penalty if strip k has width w\n    vector<vector<ll>> f(N, vector<ll>(W+2, 0));\n    for(int k = 0; k < N; k++){\n        // gather and sort the D daily demands for reservation k\n        vector<ll> demands(D);\n        for(int d = 0; d < D; d++) demands[d] = a[d][k];\n        sort(demands.begin(), demands.end());\n        // prefix sums\n        vector<ll> P(D+1, 0);\n        for(int i = 0; i < D; i++) P[i+1] = P[i] + demands[i];\n        // fill f[k][w]\n        for(int w = 1; w <= W; w++){\n            ll cap = (ll)W * w;\n            // find first index > cap\n            int id = upper_bound(demands.begin(), demands.end(), cap) - demands.begin();\n            ll cnt = D - id;\n            ll sumAbove = P[D] - P[id];\n            f[k][w] = sumAbove - cnt * cap;\n        }\n        f[k][W+1] = 0;\n    }\n\n    // Start with width=1 for each of the N strips\n    vector<int> width(N, 1);\n    vector<ll> delta(N);\n    // delta[k] = f[k][cur_width] - f[k][cur_width+1]\n    for(int k = 0; k < N; k++){\n        delta[k] = f[k][1] - f[k][2];\n    }\n\n    // Max\u2010heap of (delta, k)\n    priority_queue<pair<ll,int>> pq;\n    for(int k = 0; k < N; k++){\n        if(delta[k] > 0) pq.emplace(delta[k], k);\n    }\n\n    // Distribute the remaining W-N columns\n    int rem = W - N;\n    for(int it = 0; it < rem && !pq.empty(); it++){\n        auto [val, k] = pq.top(); pq.pop();\n        if(val <= 0) break;\n        // give one more column to strip k\n        width[k]++;\n        int w = width[k];\n        ll nd = (w <= W ? f[k][w] - f[k][w+1] : 0);\n        if(nd > 0) pq.emplace(nd, k);\n    }\n\n    // Compute x\u2010coordinates of strip boundaries\n    vector<int> X(N+1, 0);\n    for(int k = 0; k < N; k++){\n        X[k+1] = X[k] + width[k];\n    }\n\n    // Output the same layout every day\n    // strip k is [0..W] \u00d7 [X[k]..X[k+1]]\n    for(int d = 0; d < D; d++){\n        for(int k = 0; k < N; k++){\n            cout << 0 << ' ' << X[k] << ' ' << W << ' ' << X[k+1] << '\\n';\n        }\n    }\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\nstatic const int MOD = 998244353;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K;\n    cin >> N >> M >> K;   // N=9, M=20, K=81\n    static int b[9][9];\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            long long x;\n            cin >> x;\n            b[i][j] = int(x % MOD);\n        }\n    }\n    static int stamps[20][3][3];\n    for(int m = 0; m < M; m++){\n        for(int i = 0; i < 3; i++){\n            for(int j = 0; j < 3; j++){\n                long long x;\n                cin >> x;\n                stamps[m][i][j] = int(x % MOD);\n            }\n        }\n    }\n\n    struct Op { int m,p,q; };\n    vector<Op> ops;\n    ops.reserve(K);\n\n    auto compute_delta = [&](int bb[9][9], int m, int p, int q){\n        long long d = 0;\n        auto &S = stamps[m];\n        for(int di = 0; di < 3; di++){\n            for(int dj = 0; dj < 3; dj++){\n                int oldv = bb[p+di][q+dj];\n                int s = S[di][dj];\n                int sum = oldv + s;\n                // if wrap, we lose exactly MOD\n                if(sum < MOD)      d += s;\n                else { sum -= MOD; d += (long long)s - MOD; }\n            }\n        }\n        return d;\n    };\n\n    int step = 0;\n    while(step < K){\n        int rem = K - step;\n        // 1) scan all 980 placements, keep top-2 immediate\n        struct Cand { long long d; int m,p,q; };\n        Cand best1{LLONG_MIN,0,0,0}, best2{LLONG_MIN,0,0,0};\n        for(int m = 0; m < M; m++){\n            for(int p = 0; p + 2 < N; p++){\n                for(int q = 0; q + 2 < N; q++){\n                    long long d = compute_delta(b,m,p,q);\n                    if(d > best1.d){\n                        best2 = best1;\n                        best1 = {d,m,p,q};\n                    } else if(d > best2.d){\n                        best2 = {d,m,p,q};\n                    }\n                }\n            }\n        }\n        // If we only have 1 move left, do simple greedy\n        if(rem == 1){\n            if(best1.d <= 0) break;\n            // apply best1\n            auto &SB = stamps[best1.m];\n            for(int di=0;di<3;di++) for(int dj=0;dj<3;dj++){\n                int &cell = b[best1.p+di][best1.q+dj];\n                cell += SB[di][dj];\n                if(cell >= MOD) cell -= MOD;\n            }\n            ops.push_back({best1.m,best1.p,best1.q});\n            step++;\n            break;\n        }\n        // 2) lookahead on the top-2 candidates\n        long long best_pair_gain = LLONG_MIN;\n        int pick1 = -1;\n        Op second_of_pick{0,0,0};\n        for(int idx = 0; idx < 2; idx++){\n            Cand c = (idx==0 ? best1 : best2);\n            if(c.d==LLONG_MIN) break;\n            // simulate c on a temp board\n            int bt[9][9];\n            memcpy(bt, b, sizeof bt);\n            auto &SB1 = stamps[c.m];\n            for(int di=0; di<3; di++){\n                for(int dj=0; dj<3; dj++){\n                    int &cell = bt[c.p+di][c.q+dj];\n                    cell += SB1[di][dj];\n                    if(cell >= MOD) cell -= MOD;\n                }\n            }\n            // find best second move on bt\n            long long best2d = LLONG_MIN;\n            Op best2op{0,0,0};\n            for(int m2 = 0; m2 < M; m2++){\n                for(int p2 = 0; p2 + 2 < N; p2++){\n                    for(int q2 = 0; q2 + 2 < N; q2++){\n                        long long d2 = compute_delta(bt,m2,p2,q2);\n                        if(d2 > best2d){\n                            best2d = d2;\n                            best2op = {m2,p2,q2};\n                        }\n                    }\n                }\n            }\n            long long comb = c.d + best2d;\n            if(comb > best_pair_gain){\n                best_pair_gain = comb;\n                pick1 = idx;\n                second_of_pick = best2op;\n            }\n        }\n        // 3) decide: take the 2-step if it beats single and is positive\n        long long single = best1.d;\n        if(best_pair_gain > single && best_pair_gain > 0){\n            // apply the picked 1st move\n            Cand c = (pick1==0 ? best1 : best2);\n            auto &S1 = stamps[c.m];\n            for(int di=0; di<3; di++){\n                for(int dj=0; dj<3; dj++){\n                    int &cell = b[c.p+di][c.q+dj];\n                    cell += S1[di][dj];\n                    if(cell >= MOD) cell -= MOD;\n                }\n            }\n            ops.push_back({c.m,c.p,c.q});\n            step++;\n\n            // apply the best second move\n            auto &S2 = stamps[ second_of_pick.m ];\n            int p2 = second_of_pick.p, q2 = second_of_pick.q;\n            for(int di=0; di<3; di++){\n                for(int dj=0; dj<3; dj++){\n                    int &cell = b[p2+di][q2+dj];\n                    cell += S2[di][dj];\n                    if(cell >= MOD) cell -= MOD;\n                }\n            }\n            ops.push_back(second_of_pick);\n            step++;\n        }\n        else if(single > 0){\n            // just do the one-step greedy\n            auto &S = stamps[best1.m];\n            for(int di=0; di<3; di++){\n                for(int dj=0; dj<3; dj++){\n                    int &cell = b[best1.p+di][best1.q+dj];\n                    cell += S[di][dj];\n                    if(cell >= MOD) cell -= MOD;\n                }\n            }\n            ops.push_back({best1.m,best1.p,best1.q});\n            step++;\n        }\n        else {\n            // nothing positive to do\n            break;\n        }\n    }\n\n    // output\n    cout << ops.size() << \"\\n\";\n    for(auto &o : ops){\n        cout << o.m << \" \" << o.p << \" \" << o.q << \"\\n\";\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<vector<int>> A(N, vector<int>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> A[i][j];\n        }\n    }\n\n    // We'll kill off the N-1 small cranes immediately,\n    // and let only crane 0 (the \"large\" crane) do all the work.\n    // Keep track, for each row i, how many we've already picked (so we know A[i][picked[i]] is next).\n    vector<int> picked(N, 0);\n\n    // Current position of the large crane:\n    int curR = 0, curC = 0;\n\n    // Build up the action sequence for crane 0:\n    vector<char> ops0;\n\n    int total = N * N;\n    for(int done = 0; done < total; done++){\n        // Find the nearest *available* gate:\n        int bestDist = INT_MAX, bestRow = -1, bestId = -1;\n        for(int r = 0; r < N; r++){\n            if(picked[r] < N){\n                int id = A[r][ picked[r] ];\n                int d = abs(curR - r) + abs(curC - 0);\n                if(d < bestDist || (d == bestDist && id < bestId)){\n                    bestDist = d;\n                    bestRow = r;\n                    bestId  = id;\n                }\n            }\n        }\n        // 1) Move large crane from (curR,curC) to (bestRow,0)\n        int dr = bestRow - curR;\n        if(dr > 0)  while(dr--)  ops0.push_back('D');\n        else        while(dr++ < 0) ops0.push_back('U');\n        int dc = 0 - curC;\n        if(dc > 0)  while(dc--)  ops0.push_back('R');\n        else        while(dc++ < 0) ops0.push_back('L');\n\n        // 2) Pick\n        ops0.push_back('P');\n        picked[bestRow]++;\n\n        // 3) Carry to its *correct* dispatch gate at row = bestId/N, col = N-1\n        int destR = bestId / N, destC = N - 1;\n        // horizontal \u2192\n        int h = destC - 0;\n        while(h--) ops0.push_back('R');\n        // vertical\n        int dr2 = destR - bestRow;\n        if(dr2 > 0)  while(dr2--)  ops0.push_back('D');\n        else          while(dr2++ < 0) ops0.push_back('U');\n        // 4) Drop\n        ops0.push_back('Q');\n\n        // Update crane-0 position\n        curR = destR;\n        curC = destC;\n    }\n\n    int M = (int)ops0.size();\n    // Build each crane's command string\n    vector<string> S(N);\n    // Crane 0:\n    S[0].reserve(M);\n    for(char c : ops0) S[0].push_back(c);\n    // Cranes 1..N-1: bomb on turn 0, then just dots\n    for(int i = 1; i < N; i++){\n        S[i].push_back('B');\n        S[i].append(M-1, '.');\n    }\n\n    // Output\n    for(int i = 0; i < N; i++){\n        cout << S[i] << \"\\n\";\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Task {\n    int sx, sy;\n    int tx, ty;\n    int d;\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<vector<int>> h(N, vector<int>(N));\n    for(int i = 0; i < N; i++)\n        for(int j = 0; j < N; j++)\n            cin >> h[i][j];\n\n    // 1) collect sources and sinks\n    vector<pair<int,int>> src, dst;\n    vector<int> supply, demand;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(h[i][j] > 0){\n                src.emplace_back(i,j);\n                supply.push_back(h[i][j]);\n            } else if(h[i][j] < 0){\n                dst.emplace_back(i,j);\n                demand.push_back(-h[i][j]);\n            }\n        }\n    }\n    int S = src.size(), T = dst.size();\n    if(S == 0){\n        // already flat?\n        return 0;\n    }\n\n    // 2) build all pairs with distance\n    struct Edge { int dist, i, j; };\n    vector<Edge> E;\n    E.reserve(S*T);\n    for(int i = 0; i < S; i++){\n        for(int j = 0; j < T; j++){\n            int d = abs(src[i].first - dst[j].first)\n                  + abs(src[i].second - dst[j].second);\n            E.push_back({d, i, j});\n        }\n    }\n    sort(E.begin(), E.end(),\n         [&](auto &a, auto &b){ return a.dist < b.dist; });\n\n    // 3) greedy matching\n    vector<int> remS = supply, remT = demand;\n    vector<vector<int>> flow(S, vector<int>(T,0));\n    for(auto &e : E){\n        int i = e.i, j = e.j;\n        if(remS[i] == 0 || remT[j] == 0) continue;\n        int d = min(remS[i], remT[j]);\n        flow[i][j] = d;\n        remS[i] -= d;\n        remT[j] -= d;\n    }\n\n    // 4) collect tasks\n    vector<Task> tasks;\n    tasks.reserve(S+T);\n    for(int i = 0; i < S; i++){\n        for(int j = 0; j < T; j++){\n            if(flow[i][j] > 0){\n                tasks.push_back({\n                    src[i].first, src[i].second,\n                    dst[j].first, dst[j].second,\n                    flow[i][j]\n                });\n            }\n        }\n    }\n\n    // 5) execute tasks in nearest\u2010neighbor order\n    int cx = 0, cy = 0;\n    vector<string> ops;\n    ops.reserve(40000);\n\n    auto go = [&](int nx, int ny){\n        while(cx < nx){ ops.push_back(\"D\"); cx++; }\n        while(cx > nx){ ops.push_back(\"U\"); cx--; }\n        while(cy < ny){ ops.push_back(\"R\"); cy++; }\n        while(cy > ny){ ops.push_back(\"L\"); cy--; }\n    };\n\n    while(!tasks.empty()){\n        // pick the task whose source is closest (empty travel)\n        int best = 0, bestd = INT_MAX;\n        for(int i = 0; i < (int)tasks.size(); i++){\n            int d = abs(tasks[i].sx - cx)\n                  + abs(tasks[i].sy - cy);\n            if(d < bestd){\n                bestd = d;\n                best = i;\n            }\n        }\n        Task t = tasks[best];\n        // remove it\n        tasks[best] = tasks.back();\n        tasks.pop_back();\n\n        // move to source\n        go(t.sx, t.sy);\n        // load\n        ops.push_back(\"+\" + to_string(t.d));\n        // move to sink\n        go(t.tx, t.ty);\n        // unload\n        ops.push_back(\"-\" + to_string(t.d));\n    }\n\n    // output\n    for(auto &s : ops) {\n        cout << s << \"\\n\";\n    }\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    cin >> N >> M >> T;\n    const int S = 2 * N * (N - 1); // 60 when N=6\n\n    // read initial seeds\n    vector<vector<int>> X(S, vector<int>(M));\n    for(int i = 0; i < S; i++)\n      for(int j = 0; j < M; j++)\n        cin >> X[i][j];\n\n    // positions of a 2x2 interior cluster in a 6x6 grid\n    vector<pair<int,int>> cluster = {{2,2},{2,3},{3,2},{3,3}};\n\n    for(int turn = 0; turn < T; turn++){\n      // 1) compute total-sums & sort\n      vector<pair<int,int>> V(S);\n      for(int i = 0; i < S; i++){\n        int sum = 0;\n        for(int v : X[i]) sum += v;\n        V[i] = {sum, i};\n      }\n      sort(V.begin(), V.end(), greater<>());\n\n      // 2) find the seed that is max in each dimension\n      vector<int> best_dim(M, -1);\n      for(int d = 0; d < M; d++){\n        int who = 0, best = -1;\n        for(int i = 0; i < S; i++){\n          if(X[i][d] > best){\n            best = X[i][d];\n            who = i;\n          }\n        }\n        best_dim[d] = who;\n      }\n\n      // 3) build pick\u2010set: include all distinct best_dim seeds\n      vector<char> used(S, 0);\n      vector<int> picks;\n      for(int d = 0; d < M; d++){\n        int id = best_dim[d];\n        if(!used[id]){\n          used[id] = 1;\n          picks.push_back(id);\n        }\n      }\n      // 4) fill up to 36 by descending total-sum\n      for(auto &pr : V){\n        if((int)picks.size() >= N*N) break;\n        if(!used[pr.second]){\n          used[pr.second] = 1;\n          picks.push_back(pr.second);\n        }\n      }\n      // 5) sort picks by total-sum descending\n      sort(picks.begin(), picks.end(),\n           [&](int a, int b){\n             return accumulate(X[a].begin(), X[a].end(), 0)\n                  >  accumulate(X[b].begin(), X[b].end(), 0);\n           });\n\n      // 6) plant: top-4 in the 2x2 interior block, rest row-major\n      vector<vector<int>> A(N, vector<int>(N, -1));\n      for(int i = 0; i < 4; i++){\n        auto [r,c] = cluster[i];\n        A[r][c] = picks[i];\n      }\n      int idx = 4;\n      for(int i = 0; i < N && idx < N*N; i++){\n        for(int j = 0; j < N && idx < N*N; j++){\n          if(A[i][j] == -1){\n            A[i][j] = picks[idx++];\n          }\n        }\n      }\n\n      // 7) output & flush\n      for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n          cout << A[i][j] << (j+1 < N ? ' ' : '\\n');\n        }\n      }\n      cout << flush;\n\n      // 8) read in the new S seeds\n      for(int i = 0; i < S; i++){\n        for(int j = 0; j < M; j++){\n          cin >> X[i][j];\n        }\n      }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Directions: 0=right,1=down,2=left,3=up\nconst int dx[4] = {0, 1, 0, -1};\nconst int dy[4] = {1, 0, -1, 0};\nconst char DIRC[4] = {'R','D','L','U'};\n\n// Append the sequence of turns to move the fingertip to (tx,ty), ending with a 'P'\nvoid move_fingertip(int tx, int ty,\n                    int N,\n                    int &rx, int &ry, int &dir,\n                    vector<string> &ops) {\n    // Find the best new orientation d and root position (rx',ry')\n    int bestT = INT_MAX, bestD = -1, bestRx=0, bestRy=0, bestRot = 0, bestCW = 0;\n    for(int d = 0; d < 4; d++){\n        int nrx = tx - dx[d];\n        int nry = ty - dy[d];\n        if(nrx < 0 || nrx >= N || nry < 0 || nry >= N) continue;\n        int dist = abs(nrx - rx) + abs(nry - ry);\n        int cw = (d - dir + 4) % 4;\n        int ccw = (dir - d + 4) % 4;\n        int rot = min(cw, ccw);\n        int T = max(dist, rot);\n        if(T < bestT){\n            bestT = T;\n            bestD = d;\n            bestRx = nrx;\n            bestRy = nry;\n            bestRot = rot;\n            bestCW = (cw <= ccw ? 1 : 0); // 1 for CW ('R'), 0 for CCW ('L')\n        }\n    }\n    int need_dx = bestRx - rx;\n    int need_dy = bestRy - ry;\n    int moves = abs(need_dx) + abs(need_dy);\n    int rotCnt = bestRot;\n    char rotChar = bestCW ? 'R' : 'L';\n    int T = max(moves, rotCnt);\n\n    int rem_dx = need_dx, rem_dy = need_dy, rem_rot = rotCnt;\n    for(int step = 0; step < T; step++){\n        char m = '.', r = '.', a0 = '.', a1 = '.';\n        // Movement\n        if(step < moves){\n            if(rem_dx > 0){ m = 'D'; rem_dx--; rx++; }\n            else if(rem_dx < 0){ m = 'U'; rem_dx++; rx--; }\n            else if(rem_dy > 0){ m = 'R'; rem_dy--; ry++; }\n            else if(rem_dy < 0){ m = 'L'; rem_dy++; ry--; }\n        }\n        // Rotation\n        if(step < rotCnt){\n            r = rotChar;\n            if(rotChar == 'R') dir = (dir + 1) & 3;\n            else           dir = (dir + 3) & 3;\n        }\n        // On the final step, pick/place with fingertip (vertex 1)\n        if(step == T-1) a1 = 'P';\n        // Build the 2*V' = 4-character turn string: [move][rotate for v=1][action v=0][action v=1]\n        string S(4, '.');\n        S[0] = m;\n        S[1] = r;\n        S[2] = a0; // root (v=0) is never a leaf\n        S[3] = a1; // fingertip\n        ops.push_back(S);\n    }\n    // After this, (rx,ry,dir) == (bestRx,bestRy,bestD) and we have done the 'P'\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Vmax;\n    cin >> N >> M >> Vmax;\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 sources and targets\n    vector<pair<int,int>> src, dst;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(S[i][j] == '1') src.emplace_back(i,j);\n            if(T[i][j] == '1') dst.emplace_back(i,j);\n        }\n    }\n    sort(src.begin(), src.end());\n    sort(dst.begin(), dst.end());\n\n    // Output the simplest 2-node arm: 0 (root) --1--> 1 (fingertip), length=1\n    int Vp = 2;\n    cout << Vp << \"\\n\";\n    cout << 0 << \" \" << 1 << \"\\n\"; // parent of 1 is 0, edge length =1\n    // Initial root position: (0,0)\n    int rx = 0, ry = 0, dir = 0; // dir=0 means finger points right\n    cout << rx << \" \" << ry << \"\\n\";\n\n    vector<string> ops;\n    // We are never holding at the start\n    // For each takoyaki: move to source, P (pickup), move to target, P (drop)\n    for(int k = 0; k < M; k++){\n        move_fingertip(src[k].first, src[k].second, N, rx, ry, dir, ops);\n        move_fingertip(dst[k].first, dst[k].second, N, rx, ry, dir, ops);\n    }\n\n    // Emit all turns\n    for(auto &s: ops) {\n        cout << s << \"\\n\";\n    }\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pt { int x, y, w; };\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int CG = 200;\n    const int HMAX = 100000;\n\n    int N;\n    cin >> N;\n    vector<Pt> pts(2*N);\n    for(int i = 0; i < 2*N; i++){\n        cin >> pts[i].x >> pts[i].y;\n        pts[i].w = (i < N ? +1 : -1);\n    }\n\n    // 1) Compress coordinates\n    vector<int> xs, ys;\n    xs.reserve(2*N);\n    ys.reserve(2*N);\n    for(auto &p: pts){\n        xs.push_back(p.x);\n        ys.push_back(p.y);\n    }\n    sort(xs.begin(), xs.end());\n    xs.erase(unique(xs.begin(), xs.end()), xs.end());\n    sort(ys.begin(), ys.end());\n    ys.erase(unique(ys.begin(), ys.end()), ys.end());\n    int MX = xs.size(), MY = ys.size();\n\n    vector<int> compX(2*N), compY(2*N);\n    for(int i = 0; i < 2*N; i++){\n        compX[i] = int(lower_bound(xs.begin(), xs.end(), pts[i].x) - xs.begin());\n        compY[i] = int(lower_bound(ys.begin(), ys.end(), pts[i].y) - ys.begin());\n    }\n\n    // 2) Build per\u2010column and per\u2010row bins + prefix\u2010sums\n    vector<vector<pair<int,int>>> binsX(MX), binsY(MY);\n    for(int i = 0; i < 2*N; i++){\n        binsX[compX[i]].emplace_back(compY[i], pts[i].w);\n        binsY[compY[i]].emplace_back(compX[i], pts[i].w);\n    }\n    vector<vector<int>> bX_y(MX), bX_ps(MX), bY_x(MY), bY_ps(MY);\n    for(int i = 0; i < MX; i++){\n        auto &v = binsX[i];\n        sort(v.begin(), v.end(), [](auto &a, auto &b){ return a.first < b.first; });\n        int m = v.size();\n        bX_y[i].resize(m);\n        bX_ps[i].resize(m);\n        for(int j = 0; j < m; j++){\n            bX_y[i][j] = v[j].first;\n            bX_ps[i][j] = v[j].second + (j ? bX_ps[i][j-1] : 0);\n        }\n    }\n    for(int i = 0; i < MY; i++){\n        auto &v = binsY[i];\n        sort(v.begin(), v.end(), [](auto &a, auto &b){ return a.first < b.first; });\n        int m = v.size();\n        bY_x[i].resize(m);\n        bY_ps[i].resize(m);\n        for(int j = 0; j < m; j++){\n            bY_x[i][j] = v[j].first;\n            bY_ps[i][j] = v[j].second + (j ? bY_ps[i][j-1] : 0);\n        }\n    }\n\n    // Helpers to get sum of a column in [y1..y2] or row in [x1..x2]\n    auto colSum = [&](int cx, int y1, int y2){\n        auto &vy = bX_y[cx], &ps = bX_ps[cx];\n        int lo = int(lower_bound(vy.begin(), vy.end(), y1) - vy.begin());\n        int hi = int(upper_bound(vy.begin(), vy.end(), y2) - vy.begin()) - 1;\n        if(lo > hi) return 0;\n        return ps[hi] - (lo ? ps[lo-1] : 0);\n    };\n    auto rowSum = [&](int cy, int x1, int x2){\n        auto &vx = bY_x[cy], &ps = bY_ps[cy];\n        int lo = int(lower_bound(vx.begin(), vx.end(), x1) - vx.begin());\n        int hi = int(upper_bound(vx.begin(), vx.end(), x2) - vx.begin()) - 1;\n        if(lo > hi) return 0;\n        return ps[hi] - (lo ? ps[lo-1] : 0);\n    };\n\n    // Local greedy edge\u2010tweak to hill\u2010climb the rectangle\n    auto refineRect = [&](int &x1, int &x2, int &y1, int &y2, int &A){\n        while(true){\n            bool improved = false;\n            // expand left\n            if(x1 > 0){\n                int s = colSum(x1-1, y1, y2);\n                if(s > 0){ x1--; A += s; improved = true; continue; }\n            }\n            // expand right\n            if(x2+1 < MX){\n                int s = colSum(x2+1, y1, y2);\n                if(s > 0){ x2++; A += s; improved = true; continue; }\n            }\n            // expand bottom\n            if(y1 > 0){\n                int s = rowSum(y1-1, x1, x2);\n                if(s > 0){ y1--; A += s; improved = true; continue; }\n            }\n            // expand top\n            if(y2+1 < MY){\n                int s = rowSum(y2+1, x1, x2);\n                if(s > 0){ y2++; A += s; improved = true; continue; }\n            }\n            // contract left\n            if(x1 <= x2){\n                int s = colSum(x1, y1, y2);\n                if(s < 0){ A -= s; x1++; improved = true; continue; }\n            }\n            // contract right\n            if(x1 <= x2){\n                int s = colSum(x2, y1, y2);\n                if(s < 0){ A -= s; x2--; improved = true; continue; }\n            }\n            // contract bottom\n            if(y1 <= y2){\n                int s = rowSum(y1, x1, x2);\n                if(s < 0){ A -= s; y1++; improved = true; continue; }\n            }\n            // contract top\n            if(y1 <= y2){\n                int s = rowSum(y2, x1, x2);\n                if(s < 0){ A -= s; y2--; improved = true; continue; }\n            }\n            if(!improved) break;\n        }\n    };\n\n    // 3) Global sliding\u2010window Kadane in X\n    mt19937 rng(1234567);\n    int Ni1 = 50, Kx1 = 333;\n    vector<int> W(MY);\n    int bestA1 = INT_MIN, bx1 = 0, bx2 = 0, by1 = 0, by2 = 0;\n    uniform_int_distribution<int> distL(0, max(0, MX-Kx1));\n    for(int it = 0; it < Ni1; it++){\n        int L = (MX > Kx1 ? distL(rng) : 0);\n        fill(W.begin(), W.end(), 0);\n        int Rlim = min(MX, L + Kx1);\n        for(int R = L; R < Rlim; R++){\n            for(auto &pr : binsX[R])\n                W[pr.first] += pr.second;\n            // Kadane on W\n            int cur = W[0], t0 = 0, best = cur, sy = 0, ey = 0;\n            for(int y = 1; y < MY; y++){\n                if(cur > 0) cur += W[y];\n                else { cur = W[y]; t0 = y; }\n                if(cur > best){\n                    best = cur;\n                    sy = t0; ey = y;\n                }\n            }\n            if(best > bestA1){\n                bestA1 = best;\n                bx1 = L; bx2 = R;\n                by1 = sy; by2 = ey;\n            }\n        }\n    }\n\n    // 4) Coarse 200\u00d7200 DP to pick a promising region\n    int cgrid[CG][CG];\n    int CW = (HMAX + CG) / CG;\n    for(int i = 0; i < CG; i++) for(int j = 0; j < CG; j++) cgrid[i][j] = 0;\n    for(auto &p: pts){\n        int xi = min(CG-1, p.x / CW);\n        int yi = min(CG-1, p.y / CW);\n        cgrid[xi][yi] += p.w;\n    }\n    vector<int> tmpCG(CG);\n    int bestA2 = INT_MIN, cx1 = 0, cx2 = 0, cy1 = 0, cy2 = 0;\n    for(int Lx = 0; Lx < CG; Lx++){\n        fill(tmpCG.begin(), tmpCG.end(), 0);\n        for(int Rx = Lx; Rx < CG; Rx++){\n            for(int y = 0; y < CG; y++)\n                tmpCG[y] += cgrid[Rx][y];\n            // Kadane on tmpCG\n            int cur = tmpCG[0], t0 = 0, best = cur, sy = 0, ey = 0;\n            for(int y = 1; y < CG; y++){\n                if(cur > 0) cur += tmpCG[y];\n                else { cur = tmpCG[y]; t0 = y; }\n                if(cur > best){\n                    best = cur; sy = t0; ey = y;\n                }\n            }\n            if(best > bestA2){\n                bestA2 = best;\n                cx1 = Lx; cx2 = Rx;\n                cy1 = sy; cy2 = ey;\n            }\n        }\n    }\n\n    // 5) Refine DP inside that coarse region\n    int X0 = cx1 * CW, X1 = min(HMAX, (cx2+1)*CW - 1);\n    int Y0 = cy1 * CW, Y1 = min(HMAX, (cy2+1)*CW - 1);\n    vector<Pt> rpts; rpts.reserve(2000);\n    for(auto &p: pts){\n        if(p.x >= X0 && p.x <= X1 && p.y >= Y0 && p.y <= Y1)\n            rpts.push_back(p);\n    }\n    int Rn = (int)rpts.size();\n    int bestA3 = INT_MIN, rx1 = 0, rx2 = 0, ry1 = 0, ry2 = 0;\n    vector<int> xs3, ys3;\n    if(Rn){\n        xs3.reserve(Rn);\n        ys3.reserve(Rn);\n        for(auto &q: rpts){ xs3.push_back(q.x); ys3.push_back(q.y); }\n        sort(xs3.begin(), xs3.end());\n        xs3.erase(unique(xs3.begin(), xs3.end()), xs3.end());\n        sort(ys3.begin(), ys3.end());\n        ys3.erase(unique(ys3.begin(), ys3.end()), ys3.end());\n        int RX = xs3.size(), RY = ys3.size();\n        vector<int> cX(Rn), cY(Rn);\n        for(int i = 0; i < Rn; i++){\n            cX[i] = int(lower_bound(xs3.begin(), xs3.end(), rpts[i].x) - xs3.begin());\n            cY[i] = int(lower_bound(ys3.begin(), ys3.end(), rpts[i].y) - ys3.begin());\n        }\n        vector<vector<pair<int,int>>> bX2(RX);\n        for(int i = 0; i < Rn; i++){\n            bX2[cX[i]].emplace_back(cY[i], rpts[i].w);\n        }\n        if(RX <= 500){\n            vector<int> tmp(RY);\n            for(int Lx = 0; Lx < RX; Lx++){\n                fill(tmp.begin(), tmp.end(), 0);\n                for(int Rx = Lx; Rx < RX; Rx++){\n                    for(auto &pr: bX2[Rx]) tmp[pr.first] += pr.second;\n                    int cur = tmp[0], t0 = 0, best = cur, sy = 0, ey = 0;\n                    for(int y = 1; y < RY; y++){\n                        if(cur > 0) cur += tmp[y];\n                        else { cur = tmp[y]; t0 = y; }\n                        if(cur > best){\n                            best = cur; sy = t0; ey = y;\n                        }\n                    }\n                    if(best > bestA3){\n                        bestA3 = best;\n                        rx1 = Lx; rx2 = Rx;\n                        ry1 = sy; ry2 = ey;\n                    }\n                }\n            }\n        } else {\n            int Ni2 = 40, Kx2 = 250;\n            uniform_int_distribution<int> dist2(0, max(0, RX-Kx2));\n            vector<int> tmp(RY), starts(Ni2);\n            for(int i = 0; i < Ni2; i++)\n                starts[i] = (RX > Kx2 ? dist2(rng) : 0);\n            for(int Lx: starts){\n                fill(tmp.begin(), tmp.end(), 0);\n                int Rlim = min(RX, Lx+Kx2);\n                for(int Rx = Lx; Rx < Rlim; Rx++){\n                    for(auto &pr: bX2[Rx]) tmp[pr.first] += pr.second;\n                    int cur = tmp[0], t0 = 0, best = cur, sy = 0, ey = 0;\n                    for(int y = 1; y < RY; y++){\n                        if(cur > 0) cur += tmp[y];\n                        else { cur = tmp[y]; t0 = y; }\n                        if(cur > best){\n                            best = cur; sy = t0; ey = y;\n                        }\n                    }\n                    if(best > bestA3){\n                        bestA3 = best;\n                        rx1 = Lx; rx2 = Rx;\n                        ry1 = sy; ry2 = ey;\n                    }\n                }\n            }\n        }\n    }\n\n    // 6) Locally refine both candidates\n    // Candidate A: global sliding\u2010window\n    int A1 = 0;\n    int fbx1 = bx1, fbx2 = bx2, fby1 = by1, fby2 = by2;\n    for(int xx = fbx1; xx <= fbx2; xx++){\n        A1 += colSum(xx, fby1, fby2);\n    }\n    refineRect(fbx1, fbx2, fby1, fby2, A1);\n\n    // Candidate B: coarse+fine\n    int A2 = INT_MIN;\n    int frx1=0, frx2=0, fry1=0, fry2=0;\n    if(Rn && rx1 <= rx2 && ry1 <= ry2){\n        int gx1 = int(lower_bound(xs.begin(), xs.end(), xs3[rx1]) - xs.begin());\n        int gx2 = int(lower_bound(xs.begin(), xs.end(), xs3[rx2]) - xs.begin());\n        int gy1 = int(lower_bound(ys.begin(), ys.end(), ys3[ry1]) - ys.begin());\n        int gy2 = int(lower_bound(ys.begin(), ys.end(), ys3[ry2]) - ys.begin());\n        if(gx1 <= gx2 && gy1 <= gy2){\n            frx1 = gx1; frx2 = gx2; fry1 = gy1; fry2 = gy2;\n            A2 = 0;\n            for(int xx = frx1; xx <= frx2; xx++){\n                A2 += colSum(xx, fry1, fry2);\n            }\n            refineRect(frx1, frx2, fry1, fry2, A2);\n        }\n    }\n\n    // 7) Pick the better\n    int finalA = A1;\n    int FX1 = fbx1, FX2 = fbx2, FY1 = fby1, FY2 = fby2;\n    if(A2 > A1){\n        finalA = A2;\n        FX1 = frx1; FX2 = frx2; FY1 = fry1; FY2 = fry2;\n    }\n    // Fallback if non\u2010positive or degenerate\n    if(finalA <= 0 || FX2 <= FX1 || FY2 <= FY1){\n        FX1 = FY1 = 0;\n        FX2 = FY2 = 1;\n    }\n\n    // 8) Output the rectangle\n    cout << 4 << \"\\n\";\n    cout << xs[FX1] << \" \" << ys[FY1] << \"\\n\";\n    cout << xs[FX1] << \" \" << ys[FY2] << \"\\n\";\n    cout << xs[FX2] << \" \" << ys[FY2] << \"\\n\";\n    cout << xs[FX2] << \" \" << ys[FY1] << \"\\n\";\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    ll sigma;\n    cin >> N >> T >> sigma;\n    vector<ll> w0(N), h0(N);\n    for(int i = 0; i < N; i++){\n        cin >> w0[i] >> h0[i];\n    }\n\n    // Precompute for each rectangle the rotated width and height:\n    // we choose rotation so that width_i = min(w0,h0), height_i = max(w0,h0).\n    vector<ll> wi(N), hi(N);\n    for(int i = 0; i < N; i++){\n        wi[i] = min(w0[i], h0[i]);\n        hi[i] = max(w0[i], h0[i]);\n    }\n\n    // Try all possible row counts R = 1..N, slicing [0..N) into R contiguous chunks,\n    // and score = max_row_width + sum_row_heights.  Pick the best R.\n    ll bestScore = LLONG_MAX;\n    int bestR = 1;\n    vector<int> bestStart, bestSize;\n    for(int R = 1; R <= N; R++){\n        int base = N / R, rem = N % R;\n        vector<int> start(R), sz(R);\n        start[0] = 0;\n        for(int j = 0; j < R; j++){\n            sz[j] = base + (j < rem ? 1 : 0);\n            if(j > 0) start[j] = start[j-1] + sz[j-1];\n        }\n        ll sumH = 0, maxW = 0;\n        for(int j = 0; j < R; j++){\n            ll sw = 0, mh = 0;\n            for(int i = start[j]; i < start[j] + sz[j]; i++){\n                sw += wi[i];\n                mh = max(mh, hi[i]);\n            }\n            maxW = max(maxW, sw);\n            sumH += mh;\n        }\n        ll sc = maxW + sumH;\n        if(sc < bestScore){\n            bestScore = sc;\n            bestR = R;\n            bestStart = start;\n            bestSize = sz;\n        }\n    }\n\n    // Build the final row\u2010assignment and row\u2010representatives (the tallest block in each row).\n    int R = bestR;\n    auto &start = bestStart;\n    auto &sz    = bestSize;\n    vector<int> row(N), rep(R);\n    for(int j = 0; j < R; j++){\n        for(int i = start[j]; i < start[j] + sz[j]; i++){\n            row[i] = j;\n        }\n        // find rep[j] = index with maximal hi in this chunk\n        int r = start[j];\n        for(int i = start[j]; i < start[j] + sz[j]; i++){\n            if(hi[i] > hi[r]) r = i;\n        }\n        rep[j] = r;\n    }\n\n    // Now do the T turns.  Each turn we output the same N placements,\n    // flush, and read back (W',H') to stay in sync.\n    for(int t = 0; t < T; t++){\n        cout << N << \"\\n\";\n        for(int i = 0; i < N; i++){\n            int j = row[i];\n            // rotation bit\n            int r = (w0[i] > h0[i] ? 1 : 0);\n            char d;\n            int b;\n            if(j == 0){\n                // top row: push Up\n                d = 'U';\n                b = (i == 0 ? -1 : i - 1);\n            } else {\n                // lower rows: push Left, aligned under rep[j-1]\n                d = 'L';\n                b = rep[j - 1];\n            }\n            cout << i << \" \" << r << \" \" << d << \" \" << b << \"\\n\";\n        }\n        cout << flush;\n        ll Wp, Hp;\n        if(!(cin >> Wp >> Hp)) break;\n    }\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    cin >> N >> M >> H;\n    vector<int> A(N);\n    for(int i = 0; i < N; i++) cin >> A[i];\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    // skip coordinates\n    for(int i = 0; i < N; i++){\n        int x,y; \n        cin >> x >> y;\n    }\n\n    vector<bool> covered(N, false);\n    vector<int> parent(N, -1), depth(N, 0);\n\n    vector<int> distCand(N, -1), q(N);\n    auto evalRoot = [&](int r)->long long {\n        // BFS on the *uncovered* subgraph up to depth H, sum (d+1)*A\n        long long sum = 0;\n        int ql = 0, qr = 0;\n        distCand[r] = 0;\n        q[qr++] = r;\n        sum += (long long)(1) * A[r];\n        vector<int> seen; \n        seen.push_back(r);\n        while(ql < qr){\n            int u = q[ql++];\n            if(distCand[u] == H) continue;\n            for(int w: adj[u]){\n                if(!covered[w] && distCand[w] == -1){\n                    distCand[w] = distCand[u] + 1;\n                    sum += (long long)(distCand[w] + 1) * A[w];\n                    q[qr++] = w;\n                    seen.push_back(w);\n                }\n            }\n        }\n        // reset distCand\n        for(int v: seen) distCand[v] = -1;\n        return sum;\n    };\n\n    int uncovered = N;\n    while(uncovered > 0){\n        // 1) pick best root among uncovered\n        long long bestScore = -1;\n        int bestR = -1;\n        for(int r = 0; r < N; r++){\n            if(covered[r]) continue;\n            long long sc = evalRoot(r);\n            if(sc > bestScore){\n                bestScore = sc;\n                bestR = r;\n            }\n        }\n        // 2) BFS from bestR, record parent[] and depth[], mark covered\n        int ql = 0, qr = 0;\n        vector<int> distAct(N, -1), parAct(N, -1), seenAct;\n        distAct[bestR] = 0;\n        parAct[bestR]  = -1;\n        q[qr++] = bestR;\n        seenAct.push_back(bestR);\n        covered[bestR] = true;\n        parent[bestR] = -1;\n        depth[bestR]  = 0;\n        uncovered--;\n\n        while(ql < qr){\n            int u = q[ql++];\n            if(distAct[u] == H) continue;\n            for(int w: adj[u]){\n                if(!covered[w] && distAct[w] == -1){\n                    distAct[w] = distAct[u] + 1;\n                    parAct[w]  = u;\n                    q[qr++] = w;\n                    seenAct.push_back(w);\n                    covered[w] = true;\n                    parent[w] = u;\n                    depth[w]  = distAct[w];\n                    uncovered--;\n                }\n            }\n        }\n        // next iteration until all covered\n    }\n\n    // Output the parent array\n    // If parent[v] = -1, it's a root; otherwise it's the parent vertex.\n    for(int i = 0; i < N; i++){\n        cout << parent[i] << (i+1==N?'\\n':' ');\n    }\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Segment {\n    char dir;           // 'L','R','U','D'\n    int idx;            // row or column index\n    int k;              // number of shifts in that direction\n    int cost;           // = 2*k\n    vector<int> cover;  // which Oni (by id) this segment removes\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;                // N is always 20\n    vector<string> B(N);\n    for(int i = 0; i < N; i++) {\n        cin >> B[i];\n    }\n\n    // 1) collect all Oni positions and give them IDs 0..M-1\n    vector<pair<int,int>> oni_pos;\n    oni_pos.reserve(2*N);\n    vector<vector<int>> pos2id(N, vector<int>(N, -1));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(B[i][j] == 'x'){\n                int id = (int)oni_pos.size();\n                pos2id[i][j] = id;\n                oni_pos.emplace_back(i,j);\n            }\n        }\n    }\n    int M = oni_pos.size(); // should be 2N = 40\n\n    // 2) precompute, for each row/col, where the nearest 'o' is\n    const int INF = 1000000;\n    vector<int> row_min_o(N, INF), row_max_o(N, -INF);\n    vector<int> col_min_o(N, INF), col_max_o(N, -INF);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(B[i][j] == 'o'){\n                row_min_o[i] = min(row_min_o[i], j);\n                row_max_o[i] = max(row_max_o[i], j);\n                col_min_o[j] = min(col_min_o[j], i);\n                col_max_o[j] = max(col_max_o[j], i);\n            }\n        }\n    }\n    // if a row has no 'o', row_min_o stays INF, row_max_o = -INF, etc.\n\n    // 3) build all valid segments\n    vector<Segment> segs;\n    segs.reserve(4*N);\n    auto add_segment = [&](char d, int idx, int k){\n        if(k <= 0) return;\n        Segment s;\n        s.dir = d; s.idx = idx; s.k = k; s.cost = 2*k;\n        // collect which Oni lie in that segment\n        if(d == 'L'){\n            // row idx, columns [0..k-1]\n            for(int j = 0; j < k; j++){\n                int id = pos2id[idx][j];\n                if(id >= 0) s.cover.push_back(id);\n            }\n        } else if(d == 'R'){\n            // row idx, columns [N-k..N-1]\n            for(int j = N-k; j < N; j++){\n                int id = pos2id[idx][j];\n                if(id >= 0) s.cover.push_back(id);\n            }\n        } else if(d == 'U'){\n            // col idx, rows [0..k-1]\n            for(int i = 0; i < k; i++){\n                int id = pos2id[i][idx];\n                if(id >= 0) s.cover.push_back(id);\n            }\n        } else { // 'D'\n            // col idx, rows [N-k..N-1]\n            for(int i = N-k; i < N; i++){\n                int id = pos2id[i][idx];\n                if(id >= 0) s.cover.push_back(id);\n            }\n        }\n        if(!s.cover.empty()){\n            segs.push_back(move(s));\n        }\n    };\n\n    // row-left and row-right\n    for(int i = 0; i < N; i++){\n        int L = (row_min_o[i] == INF ? N : row_min_o[i]);\n        if(L > 0) add_segment('L', i, L);\n        int R = (row_max_o[i] == -INF ? -1 : row_max_o[i]);\n        if(R < N-1) add_segment('R', i, N - (R+1));\n    }\n    // col-up and col-down\n    for(int j = 0; j < N; j++){\n        int U = (col_min_o[j] == INF ? N : col_min_o[j]);\n        if(U > 0) add_segment('U', j, U);\n        int D = (col_max_o[j] == -INF ? -1 : col_max_o[j]);\n        if(D < N-1) add_segment('D', j, N - (D+1));\n    }\n\n    int S = segs.size();\n    vector<bool> used(S,false), covered(M,false);\n    int covered_cnt = 0;\n    vector<int> chosen; chosen.reserve(S);\n\n    // 4) greedy set\u2010cover: each step pick segment with best (newly\u2010covered Oni) / cost\n    while(covered_cnt < M){\n        double best_ratio = -1.0;\n        int best_s = -1, best_new = 0;\n        for(int s = 0; s < S; s++){\n            if(used[s]) continue;\n            int newc = 0;\n            for(int id: segs[s].cover){\n                if(!covered[id]) newc++;\n            }\n            if(newc == 0) continue;\n            double ratio = double(newc) / segs[s].cost;\n            if(ratio > best_ratio){\n                best_ratio = ratio;\n                best_s = s;\n                best_new = newc;\n            }\n        }\n        if(best_s < 0){\n            // should never happen, because each Oni has at least one clear direction\n            break;\n        }\n        used[best_s] = true;\n        chosen.push_back(best_s);\n        for(int id: segs[best_s].cover){\n            if(!covered[id]){\n                covered[id] = true;\n                covered_cnt++;\n            }\n        }\n    }\n\n    // 5) emit operations for each chosen segment\n    //    we can do them in any order\u2014each (k shifts in dir, then k in the opposite) is independent\n    auto opposite = [&](char d)->char{\n        if(d=='L') return 'R';\n        if(d=='R') return 'L';\n        if(d=='U') return 'D';\n        return 'U';\n    };\n\n    vector<pair<char,int>> ops;\n    ops.reserve(1600);\n\n    for(int si: chosen){\n        auto &Sg = segs[si];\n        for(int t = 0; t < Sg.k; t++){\n            ops.emplace_back(Sg.dir, Sg.idx);\n        }\n        char od = opposite(Sg.dir);\n        for(int t = 0; t < Sg.k; t++){\n            ops.emplace_back(od, Sg.idx);\n        }\n    }\n\n    // Just in case (should be <= 4*N*N = 1600)\n    // but we know sum(2*k) <= 1600 by construction.\n    // Output:\n    for(auto &op: ops){\n        cout << op.first << \" \" << op.second << \"\\n\";\n    }\n\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    long long L;\n    cin >> N >> L;\n    vector<long long> T(N);\n    for(int i = 0; i < N; i++){\n        cin >> T[i];\n    }\n\n    // Baseline: one big cycle of length N.\n    // We set a[i] = b[i] = (i+1)%N so that the walker cycles\n    // around 0\u21921\u21922\u2192...\u2192N-1\u21920\u2192...\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;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for(int i = 0; i < M; i++) cin >> G[i];\n\n    vector<int> lx(N), rx(N), ly(N), ry(N);\n    for(int i = 0; i < N; i++){\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n\n    // Compute rectangle centers\n    vector<pair<double,double>> center(N);\n    for(int i = 0; i < N; i++){\n        center[i].first  = (lx[i] + rx[i]) * 0.5;\n        center[i].second = (ly[i] + ry[i]) * 0.5;\n    }\n\n    // Sort cities by center (lex order)\n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(), [&](int a, int b){\n        if(center[a].first != center[b].first)\n            return center[a].first < center[b].first;\n        return center[a].second < center[b].second;\n    });\n\n    // Split into M groups according to G[]\n    vector<vector<int>> groups;\n    groups.reserve(M);\n    int p = 0;\n    for(int k = 0; k < M; k++){\n        vector<int> g;\n        g.reserve(G[k]);\n        for(int t = 0; t < G[k]; t++){\n            g.push_back(idx[p++]);\n        }\n        groups.push_back(move(g));\n    }\n\n    // Prepare storage for the edges of each group\n    vector<vector<pair<int,int>>> answer_edges(M);\n\n    // For each group, run Prim's MST on the approximate centers\n    for(int k = 0; k < M; k++){\n        auto &g = groups[k];\n        int K = g.size();\n        if(K <= 1) continue;\n        vector<bool> in_mst(K,false);\n        vector<double> min_d(K, 1e18);\n        vector<int> parent(K, -1);\n\n        min_d[0] = 0.0;\n        for(int it = 0; it < K; it++){\n            // find next u with smallest min_d[u]\n            int u = -1;\n            double best = 1e18;\n            for(int i = 0; i < K; i++){\n                if(!in_mst[i] && min_d[i] < best){\n                    best = min_d[i];\n                    u = i;\n                }\n            }\n            // add it\n            in_mst[u] = true;\n            if(parent[u] != -1){\n                int a = g[u], b = g[parent[u]];\n                answer_edges[k].emplace_back(a, b);\n            }\n            // relax neighbors\n            for(int v = 0; v < K; v++){\n                if(in_mst[v]) continue;\n                double dx = center[g[u]].first  - center[g[v]].first;\n                double dy = center[g[u]].second - center[g[v]].second;\n                double d = floor(sqrt(dx*dx + dy*dy));\n                if(d < min_d[v]){\n                    min_d[v] = d;\n                    parent[v] = u;\n                }\n            }\n        }\n    }\n\n    // Output final answer: no queries\n    cout << \"!\\n\";\n    for(int k = 0; k < M; k++){\n        // list cities in group k\n        for(int i = 0; i < (int)groups[k].size(); i++){\n            if(i) cout << ' ';\n            cout << groups[k][i];\n        }\n        cout << \"\\n\";\n        // list the G[k]-1 edges\n        for(auto &e : answer_edges[k]){\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    cin >> N >> M;\n    vector<pair<int,int>> pts(M);\n    for(int i = 0; i < M; i++){\n        cin >> pts[i].first >> pts[i].second;\n    }\n    int ci = pts[0].first, cj = pts[0].second;\n    vector<pair<char,char>> ans;\n    const int INF = 1e9;\n\n    for(int k = 1; k < M; k++){\n        int ti = pts[k].first;\n        int tj = pts[k].second;\n        int di = ti - ci;\n        int dj = tj - cj;\n        int costVM = abs(di);\n        int costHM = abs(dj);\n        int costVS = INF, costHS = INF;\n\n        // cost of sliding vertically via boundary then back\n        if(di > 0){\n            // slide down to row N-1, then move up to ti\n            costVS = 1 + ((N-1) - ti);\n        } else if(di < 0){\n            // slide up to row 0, then move down to ti\n            costVS = 1 + ti;\n        }\n        // cost of sliding horizontally via boundary then back\n        if(dj > 0){\n            // slide right to col N-1, then move left to tj\n            costHS = 1 + ((N-1) - tj);\n        } else if(dj < 0){\n            // slide left to col 0, then move right to tj\n            costHS = 1 + tj;\n        }\n\n        bool useV = costVS < costVM;\n        bool useH = costHS < costHM;\n\n        // First do horizontal phase\n        if(useH){\n            if(dj > 0){\n                ans.emplace_back('S','R');\n                int moves = (N-1) - tj;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','L');\n                }\n            } else {\n                // dj<0\n                ans.emplace_back('S','L');\n                int moves = tj;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','R');\n                }\n            }\n            cj = tj;\n        } else {\n            // simple moves\n            if(dj > 0){\n                for(int t = 0; t < dj; t++){\n                    ans.emplace_back('M','R');\n                }\n            } else if(dj < 0){\n                for(int t = 0; t < -dj; t++){\n                    ans.emplace_back('M','L');\n                }\n            }\n            cj = tj;\n        }\n\n        // Then do vertical phase\n        if(useV){\n            if(di > 0){\n                ans.emplace_back('S','D');\n                int moves = (N-1) - ti;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','U');\n                }\n            } else {\n                // di<0\n                ans.emplace_back('S','U');\n                int moves = ti;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','D');\n                }\n            }\n            ci = ti;\n        } else {\n            // simple moves\n            if(di > 0){\n                for(int t = 0; t < di; t++){\n                    ans.emplace_back('M','D');\n                }\n            } else if(di < 0){\n                for(int t = 0; t < -di; t++){\n                    ans.emplace_back('M','U');\n                }\n            }\n            ci = ti;\n        }\n    }\n\n    // Output all actions\n    for(auto &ac : ans){\n        cout << ac.first << \" \" << ac.second << \"\\n\";\n    }\n    return 0;\n}"},"4":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\n\n// A free rectangle [x1,x2) x [y1,y2)\nstruct Rect { int x1,y1,x2,y2; };\n\n// If a and b share a full edge, merge into o and return true.\nstatic inline bool canMerge(const Rect &a, const Rect &b, Rect &o) {\n    // vertical\n    if(a.x1==b.x1 && a.x2==b.x2) {\n        if(a.y2==b.y1){ o={a.x1,a.y1,a.x2,b.y2}; return true; }\n        if(b.y2==a.y1){ o={a.x1,b.y1,a.x2,a.y2}; return true; }\n    }\n    // horizontal\n    if(a.y1==b.y1 && a.y2==b.y2) {\n        if(a.x2==b.x1){ o={a.x1,a.y1,b.x2,a.y2}; return true; }\n        if(b.x2==a.x1){ o={b.x1,a.y1,a.x2,a.y2}; return true; }\n    }\n    return false;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n;\n    cin >> n;\n    vector<int> x(n), y(n);\n    vector<long long> r(n);\n    for(int i=0;i<n;i++){\n        cin >> x[i] >> y[i] >> r[i];\n    }\n\n    // Precompute the \"ideal\" (w,h) \u2248 sqrt(r_i) plus swapped\n    vector<vector<pair<int,int>>> dims0(n);\n    for(int i=0;i<n;i++){\n        long long ri=r[i];\n        int w=(int)floor(sqrt((long double)ri));\n        while(1LL*w*w>ri) --w;\n        while(1LL*(w+1)*(w+1)<=ri) ++w;\n        w = max(1, min(w,10000));\n        int h=(int)((ri + w - 1)/w);\n        if(h>10000){\n            h=10000;\n            w=(int)((ri + h - 1)/h);\n        }\n        dims0[i].emplace_back(w,h);\n        if(h!=w) dims0[i].emplace_back(h,w);\n    }\n\n    // Base index list\n    vector<int> base(n);\n    iota(base.begin(), base.end(), 0);\n\n    // Build a whole bunch of order-variants\n    mt19937_64 global_rng(123456789ULL);\n    vector<vector<int>> orderVariants;\n    orderVariants.reserve(7+3+5);\n\n    //  1) r desc\n    {\n        auto ord=base;\n        sort(ord.begin(), ord.end(),\n             [&](int a,int b){ return r[a]>r[b]; });\n        orderVariants.push_back(ord);\n    }\n    //  2) r desc, x asc\n    {\n        auto ord=base;\n        sort(ord.begin(), ord.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]>r[b];\n                 return x[a]<x[b];\n             });\n        orderVariants.push_back(ord);\n    }\n    //  3) r desc, x desc\n    {\n        auto ord=base;\n        sort(ord.begin(), ord.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]>r[b];\n                 return x[a]>x[b];\n             });\n        orderVariants.push_back(ord);\n    }\n    //  4) r desc, y asc\n    {\n        auto ord=base;\n        sort(ord.begin(), ord.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]>r[b];\n                 return y[a]<y[b];\n             });\n        orderVariants.push_back(ord);\n    }\n    //  5) r desc, y desc\n    {\n        auto ord=base;\n        sort(ord.begin(), ord.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]>r[b];\n                 return y[a]>y[b];\n             });\n        orderVariants.push_back(ord);\n    }\n    //  6) r desc, dist to center asc\n    {\n        auto ord=base;\n        sort(ord.begin(), ord.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]>r[b];\n                 long long da=(x[a]-5000LL)*(x[a]-5000LL)+(y[a]-5000LL)*(y[a]-5000LL);\n                 long long db=(x[b]-5000LL)*(x[b]-5000LL)+(y[b]-5000LL)*(y[b]-5000LL);\n                 return da<db;\n             });\n        orderVariants.push_back(ord);\n    }\n    //  7) one pure random shuffle\n    {\n        auto ord=base;\n        shuffle(ord.begin(), ord.end(), global_rng);\n        orderVariants.push_back(ord);\n    }\n\n    // 3 jittered variants (small random adjacent swaps of the r-desc)\n    for(int t=0;t<3;t++){\n        auto ord = orderVariants[0]; // the pure r-desc\n        for(int i=0;i+1<n;i++){\n            if((global_rng() & 15)==0) // ~1/16 swaps\n                swap(ord[i], ord[i+1]);\n        }\n        orderVariants.push_back(ord);\n    }\n    // 5 fully random variants\n    for(int t=0;t<5;t++){\n        auto ord=base;\n        shuffle(ord.begin(), ord.end(), global_rng);\n        orderVariants.push_back(ord);\n    }\n\n    int V = (int)orderVariants.size();\n    // For each variant choose a small prob of picking 2nd-best fit\n    uniform_real_distribution<double> pickDist(0.0,0.30);\n    vector<double> pickProb(V);\n    for(int i=0;i<V;i++){\n        pickProb[i]=pickDist(global_rng);\n    }\n\n    vector<array<int,4>> bestAns(n);\n    double bestSum = -1.0;\n\n    // --- multi-start ---\n    for(int v=0;v<V;v++){\n        auto &order = orderVariants[v];\n        double p2 = pickProb[v];\n\n        // free rectangles\n        vector<Rect> freeRects;\n        freeRects.reserve(2000);\n        freeRects.push_back({0,0,10000,10000});\n\n        // current placement\n        vector<array<int,4>> ans(n);\n\n        auto removeRect = [&](int i){\n            freeRects[i]=freeRects.back();\n            freeRects.pop_back();\n        };\n        auto addFree = [&](Rect R0){\n            if(R0.x1>=R0.x2||R0.y1>=R0.y2) return;\n            // try merging\n            bool again=true;\n            while(again){\n                again=false;\n                for(int i=0;i<(int)freeRects.size();i++){\n                    Rect M;\n                    if(canMerge(R0, freeRects[i], M)){\n                        removeRect(i);\n                        R0=M;\n                        again=true;\n                        break;\n                    }\n                }\n            }\n            freeRects.push_back(R0);\n        };\n\n        // place each company\n        for(int idx: order){\n            long long ri=r[idx];\n            int xi=x[idx], yi=y[idx];\n\n            // collect ideal\u2010fit candidates\n            struct Cand { int ridx,w,h,L,Rg,D,U; int waste,area; };\n            vector<Cand> cands;\n            cands.reserve(freeRects.size()*2);\n\n            for(auto &dc: dims0[idx]){\n                int w=dc.first, h=dc.second;\n                for(int j=0;j<(int)freeRects.size();j++){\n                    auto &F=freeRects[j];\n                    int Rw=F.x2-F.x1, Rh=F.y2-F.y1;\n                    if(Rw<w||Rh<h) continue;\n                    int L = max(F.x1, xi-w+1);\n                    int Rg= min(xi,    F.x2-w);\n                    if(L>Rg) continue;\n                    int D = max(F.y1, yi-h+1);\n                    int U = min(yi,    F.y2-h);\n                    if(D>U) continue;\n                    int area = Rw*Rh;\n                    int waste= area - w*h;\n                    cands.push_back({j,w,h,L,Rg,D,U,waste,area});\n                }\n            }\n\n            if(!cands.empty()){\n                // pick best and second\u2010best by (waste,area)\n                int b0=0, b1=-1;\n                int w0=cands[0].waste, A0=cands[0].area;\n                for(int i=1;i<(int)cands.size();i++){\n                    int wst=cands[i].waste, Ai=cands[i].area;\n                    if(wst<w0 || (wst==w0 && Ai<A0)){\n                        b1=b0;\n                        b0=i;\n                        w0=wst; A0=Ai;\n                    } else if(b1<0){\n                        b1=i;\n                    } else {\n                        int w1=cands[b1].waste, A1=cands[b1].area;\n                        if(wst<w1 || (wst==w1 && Ai<A1)){\n                            b1=i;\n                        }\n                    }\n                }\n                int pick = b0;\n                if(b1>=0 && (global_rng()%10000) < (int)(p2*10000.0))\n                    pick=b1;\n\n                auto &c=cands[pick];\n                int a0 = xi - c.w/2;\n                a0 = min(max(a0, c.L), c.Rg);\n                int b0y= yi - c.h/2;\n                b0y= min(max(b0y, c.D), c.U);\n                ans[idx]={a0,b0y,a0+c.w,b0y+c.h};\n\n                // carve out\n                Rect F=freeRects[c.ridx];\n                removeRect(c.ridx);\n                int X1=F.x1, Y1=F.y1, X2=F.x2, Y2=F.y2;\n                addFree({X1,      Y1,      a0,       Y2});\n                addFree({a0+c.w,  Y1,      X2,       Y2});\n                addFree({a0,      Y1,      a0+c.w,   b0y});\n                addFree({a0,      b0y+c.h, a0+c.w,   Y2});\n            }\n            else {\n                // --- improved fallback #1 ---\n                double bestR = -1.0;\n                struct Fb{ int j,w,h,L,Rg,D,U; } bestFb{};\n\n                for(int j=0;j<(int)freeRects.size();j++){\n                    auto &F=freeRects[j];\n                    if(!(F.x1<=xi && xi<F.x2 && F.y1<=yi && yi<F.y2))\n                        continue;\n                    int Rw=F.x2-F.x1, Rh=F.y2-F.y1;\n\n                    // try four \"1D knapsack\" dims\n                    // under\u2010shoot in h\u2010direction\n                    if(Rh>0){\n                        long long wu= ri/Rh;\n                        if(wu>=1 && wu<=Rw){\n                            int w=(int)wu, h=Rh;\n                            int L0=max(F.x1, xi-w+1), Rg0=min(xi, F.x2-w);\n                            int D0=max(F.y1, yi-h+1), U0=min(yi, F.y2-h);\n                            if(L0<=Rg0 && D0<=U0){\n                                double rat=(double)(w*1LL*h)/ri;\n                                if(rat>bestR){\n                                    bestR=rat;\n                                    bestFb={j,w,h,L0,Rg0,D0,U0};\n                                }\n                            }\n                        }\n                        long long wo=(ri+Rh-1)/Rh;\n                        if(wo>=1 && wo<=Rw){\n                            int w=(int)wo, h=Rh;\n                            int L0=max(F.x1, xi-w+1), Rg0=min(xi, F.x2-w);\n                            int D0=max(F.y1, yi-h+1), U0=min(yi, F.y2-h);\n                            if(L0<=Rg0 && D0<=U0){\n                                double rat=(double)ri/(w*1LL*h);\n                                if(rat>bestR){\n                                    bestR=rat;\n                                    bestFb={j,w,h,L0,Rg0,D0,U0};\n                                }\n                            }\n                        }\n                    }\n                    // under/over in w\u2010direction\n                    if(Rw>0){\n                        long long hu= ri/Rw;\n                        if(hu>=1 && hu<=Rh){\n                            int w=Rw, h=(int)hu;\n                            int L0=max(F.x1, xi-w+1), Rg0=min(xi, F.x2-w);\n                            int D0=max(F.y1, yi-h+1), U0=min(yi, F.y2-h);\n                            if(L0<=Rg0 && D0<=U0){\n                                double rat=(double)(w*1LL*h)/ri;\n                                if(rat>bestR){\n                                    bestR=rat;\n                                    bestFb={j,w,h,L0,Rg0,D0,U0};\n                                }\n                            }\n                        }\n                        long long ho=(ri+Rw-1)/Rw;\n                        if(ho>=1 && ho<=Rh){\n                            int w=Rw, h=(int)ho;\n                            int L0=max(F.x1, xi-w+1), Rg0=min(xi, F.x2-w);\n                            int D0=max(F.y1, yi-h+1), U0=min(yi, F.y2-h);\n                            if(L0<=Rg0 && D0<=U0){\n                                double rat=(double)ri/(w*1LL*h);\n                                if(rat>bestR){\n                                    bestR=rat;\n                                    bestFb={j,w,h,L0,Rg0,D0,U0};\n                                }\n                            }\n                        }\n                    }\n                }\n\n                if(bestR>0){\n                    // place the best 1-D fallback\n                    int j=bestFb.j, w=bestFb.w, h=bestFb.h;\n                    int a0 = xi - w/2;  a0 = min(max(a0,bestFb.L), bestFb.Rg);\n                    int b0y= yi - h/2;  b0y= min(max(b0y,bestFb.D), bestFb.U);\n                    ans[idx]={a0,b0y,a0+w,b0y+h};\n\n                    // split\n                    Rect F=freeRects[j];\n                    removeRect(j);\n                    int X1=F.x1, Y1=F.y1, X2=F.x2, Y2=F.y2;\n                    addFree({X1,      Y1,      a0,       Y2});\n                    addFree({a0+w,    Y1,      X2,       Y2});\n                    addFree({a0,      Y1,      a0+w,     b0y});\n                    addFree({a0,      b0y+h,   a0+w,     Y2});\n                }\n                else {\n                    // fallback #2: a 1\u00d71 somewhere\n                    Rect F=freeRects.back();\n                    int j=(int)freeRects.size()-1;\n                    int a0=F.x1, b0y=F.y1;\n                    ans[idx]={a0,b0y,a0+1,b0y+1};\n                    removeRect(j);\n                    addFree({F.x1,      F.y1,    a0,       F.y2});\n                    addFree({a0+1,      F.y1,    F.x2,     F.y2});\n                    addFree({a0,        F.y1,    a0+1,     b0y});\n                    addFree({a0,        b0y+1,   a0+1,     F.y2});\n                }\n            }\n        }\n\n        // evaluate\n        double S=0;\n        for(int i=0;i<n;i++){\n            auto &rc=ans[i];\n            if(rc[0]<=x[i] && x[i]<rc[2] && rc[1]<=y[i] && y[i]<rc[3]){\n                long long si=1LL*(rc[2]-rc[0])*(rc[3]-rc[1]);\n                double ratio=(double)min(r[i],si)/max(r[i],si);\n                S += 1.0 - (1.0-ratio)*(1.0-ratio);\n            }\n        }\n        if(S>bestSum){\n            bestSum=S;\n            bestAns=ans;\n        }\n    }\n\n    // output the best\n    for(int i=0;i<n;i++){\n        auto &a=bestAns[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\nstatic constexpr int H = 50, W = 50;\nstatic constexpr int DX[4] = {-1,1,0,0};\nstatic constexpr int DY[4] = {0,0,-1,1};\nstatic constexpr char DC[4] = {'U','D','L','R'};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    cin >> si >> sj;\n\n    static int t[H][W], pval[H][W];\n    int maxTile = 0;\n    for(int i = 0; i < H; i++){\n        for(int j = 0; j < W; j++){\n            cin >> t[i][j];\n            maxTile = max(maxTile, t[i][j]);\n        }\n    }\n    for(int i = 0; i < H; i++){\n        for(int j = 0; j < W; j++){\n            cin >> pval[i][j];\n        }\n    }\n    int M = maxTile + 1;    // number of tiles\n    int TOT = M;            // max possible steps\n\n    // stamping trick for visited\u2010tiles in each run\n    vector<int> visitedStamp(M, 0);\n    int stamp = 1;\n\n    // RNG\n    uint64_t seed = chrono::high_resolution_clock::now()\n                        .time_since_epoch().count();\n    mt19937_64 rng(seed ^ (seed << 13));\n\n    // best overall\n    vector<char> bestPath;\n    long long bestScore = -1;\n\n    // temp\n    vector<char> curPath; \n    curPath.reserve(TOT);\n\n    // time\u2010boxing \n    auto t0 = chrono::steady_clock::now();\n    constexpr double TIME_LIMIT = 1.85;\n\n    // main multi\u2010start loop\n    for(int iter = 0; ; iter++){\n        // time check every 32 iters\n        if((iter & 31) == 0){\n            auto now = chrono::steady_clock::now();\n            double sec = double((now - t0).count()) * 1e-9;\n            if(sec > TIME_LIMIT) break;\n        }\n\n        // choose weights: periodic extremes + random\n        int md = iter % 200;\n        int WD, WP;\n        if(md == 0){\n            // pure degree\u2010only\n            WD = 20000; WP = 0;\n        } else if(md == 1){\n            // pure score\u2010only\n            WD = 0; WP = 200;\n        } else if(md == 2){\n            // fixed balanced mix\n            WD = 10000; WP = 100;\n        } else {\n            // fully random dynamic mix\n            WD = int(rng() % 20001);   // [0..20000]\n            WP = int(rng() % 201);     // [0..200]\n        }\n\n        // clear for this run\n        curPath.clear();\n        int ci = si, cj = sj;\n        long long curScore = pval[ci][cj];\n        visitedStamp[ t[ci][cj] ] = stamp;\n        int steps = 0;\n\n        // one\u2010step lookahead greedy with dynamic weights\n        while(true){\n            int bestW = INT_MIN, bestD = -1, ni = -1, nj = -1;\n\n            for(int d = 0; d < 4; d++){\n                int ti = ci + DX[d];\n                int tj = cj + DY[d];\n                if(ti < 0 || ti >= H || tj < 0 || tj >= W) continue;\n                int tid = t[ti][tj];\n                if(visitedStamp[tid] == stamp) continue;\n\n                // count unvisited\u2010tile neighbors\n                int deg = 0;\n                for(int d2 = 0; d2 < 4; d2++){\n                    int xi = ti + DX[d2], xj = tj + DY[d2];\n                    if(xi < 0 || xi >= H || xj < 0 || xj >= W) continue;\n                    if(visitedStamp[ t[xi][xj] ] != stamp)\n                        deg++;\n                }\n\n                // dynamic mix: w = deg*WD*(TOT-steps) + p*WP*steps + tiny_noise\n                int w = deg * WD * (TOT - steps)\n                      + pval[ti][tj] * WP * steps\n                      + int(rng() & 15);\n\n                if(w > bestW){\n                    bestW = w;\n                    bestD = d;\n                    ni = ti; nj = tj;\n                }\n            }\n\n            if(bestD < 0) break; // dead end\n            // commit\n            ci = ni; cj = nj;\n            steps++;\n            visitedStamp[ t[ci][cj] ] = stamp;\n            curScore += pval[ci][cj];\n            curPath.push_back( DC[bestD] );\n        }\n\n        // record if best\n        if(curScore > bestScore){\n            bestScore = curScore;\n            bestPath = curPath;\n        }\n        stamp++;\n    }\n\n    // output\n    for(char c : bestPath) cout << c;\n    cout << \"\\n\";\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nstatic constexpr int N = 30;\nstatic constexpr int VERTS = N * N;\n\n// Base initialization\nstatic constexpr double INIT_W    = 5000.0;\n\n// Hyper\u2010parameters (start/end)\nstatic constexpr double ALPHA0    = 0.30;   // initial LR\nstatic constexpr double ALPHA_MIN = 0.03;   // final LR\nstatic constexpr double EXPL0     = 400.0;  // initial exploration bonus\nstatic constexpr double SMOOTH    = 0.08;   // smoothing factor towards row/col mean\n\n// Directions\nint dr[4]   = {-1, +1,  0,  0};\nint dc[4]   = { 0,  0, -1, +1};\nchar dch[4] = {'U','D','L','R'};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // Estimated weights and visit counts\n    static double w_h[N][N-1], w_v[N-1][N];\n    static int    cnt_h[N][N-1], cnt_v[N-1][N];\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N-1;j++){\n            w_h[i][j] = INIT_W;\n            cnt_h[i][j] = 0;\n        }\n    }\n    for(int i=0;i<N-1;i++){\n        for(int j=0;j<N;j++){\n            w_v[i][j] = INIT_W;\n            cnt_v[i][j] = 0;\n        }\n    }\n\n    // Dijkstra buffers\n    static double distArr[VERTS];\n    static bool   done[VERTS];\n    static int    prevNode[VERTS];\n    static char   prevDir[VERTS];\n\n    auto idx = [&](int r,int c){ return r * N + c; };\n\n    // RNG for neighbor\u2010shuffle\n    mt19937 rng(712687126);\n\n    for(int qi=0;qi<1000;qi++){\n        int si,sj,ti,tj;\n        if(!(cin>>si>>sj>>ti>>tj)) return 0;\n\n        // Compute time\u2010dependent learning & exploration\n        double frac = qi / 1000.0;\n        double alpha = ALPHA0 * (1 - frac) + ALPHA_MIN * frac;\n        double expl  = EXPL0   * (1 - frac);\n\n        // Shuffle directions to break tie\u2010bias\n        array<int,4> dirs = {0,1,2,3};\n        shuffle(dirs.begin(), dirs.end(), rng);\n\n        // Init Dijkstra\n        const double INF = 1e18;\n        for(int i=0;i<VERTS;i++){\n            distArr[i] = INF;\n            done[i] = false;\n        }\n        int s_id = idx(si,sj), t_id = idx(ti,tj);\n        distArr[s_id] = 0.0;\n\n        priority_queue<pair<double,int>,\n                       vector<pair<double,int>>,\n                       greater<pair<double,int>>> pq;\n        pq.push({0.0, s_id});\n\n        // Dijkstra + exploration bonus\n        while(!pq.empty()){\n            auto [cd,u] = pq.top(); pq.pop();\n            if(done[u]) continue;\n            done[u] = true;\n            if(u == t_id) break;\n            int ur = u / N, uc = u % N;\n            for(int d: dirs){\n                int vr = ur + dr[d], vc = uc + dc[d];\n                if(vr<0||vr>=N||vc<0||vc>=N) continue;\n                double w_e, bonus;\n                if(d==0){        // U: vertical above\n                    w_e   = w_v[vr][vc];\n                    bonus = expl / sqrt(double(cnt_v[vr][vc] + 1));\n                }\n                else if(d==1){   // D: vertical below\n                    w_e   = w_v[ur][uc];\n                    bonus = expl / sqrt(double(cnt_v[ur][uc] + 1));\n                }\n                else if(d==2){   // L: horizontal left\n                    w_e   = w_h[vr][vc];\n                    bonus = expl / sqrt(double(cnt_h[vr][vc] + 1));\n                }\n                else {           // R: horizontal right\n                    w_e   = w_h[ur][uc];\n                    bonus = expl / sqrt(double(cnt_h[ur][uc] + 1));\n                }\n                double cst = w_e - bonus;\n                if(cst < 1.0) cst = 1.0;\n                int v = idx(vr,vc);\n                double nd = cd + cst;\n                if(nd < distArr[v]){\n                    distArr[v] = nd;\n                    prevNode[v] = u;\n                    prevDir[v]  = dch[d];\n                    pq.push({nd, v});\n                }\n            }\n        }\n\n        // Reconstruct path\n        vector<char> rev;\n        {\n            int cur = t_id;\n            while(cur != s_id){\n                rev.push_back(prevDir[cur]);\n                cur = prevNode[cur];\n            }\n        }\n        int L = rev.size();\n        string path; path.reserve(L);\n        for(int i=L-1;i>=0;i--) path.push_back(rev[i]);\n\n        // Print & flush\n        cout << path << \"\\n\" << flush;\n\n        // Read noisy total length\n        int b_obs;\n        cin >> b_obs;\n\n        // Collect edges and compute s_est\n        struct Edge { bool horiz; int r,c; };\n        vector<Edge> edges; edges.reserve(L);\n        double s_est = 0.0;\n        int cr = si, cc = sj;\n        for(char mv: path){\n            if(mv=='U'){\n                edges.push_back({false, cr-1, cc});\n                s_est += w_v[cr-1][cc];\n                cr--;\n            }\n            else if(mv=='D'){\n                edges.push_back({false, cr, cc});\n                s_est += w_v[cr][cc];\n                cr++;\n            }\n            else if(mv=='L'){\n                edges.push_back({true, cr, cc-1});\n                s_est += w_h[cr][cc-1];\n                cc--;\n            }\n            else { // 'R'\n                edges.push_back({true, cr, cc});\n                s_est += w_h[cr][cc];\n                cc++;\n            }\n        }\n\n        // Weighted residual update\n        double err = double(b_obs) - s_est;\n        if(L>0 && fabs(err)>1e-9){\n            // Track which rows/cols are touched for smoothing\n            vector<bool> touch_row(N,false), touch_col(N,false);\n            for(auto &e: edges){\n                if(e.horiz){\n                    touch_row[e.r] = true;\n                    double &w = w_h[e.r][e.c];\n                    int    &ct= cnt_h[e.r][e.c];\n                    ct++;\n                    double lr = alpha / sqrt(double(ct));\n                    w += w * lr * (err / s_est);\n                    if(w < 1.0) w = 1.0;\n                } else {\n                    touch_col[e.c] = true;\n                    double &w = w_v[e.r][e.c];\n                    int    &ct= cnt_v[e.r][e.c];\n                    ct++;\n                    double lr = alpha / sqrt(double(ct));\n                    w += w * lr * (err / s_est);\n                    if(w < 1.0) w = 1.0;\n                }\n            }\n            // Smoothing toward row/column means\n            for(int i=0;i<N;i++){\n                if(touch_row[i]){\n                    // horizontal row\u2010mean\n                    double mu = 0;\n                    for(int j=0;j<N-1;j++) mu += w_h[i][j];\n                    mu /= (N-1);\n                    for(int j=0;j<N-1;j++){\n                        w_h[i][j] = w_h[i][j] * (1 - SMOOTH) + mu * SMOOTH;\n                    }\n                }\n                if(touch_col[i]){\n                    // vertical column\u2010mean\n                    double mu = 0;\n                    for(int r=0;r<N-1;r++) mu += w_v[r][i];\n                    mu /= (N-1);\n                    for(int r=0;r<N-1;r++){\n                        w_v[r][i] = w_v[r][i] * (1 - SMOOTH) + mu * SMOOTH;\n                    }\n                }\n            }\n        }\n    }\n\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// fast xorshift RNG\nstatic uint64_t rng_state = chrono::steady_clock::now().time_since_epoch().count();\ninline uint32_t xorshift32() {\n    rng_state ^= rng_state << 13;\n    rng_state ^= rng_state >> 7;\n    rng_state ^= rng_state << 17;\n    return (uint32_t)rng_state;\n}\ninline int randInt(int l, int r) {\n    return l + (xorshift32() % (r - l + 1));\n}\ninline double randDouble() {\n    // 24\u2010bit uniform\n    return (xorshift32() & 0xFFFFFF) / double(1<<24);\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const double TL = 2.95;     // leave a small margin\n    const int N = 20;\n    int M;\n    cin >> M;\n    vector<string> s(M);\n    for(int i = 0; i < M; i++){\n        cin >> s[i];\n    }\n    // convert strings to 0..7\n    vector<vector<int>> sChars(M);\n    for(int i = 0; i < M; i++){\n        int L = s[i].size();\n        sChars[i].resize(L);\n        for(int j = 0; j < L; j++){\n            sChars[i][j] = s[i][j] - 'A';\n        }\n    }\n\n    // Build all placements\n    struct Placement {\n        int si;\n        int len;\n        vector<int> coord; // (i,j) pairs flattened: coord[2*p],coord[2*p+1]\n    };\n    vector<Placement> placements;\n    placements.reserve(M * 2 * N);\n    const int CELL = N * N;\n    vector<vector<int>> byCell(CELL);\n    for(int c = 0; c < CELL; c++){\n        byCell[c].reserve(600);\n    }\n\n    for(int si = 0; si < M; si++){\n        int L = sChars[si].size();\n        for(int dir = 0; dir < 2; dir++){ // 0=H,1=V\n            for(int x = 0; x < N; x++){\n                for(int st = 0; st < N; st++){\n                    Placement P;\n                    P.si = si;\n                    P.len = L;\n                    P.coord.resize(2 * L);\n                    for(int p = 0; p < L; p++){\n                        int i,j;\n                        if(dir == 0){\n                            i = x;\n                            j = (st + p) % N;\n                        } else {\n                            i = (st + p) % N;\n                            j = x;\n                        }\n                        P.coord[2*p] = i;\n                        P.coord[2*p+1] = j;\n                    }\n                    int pid = placements.size();\n                    placements.push_back(move(P));\n                    // index into byCell\n                    auto &C = placements.back().coord;\n                    for(int p = 0; p < placements.back().len; p++){\n                        int i = C[2*p], j = C[2*p+1];\n                        byCell[i*N + j].push_back(pid);\n                    }\n                }\n            }\n        }\n    }\n\n    int Pn = placements.size();\n\n    // current grid as ints 0..7\n    vector<int> grid(CELL);\n    vector<int> bestGrid(CELL);\n\n    // valid flags for placements\n    vector<char> valid(Pn, 0);\n    // match count per string\n    vector<int> matchCount(M, 0);\n\n    // initialize grid randomly\n    for(int i = 0; i < CELL; i++){\n        grid[i] = randInt(0,7);\n    }\n    // compute initial valid[] and matchCount[]\n    for(int pid = 0; pid < Pn; pid++){\n        auto &P = placements[pid];\n        bool ok = true;\n        for(int p = 0; p < P.len; p++){\n            int i = P.coord[2*p], j = P.coord[2*p+1];\n            if(grid[i*N+j] != sChars[P.si][p]){\n                ok = false;\n                break;\n            }\n        }\n        if(ok){\n            valid[pid] = 1;\n            matchCount[P.si]++;\n        }\n    }\n    int curC = 0;\n    for(int i = 0; i < M; i++) if(matchCount[i] > 0) curC++;\n    int bestC = curC;\n    bestGrid = grid;\n\n    // buffers for delta computations\n    vector<pair<int,char>> changed; changed.reserve(1000);\n    vector<int> sis; sis.reserve(1000);\n    vector<int> oldMatch(M);\n    vector<char> seen(M,0);\n\n    auto start = chrono::steady_clock::now();\n    int iter = 0;\n    const double T0 = 5.0, T1 = 0.1;\n\n    while(true){\n        iter++;\n        if((iter & 511) == 0){\n            auto now = chrono::steady_clock::now();\n            double t = chrono::duration<double>(now - start).count();\n            if(t > TL) break;\n        }\n        // temperature\n        auto now = chrono::steady_clock::now();\n        double t = chrono::duration<double>(now - start).count() / TL;\n        if(t > 1.0) t = 1.0;\n        double T = T0 + (T1 - T0) * t;\n\n        // pick a random cell\n        int c = randInt(0, CELL-1);\n        int oldL = grid[c];\n        int newL = randInt(0,7);\n        if(newL == oldL) continue;\n\n        changed.clear();\n        sis.clear();\n        int newC = curC;\n\n        int ci = c / N, cj = c % N;\n\n        // try the change\n        for(int pid : byCell[c]){\n            auto &P = placements[pid];\n            int si = P.si;\n            bool prev = valid[pid];\n            bool nowv = true;\n            // check validity if we change this cell to newL\n            for(int p = 0; p < P.len; p++){\n                int ii = P.coord[2*p], jj = P.coord[2*p+1];\n                int gv = (ii==ci && jj==cj ? newL : grid[ii*N+jj]);\n                if(gv != sChars[si][p]){\n                    nowv = false;\n                    break;\n                }\n            }\n            if(prev != nowv){\n                changed.emplace_back(pid, prev);\n                if(!seen[si]){\n                    seen[si] = 1;\n                    sis.push_back(si);\n                    oldMatch[si] = matchCount[si];\n                }\n                if(prev){\n                    matchCount[si]--;\n                    if(oldMatch[si] > 0 && matchCount[si] == 0) newC--;\n                } else {\n                    matchCount[si]++;\n                    if(oldMatch[si] == 0 && matchCount[si] == 1) newC++;\n                }\n                valid[pid] = nowv;\n            }\n        }\n\n        int delta = newC - curC;\n        bool accept = false;\n        if(delta >= 0) accept = true;\n        else {\n            double p = exp(delta / T);\n            if(randDouble() < p) accept = true;\n        }\n\n        if(accept){\n            grid[c] = newL;\n            curC = newC;\n            if(curC > bestC){\n                bestC = curC;\n                bestGrid = grid;\n            }\n        } else {\n            // revert\n            for(auto &pc : changed){\n                valid[pc.first] = pc.second;\n            }\n            for(int si : sis){\n                matchCount[si] = oldMatch[si];\n            }\n        }\n        for(int si : sis) seen[si] = 0;\n    }\n\n    // output bestGrid\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            char ch = char('A' + bestGrid[i*N+j]);\n            cout << ch;\n        }\n        cout << \"\\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    cin >> N >> si >> sj;\n    vector<string> C(N);\n    for(int i = 0; i < N; i++) {\n        cin >> C[i];\n    }\n\n    // 1) Flatten road cells, assign IDs, record cost and position.\n    vector<int> id_map(N*N, -1);\n    vector<pair<int,int>> id2pos;\n    vector<int> id2cost;\n    id2pos.reserve(N*N);\n    id2cost.reserve(N*N);\n    int r = 0;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            char ch = C[i][j];\n            if(ch != '#'){\n                id_map[i*N + j] = r++;\n                id2pos.emplace_back(i,j);\n                id2cost.push_back(ch - '0');\n            }\n        }\n    }\n    if(r == 0){\n        // No roads at all (degenerate) \u2014 just print empty.\n        cout << \"\\n\";\n        return 0;\n    }\n    int startId = id_map[si*N + sj];\n\n    // 2) Build 4\u2010nbr graph with symmetric weights w(u,v)=cost[u]+cost[v].\n    vector<vector<pair<int,int>>> graph(r);\n    static const int di[4] = {-1,1,0,0}, dj[4] = {0,0,-1,1};\n    for(int u = 0; u < r; u++){\n        auto [i,j] = id2pos[u];\n        int cu = id2cost[u];\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            int v = id_map[ni*N + nj];\n            if(v<0) continue;\n            int cv = id2cost[v];\n            graph[u].emplace_back(v, cu+cv);\n        }\n    }\n\n    // 3) MST via Prim from startId.\n    const int INF = 1e9;\n    vector<int> key(r, INF), parent(r, -1);\n    vector<char> used(r,0);\n    key[startId] = 0;\n    priority_queue<pair<int,int>,\n        vector<pair<int,int>>,\n        greater<pair<int,int>>> pq;\n    pq.emplace(0, startId);\n    while(!pq.empty()){\n        auto [cw,u] = pq.top(); pq.pop();\n        if(used[u]) continue;\n        used[u] = 1;\n        for(auto &e: graph[u]){\n            int v = e.first, wuv = e.second;\n            if(!used[v] && wuv < key[v]){\n                key[v] = wuv;\n                parent[v] = u;\n                pq.emplace(wuv, v);\n            }\n        }\n    }\n\n    // 4) Build undirected MST adjacency.\n    vector<vector<int>> treeAdj(r);\n    for(int v = 0; v < r; v++){\n        int u = parent[v];\n        if(u >= 0){\n            treeAdj[u].push_back(v);\n            treeAdj[v].push_back(u);\n        }\n    }\n\n    // 5) Compute original MST\u2010degree and detect \"turn\" nodes (deg==2 & non\u2010collinear).\n    vector<int> deg(r);\n    for(int u = 0; u < r; u++){\n        deg[u] = (int)treeAdj[u].size();\n    }\n    vector<char> is_turn(r, 0);\n    for(int u = 0; u < r; u++){\n        if(deg[u] == 2){\n            int a = treeAdj[u][0], b = treeAdj[u][1];\n            auto [ui,uj] = id2pos[u];\n            auto [ai,aj] = id2pos[a];\n            auto [bi,bj] = id2pos[b];\n            // collinear if same row or same col\n            bool col = (ai==ui && bi==ui) || (aj==uj && bj==uj);\n            if(!col) is_turn[u] = 1;\n        }\n    }\n    // keep[u] = start || junction (deg>=3) || turn (deg==2 & non\u2010collinear)\n    vector<char> keep(r,0);\n    for(int u = 0; u < r; u++){\n        if(u == startId || deg[u] >= 3 || is_turn[u]) keep[u] = 1;\n    }\n\n    // 6) Root the MST at startId, build children[].\n    vector<int> parentT(r, -1);\n    vector<vector<int>> children(r);\n    parentT[startId] = -1;\n    {\n        // simple DFS stack\n        vector<int> stk;\n        stk.reserve(r);\n        stk.push_back(startId);\n        while(!stk.empty()){\n            int u = stk.back(); stk.pop_back();\n            for(int v: treeAdj[u]){\n                if(v == parentT[u]) continue;\n                parentT[v] = u;\n                children[u].push_back(v);\n                stk.push_back(v);\n            }\n        }\n    }\n\n    // 7) Compute hasImportantSubtree[u]\n    vector<char> hasImp(r,0);\n    function<void(int)> dfs_imp = [&](int u){\n        char h = keep[u];\n        for(int v: children[u]){\n            dfs_imp(v);\n            if(hasImp[v]) h = 1;\n        }\n        hasImp[u] = h;\n    };\n    dfs_imp(startId);\n\n    // 8) Euler\u2010style DFS on the *pruned* tree, emitting moves only into subtrees\n    //    that contain some keep\u2010node.\n    string ans;\n    ans.reserve(r*2);\n\n    auto dirChar = [&](int ui,int uj,int vi,int vj){\n        if(vi == ui-1 && vj == uj) return 'U';\n        if(vi == ui+1 && vj == uj) return 'D';\n        if(vi == ui && vj == uj-1) return 'L';\n        return 'R';\n    };\n    auto rev = [&](char c){\n        if(c=='U') return 'D';\n        if(c=='D') return 'U';\n        if(c=='L') return 'R';\n        return 'L';\n    };\n\n    function<void(int)> dfs_euler = [&](int u){\n        auto [ui,uj] = id2pos[u];\n        for(int v: children[u]){\n            if(!hasImp[v]) continue;  // prune entire subtree\n            auto [vi,vj] = id2pos[v];\n            char mv = dirChar(ui,uj,vi,vj);\n            ans.push_back(mv);\n            dfs_euler(v);\n            ans.push_back(rev(mv));\n        }\n    };\n    dfs_euler(startId);\n\n    // 9) Output\n    cout << ans << \"\\n\";\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Interactive scheduler with simple skill\u2010estimation.\n\nstruct Node {\n    int depth;\n    int best_pred;\n    int id;\n};\nstruct PQCmp {\n    bool operator()(Node const &a, Node const &b) const {\n        if(a.depth != b.depth) return a.depth < b.depth;        // deeper first\n        if(a.best_pred != b.best_pred) return a.best_pred < b.best_pred; // larger best_pred first\n        return a.id > b.id;                                      // smaller id first\n    }\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n    vector<vector<int>> d(N, vector<int>(K));\n    for(int i = 0; i < N; i++)\n        for(int j = 0; j < K; j++)\n            cin >> d[i][j];\n\n    vector<vector<int>> adj(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        adj[u].push_back(v);\n        indeg[v]++;\n    }\n\n    // 1) Compute \"depth\" = 1 + max depth of children\n    vector<int> depth(N, -1);\n    function<int(int)> dfs = [&](int u){\n        if(depth[u] != -1) return depth[u];\n        int best = 0;\n        for(int v: adj[u])\n            best = max(best, dfs(v));\n        return depth[u] = best + 1;\n    };\n    for(int i = 0; i < N; i++)\n        if(depth[i] < 0)\n            dfs(i);\n\n    // Skill estimates: lower bounds of s[j][k]\n    vector<vector<int>> s_est(M, vector<int>(K, 0));\n\n    // Track state\n    vector<bool> done(N,false), started(N,false);\n    vector<int> assigned_task(M,-1), assign_day(M,0);\n    vector<char> worker_free(M,1);\n    vector<int> free_list;\n    free_list.reserve(M);\n    for(int j=0;j<M;j++) free_list.push_back(j);\n\n    // Priority queue of ready tasks\n    priority_queue<Node,vector<Node>,PQCmp> pq;\n\n    // Compute best_pred for a task i under current s_est[]\n    auto compute_best_pred = [&](int i){\n        int best = INT_MAX;\n        for(int j=0;j<M;j++){\n            int sumd = 0;\n            // compute sum of max(0, d[i][k] - s_est[j][k])\n            for(int k2=0;k2<K;k2++){\n                int delta = d[i][k2] - s_est[j][k2];\n                if(delta>0) sumd += delta;\n            }\n            if(sumd < best) best = sumd;\n        }\n        return best==INT_MAX?0:best;\n    };\n\n    // Initially push indegree\u2010zero tasks\n    for(int i=0;i<N;i++){\n        if(indeg[i]==0){\n            int bp = compute_best_pred(i);\n            pq.push({depth[i], bp, i});\n        }\n    }\n\n    int cur_day = 1;\n    while(true){\n        // 1) morning: assign as many as possible\n        vector<pair<int,int>> out;\n        out.reserve(M);\n        // Pop tasks and match to best free worker\n        while(!free_list.empty() && !pq.empty()){\n            // pop a valid task with up\u2010to\u2010date best_pred\n            Node nd;\n            while(true){\n                if(pq.empty()) break;\n                nd = pq.top(); pq.pop();\n                int i = nd.id;\n                if(started[i]) continue; // already assigned\n                int bp_now = compute_best_pred(i);\n                if(bp_now != nd.best_pred){\n                    // stale, re\u2010push fresh\n                    pq.push({depth[i], bp_now, i});\n                    continue;\n                }\n                // got a good one\n                break;\n            }\n            if(started[nd.id]) break;\n            int i = nd.id;\n            // pick best free worker for task i\n            int best_w = -1, best_cost = INT_MAX;\n            for(int idx=0;idx<(int)free_list.size();idx++){\n                int j = free_list[idx];\n                int sumd = 0;\n                for(int k2=0;k2<K;k2++){\n                    int delta = d[i][k2] - s_est[j][k2];\n                    if(delta>0) sumd += delta;\n                }\n                if(sumd < best_cost){\n                    best_cost = sumd;\n                    best_w = idx;\n                }\n            }\n            int w = free_list[best_w];\n            // remove worker w from free_list\n            free_list[best_w] = free_list.back();\n            free_list.pop_back();\n\n            // assign\n            started[i] = true;\n            worker_free[w] = 0;\n            assigned_task[w] = i;\n            assign_day[w] = cur_day;\n            out.emplace_back(w+1, i+1);\n        }\n\n        // print assignment\n        cout << (int)out.size();\n        for(auto &pr: out){\n            cout << \" \" << pr.first << \" \" << pr.second;\n        }\n        cout << \"\\n\" << flush;\n\n        // 2) read who finished at end of day\n        int cnt;\n        cin >> cnt;\n        if(!cin || cnt<0) break;\n        for(int _=0;_<cnt;_++){\n            int f; cin >> f;\n            int w = f-1;\n            int i = assigned_task[w];\n            // compute observed t\n            int t = cur_day - assign_day[w] + 1;\n            int w_est = t>1 ? t-1 : 0;\n            // update skill\u2010estimate\n            if(i>=0){\n                for(int k2=0;k2<K;k2++){\n                    int lb = d[i][k2] - w_est;\n                    if(lb> s_est[w][k2])\n                        s_est[w][k2] = lb;\n                }\n            }\n            // free worker\n            worker_free[w] = 1;\n            assigned_task[w] = -1;\n            free_list.push_back(w);\n            // mark task done and push children if ready\n            if(i>=0 && !done[i]){\n                done[i] = true;\n                for(int nx: adj[i]){\n                    if(--indeg[nx]==0){\n                        int bp = compute_best_pred(nx);\n                        pq.push({depth[nx], bp, nx});\n                    }\n                }\n            }\n        }\n        cur_day++;\n    }\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\n#include <chrono>\nusing namespace std;\nusing ll = long long;\nstatic inline int manh(int x1,int y1,int x2,int y2){\n    return abs(x1-x2)+abs(y1-y2);\n}\nstruct Order{ int a,b,c,d,dist; };\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    // 1) read input\n    vector<Order> ord(1000);\n    for(int i=0;i<1000;i++){\n        cin>>ord[i].a>>ord[i].b>>ord[i].c>>ord[i].d;\n        ord[i].dist = manh(ord[i].a,ord[i].b,ord[i].c,ord[i].d);\n    }\n    // time stamp\n    auto time_start = chrono::steady_clock::now();\n    const double TIME_LIMIT = 1.97;\n\n    // 2) pick 50 by smallest internal dist\n    vector<int> sel(1000);\n    iota(sel.begin(),sel.end(),0);\n    nth_element(sel.begin(), sel.begin()+50, sel.end(),\n                [&](int i,int j){ return ord[i].dist < ord[j].dist; });\n    sel.resize(50);\n    const int M = 50;\n\n    // 3) build condensed graph\n    vector<int> px(M),py(M),dx(M),dy(M),start_cost(M),end_cost(M);\n    for(int i=0;i<M;i++){\n        auto &o = ord[sel[i]];\n        px[i]=o.a; py[i]=o.b;\n        dx[i]=o.c; dy[i]=o.d;\n        start_cost[i]=manh(400,400,px[i],py[i]);\n        end_cost[i]  =manh(dx[i],dy[i],400,400);\n    }\n    static int trans[50][50];\n    for(int i=0;i<M;i++){\n        for(int j=0;j<M;j++){\n            trans[i][j] = manh(dx[i],dy[i], px[j],py[j]);\n        }\n    }\n\n    // 4) multi\u2010start greedy NN\n    vector<int> order_by_start(M);\n    iota(order_by_start.begin(),order_by_start.end(),0);\n    sort(order_by_start.begin(),order_by_start.end(),\n         [&](int i,int j){return start_cost[i]<start_cost[j];});\n    const int K_GREED = min(M,30);\n    vector<pair<ll,vector<int>>> greeds;\n    greeds.reserve(K_GREED);\n    for(int ss=0; ss<K_GREED; ss++){\n        int s = order_by_start[ss];\n        vector<char> used(M,false);\n        vector<int> path;\n        path.reserve(M);\n        path.push_back(s);\n        used[s]=1;\n        int cur=s;\n        for(int t=1;t<M;t++){\n            int bestc=INT_MAX,bestj=-1;\n            for(int j=0;j<M;j++) if(!used[j]){\n                int c = trans[cur][j];\n                if(c<bestc){ bestc=c; bestj=j; }\n            }\n            path.push_back(bestj);\n            used[bestj]=1;\n            cur=bestj;\n        }\n        ll csum = start_cost[path[0]];\n        for(int i=0;i+1<M;i++) csum += trans[path[i]][path[i+1]];\n        csum += end_cost[path[M-1]];\n        greeds.emplace_back(csum, std::move(path));\n    }\n    sort(greeds.begin(), greeds.end(),\n         [&](auto &A, auto &B){return A.first<B.first;});\n\n    // 5) true directed 2-opt on top T=2 seeds within TL_OPT\n    const int T_OPT = min((int)greeds.size(),2);\n    const double TL_OPT = 1.30;\n    ll best_cost = greeds[0].first;\n    vector<int> best_path = greeds[0].second;\n    for(int ti=0; ti<T_OPT; ti++){\n        auto now = chrono::steady_clock::now();\n        if(chrono::duration<double>(now - time_start).count() > TL_OPT) break;\n        ll cur_cost = greeds[ti].first;\n        auto P = greeds[ti].second;\n        // directed 2-opt\n        static ll prefix[50];\n        while(true){\n            bool improved=false;\n            // build prefix of interior reversals\n            // prefix[k] = sum_{u=0..k} ( trans[P[u+1]][P[u]] - trans[P[u]][P[u+1]] )\n            prefix[0] = (ll)trans[P[1]][P[0]] - trans[P[0]][P[1]];\n            for(int u=1;u<M-1;u++){\n                prefix[u] = prefix[u-1]\n                          + ((ll)trans[P[u+1]][P[u]] - trans[P[u]][P[u+1]]);\n            }\n            for(int i=1;i<M-1 && !improved;i++){\n                int A=P[i-1], B=P[i];\n                ll orig1 = trans[A][B];\n                ll before = prefix[i-1];\n                for(int j=i+1;j<M && !improved;j++){\n                    int C=P[j];\n                    bool endseg = (j==M-1);\n                    ll orig2 = endseg ? end_cost[C]\n                                      : trans[C][P[j+1]];\n                    ll new1  = trans[A][C];\n                    ll new2  = endseg ? end_cost[B]\n                                      : trans[B][P[j+1]];\n                    ll interior = prefix[j-1] - before;\n                    ll delta = (new1+new2) - (orig1+orig2) + interior;\n                    if(delta<0){\n                        reverse(P.begin()+i, P.begin()+j+1);\n                        cur_cost += delta;\n                        improved = true;\n                    }\n                }\n            }\n            now = chrono::steady_clock::now();\n            if(!improved\n             || chrono::duration<double>(now - time_start).count() > TL_OPT)\n                break;\n        }\n        if(cur_cost < best_cost){\n            best_cost = cur_cost;\n            best_path = std::move(P);\n        }\n    }\n\n    // 6) expand best_path into explicit route_points + cur_sel_ids\n    vector<int> cur_sel_ids(M);\n    for(int k=0;k<M;k++){\n        cur_sel_ids[k] = sel[ best_path[k] ];\n    }\n    vector<pair<int,int>> route;\n    route.reserve(2*M+2);\n    route.emplace_back(400,400);\n    for(int k=0;k<M;k++){\n        auto &o = ord[cur_sel_ids[k]];\n        route.emplace_back(o.a,o.b);\n        route.emplace_back(o.c,o.d);\n    }\n    route.emplace_back(400,400);\n\n    // 7) prepare outside\u2010pool (top K_OUT by internal-dist)\n    static bool in_sel[1000];\n    memset(in_sel,0,sizeof(in_sel));\n    for(int x:cur_sel_ids) in_sel[x]=1;\n    vector<pair<int,int>> outv; // (dist, idx)\n    outv.reserve(1000);\n    for(int i=0;i<1000;i++){\n        if(!in_sel[i]) outv.emplace_back(ord[i].dist, i);\n    }\n    sort(outv.begin(), outv.end());\n    const int K_OUT = 150;\n    if((int)outv.size()>K_OUT) outv.resize(K_OUT);\n    vector<int> outside;\n    outside.reserve(K_OUT);\n    for(auto &p: outv) outside.push_back(p.second);\n\n    // 8) \u201cswap\u2010out / swap\u2010in\u201d local search\n    while(true){\n        auto now = chrono::steady_clock::now();\n        if(chrono::duration<double>(now - time_start).count() > TIME_LIMIT) break;\n\n        // compute removal deltas\n        vector<ll> remd(M);\n        ll best_rem = LLONG_MIN;\n        int rem_i = -1;\n        for(int k=0;k<M;k++){\n            int rp = 2*k+1;\n            auto &L = route[rp-1];\n            auto &P = route[rp];\n            auto &D = route[rp+1];\n            auto &R = route[rp+2];\n            ll before = manh(L.first,L.second,P.first,P.second)\n                      + manh(P.first,P.second,D.first,D.second)\n                      + manh(D.first,D.second,R.first,R.second);\n            ll after  = manh(L.first,L.second,R.first,R.second);\n            ll delta  = before - after; // how much we save by removing\n            remd[k]=delta;\n            if(delta>best_rem){\n                best_rem=delta; rem_i=k;\n            }\n        }\n        if(best_rem<=0) break; // nothing profitable to remove\n\n        // compute insertion deltas for outside\n        ll best_ins = LLONG_MAX;\n        int ins_j = -1, ins_pos=0;\n        for(int j=0;j<(int)outside.size();j++){\n            auto &o = ord[ outside[j] ];\n            ll bestj = LLONG_MAX;\n            int bestp = 0;\n            // only even positions 0..2*M\n            for(int ip=0; ip<=M; ip++){\n                int rp = 2*ip;\n                auto &A = route[rp];\n                auto &B = route[rp+1];\n                ll cost_before = manh(A.first,A.second,B.first,B.second);\n                ll cost_after  = manh(A.first,A.second,o.a,o.b)\n                               + manh(o.a,o.b,o.c,o.d)\n                               + manh(o.c,o.d,B.first,B.second);\n                ll d = cost_after - cost_before;\n                if(d<bestj){\n                    bestj=d; bestp=ip;\n                }\n            }\n            if(bestj<best_ins){\n                best_ins=bestj; ins_j=j; ins_pos=bestp;\n            }\n        }\n        if(ins_j<0 || best_ins >= best_rem) break;\n\n        // apply swap: remove rem_i, insert outside[ins_j] at ins_pos\n        int out_id = outside[ins_j];\n        int old_id = cur_sel_ids[rem_i];\n        // 1) remove from route & sel_ids\n        int rp = 2*rem_i+1;\n        route.erase(route.begin()+rp, route.begin()+rp+2);\n        cur_sel_ids.erase(cur_sel_ids.begin()+rem_i);\n        // adjust insertion index\n        int new_ins = ins_pos;\n        if(ins_pos>rem_i) new_ins = ins_pos-1;\n        // 2) insert into sel_ids\n        cur_sel_ids.insert(cur_sel_ids.begin()+new_ins, out_id);\n        // 3) insert into route\n        int ip = 2*new_ins+1;\n        route.insert(route.begin()+ip, {ord[out_id].a, ord[out_id].b});\n        route.insert(route.begin()+ip+1, {ord[out_id].c, ord[out_id].d});\n        // 4) swap pools\n        outside[ins_j] = old_id;\n        // and continue\n    }\n\n    // 9) output\n    // first line: 50 and the chosen original order\u2010IDs (1\u2010based)\n    cout<<M;\n    for(int id:cur_sel_ids) cout<<' '<<(id+1);\n    cout<<\"\\n\";\n\n    // second line: full route\n    cout<<route.size();\n    for(auto &p:route){\n        cout<<' '<<p.first<<' '<<p.second;\n    }\n    cout<<\"\\n\";\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Disjoint\u2010set union (union by rank + path compression)\nstruct DSU {\n    int n;\n    vector<int> p, r;\n    DSU(int _n): n(_n), p(n,-1), r(n,0) {\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        return p[x]==x ? x : 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    vector<pair<int,int>> coord(N);\n    for(int i = 0; i < N; i++){\n        cin >> coord[i].first >> coord[i].second;\n    }\n    struct Edge { int u,v,id; int d; };\n    vector<Edge> edges;\n    edges.reserve(M);\n    for(int i = 0; i < M; i++){\n        int u,v;\n        cin >> u >> v;\n        int dx = coord[u].first  - coord[v].first;\n        int dy = coord[u].second - coord[v].second;\n        // rounded Euclidean distance\n        int di = int( round( sqrt(double(dx*dx + dy*dy)) ) );\n        edges.push_back({u,v,i,di});\n    }\n\n    // Kruskal on weights = d_i\n    vector<bool> choose(M,false);\n    DSU dsu(N);\n    sort(edges.begin(), edges.end(),\n         [&](auto &A, auto &B){\n             return A.d < B.d;\n         });\n    int taken = 0;\n    for(auto &e: edges){\n        if(taken == N-1) break;\n        if(dsu.unite(e.u, e.v)){\n            choose[e.id] = true;\n            taken++;\n        }\n    }\n    // Now process the stream\n    for(int i = 0; i < M; i++){\n        int l;\n        if(!(cin >> l)) return 0;  // safety\n        if(choose[i]){\n            cout << 1 << '\\n';\n        } else {\n            cout << 0 << '\\n';\n        }\n        cout.flush();  // must flush after each decision\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    vector<int> ppx(N), ppy(N), pt(N);\n    for(int i = 0; i < N; i++){\n        cin >> ppx[i] >> ppy[i] >> pt[i];\n        --ppx[i]; --ppy[i];\n    }\n    int M;\n    cin >> M;\n    vector<int> hx(M), hy(M);\n    for(int i = 0; i < M; i++){\n        cin >> hx[i] >> hy[i];\n        --hx[i]; --hy[i];\n    }\n\n    // Directions: 0=up,1=right,2=down,3=left\n    int dx[4] = {-1, 0, 1,  0};\n    int dy[4] = { 0, 1, 0, -1};\n    char buildC[4] = {'u','r','d','l'};\n\n    // petAt[x][y] = is there at least one pet at (x,y) at start of current turn?\n    static bool petAt[30][30] = {};\n    // humanAt[x][y] = is there a human at (x,y)? (they never move in this plan)\n    static bool humanAt[30][30] = {};\n    for(int i = 0; i < M; i++){\n        humanAt[hx[i]][hy[i]] = true;\n    }\n    // initialize petAt by initial positions\n    for(int i = 0; i < N; i++){\n        petAt[ppx[i]][ppy[i]] = true;\n    }\n\n    // For each human, pick up to 4 build\u2010directions in some fixed order,\n    // avoiding initially occupied or out\u2010of\u2010bounds or human\u2010occupied cells.\n    vector<vector<int>> buildDir(M);\n    for(int i = 0; i < M; i++){\n        int x = hx[i], y = hy[i];\n        for(int d = 0; d < 4; d++){\n            int bx = x + dx[d], by = y + dy[d];\n            // only if inside grid and no human there\n            if(bx < 0 || bx >= 30 || by < 0 || by >= 30) continue;\n            if(humanAt[bx][by]) continue;\n            buildDir[i].push_back(d);\n        }\n    }\n\n    auto canBuild = [&](int bx, int by)->bool {\n        // must be on the grid\n        if(bx < 0 || bx >= 30 || by < 0 || by >= 30) return false;\n        // no human or pet currently on target\n        if(humanAt[bx][by] || petAt[bx][by]) return false;\n        // no pet in any adjacent square\n        for(int dd = 0; dd < 4; dd++){\n            int ax = bx + dx[dd], ay = by + dy[dd];\n            if(ax >= 0 && ax < 30 && ay >= 0 && ay < 30){\n                if(petAt[ax][ay]) return false;\n            }\n        }\n        return true;\n    };\n\n    const int TURNS = 300;\n    string out(M, '.');\n\n    for(int turn = 0; turn < TURNS; turn++){\n        // 1) Decide and output actions\n        for(int i = 0; i < M; i++){\n            if(turn < (int)buildDir[i].size()){\n                int d = buildDir[i][turn];\n                int bx = hx[i] + dx[d], by = hy[i] + dy[d];\n                if(canBuild(bx, by)){\n                    out[i] = buildC[d];\n                } else {\n                    out[i] = '.';\n                }\n            } else {\n                out[i] = '.';\n            }\n        }\n        cout << out << \"\\n\" << flush;\n\n        // 2) Read pet movements and update positions\n        //    then rebuild petAt for the next turn.\n        vector<string> moves(N);\n        for(int i = 0; i < N; i++){\n            cin >> moves[i];\n        }\n        // clear\n        memset(petAt, 0, sizeof(petAt));\n        // apply moves\n        for(int i = 0; i < N; i++){\n            if(moves[i][0] != '.'){\n                for(char c: moves[i]){\n                    if(c == 'U')      ppx[i]--;\n                    else if(c == 'D') ppx[i]++;\n                    else if(c == 'L') ppy[i]--;\n                    else if(c == 'R') ppy[i]++;\n                }\n            }\n            // mark\n            int x = ppx[i], y = ppy[i];\n            if(0 <= x && x < 30 && 0 <= y && y < 30){\n                petAt[x][y] = true;\n            }\n        }\n    }\n\n    return 0;\n}","ahc009":"#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,ti,tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n\n    // read walls\n    vector<string> h(20), v(19);\n    for(int i=0;i<20;i++) cin >> h[i];\n    for(int i=0;i<19;i++) cin >> v[i];\n\n    // Precompute for each cell (i,j) the list of valid neighbor\u2010directions,\n    // sorted by manhattan distance to target ascending.\n    static vector<int> nbr[20][20];\n    int dx[4]={-1,1,0,0}, dy[4]={0,0,-1,1};\n    char dc[4]={'U','D','L','R'};\n    for(int i=0;i<20;i++){\n        for(int j=0;j<20;j++){\n            nbr[i][j].clear();\n            for(int d=0;d<4;d++){\n                int ni=i+dx[d], nj=j+dy[d];\n                bool ok=false;\n                if(d==0){ if(i>=1   && v[i-1][j]=='0') ok=true; }\n                if(d==1){ if(i<=18  && v[i][j]=='0')   ok=true; }\n                if(d==2){ if(j>=1   && h[i][j-1]=='0') ok=true; }\n                if(d==3){ if(j<=18  && h[i][j]=='0')   ok=true; }\n                if(ok){\n                    nbr[i][j].push_back(d);\n                }\n            }\n            // sort by manhattan distance of the neighbor to (ti,tj)\n            sort(nbr[i][j].begin(), nbr[i][j].end(),\n                 [&](int d1,int d2){\n                     int ni1=i+dx[d1], nj1=j+dy[d1];\n                     int ni2=i+dx[d2], nj2=j+dy[d2];\n                     int md1=abs(ni1-ti)+abs(nj1-tj);\n                     int md2=abs(ni2-ti)+abs(nj2-tj);\n                     return md1<md2;\n                 });\n        }\n    }\n\n    // BFS to find the shortest path in the union\u2010of\u2010trees graph\n    static int dist[20][20], pi_[20][20], pj_[20][20];\n    static char pm_[20][20];\n    const int INF = 1e9;\n    for(int i=0;i<20;i++)\n      for(int j=0;j<20;j++)\n        dist[i][j]=INF;\n\n    queue<pair<int,int>> q;\n    dist[si][sj]=0;\n    q.push({si,sj});\n    while(!q.empty()){\n        auto [i,j]=q.front(); q.pop();\n        if(i==ti && j==tj) break;\n        for(int d: nbr[i][j]){\n            int ni=i+dx[d], nj=j+dy[d];\n            if(dist[ni][nj] > dist[i][j]+1){\n                dist[ni][nj]=dist[i][j]+1;\n                pi_[ni][nj]=i; pj_[ni][nj]=j;\n                pm_[ni][nj]=dc[d];\n                q.push({ni,nj});\n            }\n        }\n    }\n\n    // Reconstruct the move sequence\n    vector<char> path;\n    if(dist[ti][tj]<INF){\n        int ci=ti, cj=tj;\n        while(!(ci==si && cj==sj)){\n            char c = pm_[ci][cj];\n            path.push_back(c);\n            int pi=pi_[ci][cj], pj=pj_[ci][cj];\n            ci=pi; cj=pj;\n        }\n        reverse(path.begin(), path.end());\n    }\n    int D = (int)path.size();\n    if(D==0){\n        // either already at office (rare) or no path\n        cout<<\"\\n\";\n        return 0;\n    }\n\n    // We will pick a uniform block\u2010size k, B = floor(200/k) full blocks,\n    // then distribute any rem = 200 - B*k extra instructions across\n    // the last rem blocks (1 each).\n    int k_cap = 200 / D;\n    if(k_cap < 1) k_cap = 1;\n    // precompute p^k\n    vector<double> ppow(k_cap+2, 1.0);\n    for(int i=1;i<=k_cap;i++) ppow[i] = ppow[i-1] * p;\n\n    // Negative\u2010Binomial enumeration to choose best k\n    double bestE = -1.0;\n    int best_k = 1, best_B = D;\n    for(int k=1;k<=k_cap;k++){\n        double pk = ppow[k];\n        double q  = 1.0 - pk;\n        int B = 200 / k;\n        if(B < D) continue;\n        // failures allowed in full\u2010block NB until the Dth success\n        int rmax = B - D;\n        // P_j = Prob exactly j failures before the Dth success (i.e. finish in block D+j)\n        // P_0 = q^D\n        double Pj = pow(q, D);\n        double E = Pj * (401.0 - k*(D+0));\n        for(int j=1;j<=rmax;j++){\n            // NB recurrence\n            Pj = Pj * ((D + j - 1.0)/ j) * (1.0 - q);\n            E += Pj * (401.0 - k*(D + j));\n        }\n        if(E > bestE){\n            bestE = E;\n            best_k = k;\n            best_B = B;\n        }\n    }\n\n    // Now build the actual instruction string of length exactly 200:\n    // give best_B blocks, each block = best_k or best_k+1 reps\n    // (we distribute rem = 200 - best_B*best_k across the last rem blocks)\n    int rem = 200 - best_B * best_k;\n    string out;\n    out.reserve(200);\n    for(int b=0;b<best_B;b++){\n        int blk = best_k + (b >= best_B - rem ? 1 : 0);\n        char c = path[b % D];\n        for(int t=0;t<blk;t++){\n            out.push_back(c);\n        }\n    }\n    // safety check (should be exactly 200)\n    if((int)out.size() > 200) out.resize(200);\n\n    cout << out << \"\\n\";\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Grid size\nstatic const int H = 30, W = 30;\n// Directions: 0=left,1=up,2=right,3=down\nint di[4] = {0,-1,0,1}, dj[4] = {-1,0,1,0};\ninline int opp(int d){ return (d+2)&3; }\n\n// to_dir[s][d]: if a train enters tile\u2010state s from side d,\n// returns exit side, or -1 if no rail.\nstatic const int to_dir[8][4] = {\n  { 1, 0,-1,-1},\n  { 3,-1,-1, 0},\n  {-1,-1, 3, 2},\n  {-1, 2, 1,-1},\n  { 1, 0, 3, 2},\n  { 3, 2, 1, 0},\n  { 2,-1, 0,-1},\n  {-1, 3,-1, 1}\n};\n\n// splitmix64 RNG\nstatic uint64_t rnd_state;\ninline uint64_t splitmix64(){\n  uint64_t z = (rnd_state += 0x9e3779b97f4a7c15ULL);\n  z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;\n  z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;\n  return z ^ (z >> 31);\n}\n// uniform [0,1)\ninline double rnd01(){\n  uint64_t r = splitmix64() >> 11; // top 53 bits\n  return r * (1.0/9007199254740992.0);\n}\n\n// Rotate original tile\u2010state s by r\u00d790\u00b0 CCW\ninline int rotateState(int s, int r){\n  if(s < 4)          return (s + r) & 3;  // single\u2010curve 0..3\n  else if(r & 1)     return s ^ 1;        // flips 4<->5 or 6<->7\n  else               return s;\n}\n\nint main(){\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n\n  // Seed RNG\n  rnd_state = chrono::steady_clock::now().time_since_epoch().count();\n\n  // Read input\n  static int orig[H][W];\n  for(int i = 0; i < H; i++){\n    string s; cin >> s;\n    for(int j = 0; j < W; j++){\n      orig[i][j] = s[j] - '0';\n    }\n  }\n\n  // Precompute open\u2010side masks\n  int openMask[8];\n  for(int s = 0; s < 8; s++){\n    int m = 0;\n    for(int d = 0; d < 4; d++){\n      if(to_dir[s][d] != -1) m |= 1<<d;\n    }\n    openMask[s] = m;\n  }\n\n  // Timing\n  auto now = chrono::steady_clock::now;\n  auto t0  = now();\n  const double TOTAL_TIME      = 1.90;\n  const double GREEDY_TIME     = 0.10;\n  const int    MAX_GREEDY_PASSES = 8;\n\n  // Rotation arrays\n  static int rot[H][W], bestLocalRot[H][W], bestCycleRot[H][W];\n\n  // Compute the \u201clocal\u2010match\u201d sum proxy\n  auto computeLocalSum = [&](){\n    int S = 0;\n    for(int i=0;i<H;i++) for(int j=0;j<W;j++){\n      int s = rotateState(orig[i][j], rot[i][j]);\n      int m = openMask[s];\n      for(int d=0;d<4;d++) if(m & (1<<d)){\n        int ni=i+di[d], nj=j+dj[d];\n        if(ni>=0&&ni<H&&nj>=0&&nj<W){\n          int s2 = rotateState(orig[ni][nj], rot[ni][nj]);\n          if(openMask[s2] & (1<<opp(d))) S++;\n        } else {\n          S--;\n        }\n      }\n    }\n    return S;\n  };\n\n  // Full cycle detection -> L1\u00d7L2\n  auto computeCycleScore = [&](){\n    static bool vis[H][W][4];\n    memset(vis, 0, sizeof(vis));\n    static int state[H][W];\n    for(int i=0;i<H;i++) for(int j=0;j<W;j++)\n      state[i][j] = rotateState(orig[i][j], rot[i][j]);\n\n    vector<int> loops;\n    loops.reserve(H*W);\n\n    for(int i=0;i<H;i++) for(int j=0;j<W;j++){\n      for(int d=0; d<4; d++){\n        if(vis[i][j][d]) continue;\n        // must have an entry rail\n        int st = state[i][j];\n        int d2 = to_dir[st][d];\n        if(d2<0) continue;\n        int ni=i+di[d], nj=j+dj[d];\n        if(ni<0||ni>=H||nj<0||nj>=W) continue;\n        // neighbor must accept\n        if(to_dir[state[ni][nj]][opp(d)]<0) continue;\n\n        // simulate\n        int si=i, sj=j, sd=d;\n        int ci=i, cj=j, cd=d, len=0;\n        while(true){\n          vis[ci][cj][cd] = true;\n          int scc = state[ci][cj];\n          int ex = to_dir[scc][cd];\n          if(ex<0) break;\n          int nni=ci+di[ex], nnj=cj+dj[ex];\n          if(nni<0||nni>=H||nnj<0||nnj>=W) break;\n          int nd = opp(ex);\n          ci=nni; cj=nnj; cd=nd; \n          len++;\n          if(ci==si && cj==sj && cd==sd){\n            loops.push_back(len);\n            break;\n          }\n        }\n      }\n    }\n    if(loops.size()<2) return 0;\n    nth_element(loops.begin(), loops.begin()+1, loops.end(), greater<int>());\n    return loops[0]*loops[1];\n  };\n\n  // Greedy edge\u2010matching sweep\n  auto greedy = [&](int passes){\n    for(int pass=0; pass<passes; pass++){\n      bool any=false;\n      for(int i=0;i<H;i++) for(int j=0;j<W;j++){\n        int curR = rot[i][j];\n        int bestR = curR, bestSc = INT_MIN;\n        for(int r=0;r<4;r++){\n          int s = rotateState(orig[i][j], r);\n          int m = openMask[s];\n          int sc=0;\n          for(int d=0;d<4;d++) if(m & (1<<d)){\n            int ni=i+di[d], nj=j+dj[d];\n            if(ni>=0&&ni<H&&nj>=0&&nj<W){\n              int s2 = rotateState(orig[ni][nj], rot[ni][nj]);\n              if(openMask[s2] & (1<<opp(d))) sc++;\n            } else sc--;\n          }\n          if(sc>bestSc){\n            bestSc=sc; bestR=r;\n          }\n        }\n        if(bestR!=curR){\n          rot[i][j]=bestR;\n          any=true;\n        }\n      }\n      if(!any) break;\n    }\n  };\n\n  // ========== 1) Multi\u2010start greedy ==========\n  int bestLocalSum = INT_MIN;\n  // start #0 = all zeros\n  for(int i=0;i<H;i++) for(int j=0;j<W;j++) rot[i][j]=0;\n  greedy(MAX_GREEDY_PASSES);\n  bestLocalSum = computeLocalSum();\n  for(int i=0;i<H;i++) for(int j=0;j<W;j++)\n    bestLocalRot[i][j] = rot[i][j];\n  // also init bestCycle from this\n  int bestCycleScore = computeCycleScore();\n  for(int i=0;i<H;i++) for(int j=0;j<W;j++)\n    bestCycleRot[i][j] = rot[i][j];\n\n  // random starts until GREEDY_TIME\n  int starts = 1;\n  while(starts<10 && chrono::duration<double>(now()-t0).count() < GREEDY_TIME){\n    for(int i=0;i<H;i++) for(int j=0;j<W;j++)\n      rot[i][j] = int(splitmix64() & 3);\n    greedy(MAX_GREEDY_PASSES);\n    int s = computeLocalSum();\n    if(s > bestLocalSum){\n      bestLocalSum = s;\n      for(int i=0;i<H;i++) for(int j=0;j<W;j++)\n        bestLocalRot[i][j] = rot[i][j];\n      int cs = computeCycleScore();\n      if(cs > bestCycleScore){\n        bestCycleScore = cs;\n        for(int i=0;i<H;i++) for(int j=0;j<W;j++)\n          bestCycleRot[i][j] = rot[i][j];\n      }\n    }\n    starts++;\n  }\n\n  // ========== 2) Simulated Annealing ==========  \n  // initialize from bestLocalRot\n  static int curMask[H][W];\n  for(int i=0;i<H;i++) for(int j=0;j<W;j++){\n    rot[i][j] = bestLocalRot[i][j];\n    curMask[i][j] = openMask[rotateState(orig[i][j], rot[i][j])];\n  }\n  int curSum = bestLocalSum;\n\n  // fixed\u2010temperature T and precompute exp\n  const double T = 1.5;\n  double accP[9];\n  for(int d=1; d<=8; d++) accP[d] = exp(-double(d)/T);\n\n  auto saEnd = t0 + chrono::duration<double>(TOTAL_TIME);\n  uint64_t iter = 0;\n\n  while(true){\n    if((iter & 511)==0 && now() > saEnd) break;\n    iter++;\n\n    // random tile & new rotation\n    int i = splitmix64() % H;\n    int j = splitmix64() % W;\n    int oldR = rot[i][j];\n    int newR = (oldR + 1 + int(splitmix64()%3)) & 3;\n    if(newR == oldR) continue;\n\n    int oldM = curMask[i][j];\n    int newM = openMask[rotateState(orig[i][j], newR)];\n\n    // delta in sum\n    int delta = 0;\n    for(int d=0; d<4; d++){\n      int oH = (oldM>>d)&1, nH = (newM>>d)&1;\n      int ni=i+di[d], nj=j+dj[d];\n      if(ni>=0&&ni<H&&nj>=0&&nj<W){\n        int neighH = (curMask[ni][nj]>>opp(d))&1;\n        if(neighH) delta += 2*(nH - oH);\n      } else {\n        delta += (oH - nH);\n      }\n    }\n\n    if(delta >= 0 || rnd01() < accP[-delta]){\n      // accept\n      rot[i][j]     = newR;\n      curMask[i][j] = newM;\n      curSum += delta;\n\n      // if we beat our local\u2010sum best, update and also try a cycle check\n      if(curSum > bestLocalSum){\n        bestLocalSum = curSum;\n        for(int x=0;x<H;x++) for(int y=0;y<W;y++)\n          bestLocalRot[x][y] = rot[x][y];\n        int cs = computeCycleScore();\n        if(cs > bestCycleScore){\n          bestCycleScore = cs;\n          for(int x=0;x<H;x++) for(int y=0;y<W;y++)\n            bestCycleRot[x][y] = rot[x][y];\n        }\n      }\n    }\n\n    // periodic true\u2010score scan\n    if((iter & ((1<<14)-1)) == 0){\n      int cs = computeCycleScore();\n      if(cs > bestCycleScore){\n        bestCycleScore = cs;\n        for(int x=0;x<H;x++) for(int y=0;y<W;y++)\n          bestCycleRot[x][y] = rot[x][y];\n      }\n    }\n  }\n\n  // ========== Output the best\u2010by\u2010true\u2010score layout ==========\n  string out;\n  out.reserve(H*W);\n  for(int i=0;i<H;i++){\n    for(int j=0;j<W;j++){\n      out.push_back(char('0' + bestCycleRot[i][j]));\n    }\n  }\n  cout << out << \"\\n\";\n  return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// Union-Find with cycle detection\nstruct UF {\n    vector<int> p, sz;\n    vector<bool> cyc;\n    UF(int n): p(n), sz(n,1), cyc(n,false){\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x){\n        return p[x]==x ? x : p[x]=find(p[x]);\n    }\n    void unite(int a, int b){\n        int ra = find(a), rb = find(b);\n        if(ra==rb){\n            cyc[ra] = true;\n        } else {\n            if(sz[ra]<sz[rb]) swap(ra,rb);\n            p[rb] = ra;\n            sz[ra] += sz[rb];\n            cyc[ra] = cyc[ra] | cyc[rb];\n        }\n    }\n};\n\n// Compute the size of the largest tree (acyclic connected component)\n// in the graph implied by the current grid G of size N\u00d7N.\nint compute_best_tree(int N, const vector<int>& G){\n    int NN = N*N;\n    UF uf(NN);\n    auto idx = [&](int i,int j){ return i*N + j; };\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            int v = G[idx(i,j)];\n            if(v==0) continue;  // empty\n            // down\u2013up edge?\n            if(i+1<N){\n                int v2 = G[idx(i+1,j)];\n                if((v & 8) && (v2 & 2)){\n                    uf.unite(idx(i,j), idx(i+1,j));\n                }\n            }\n            // right\u2013left edge?\n            if(j+1<N){\n                int v2 = G[idx(i,j+1)];\n                if((v & 4) && (v2 & 1)){\n                    uf.unite(idx(i,j), idx(i,j+1));\n                }\n            }\n        }\n    }\n    // collect component sizes & cycle flags\n    vector<int> csz(NN,0);\n    vector<bool> ccyc(NN,false);\n    for(int x=0;x<NN;x++){\n        int r = uf.find(x);\n        csz[r] = uf.sz[r];\n        ccyc[r] = uf.cyc[r];\n    }\n    // find empty index\n    int empty_idx = -1;\n    for(int x=0;x<NN;x++){\n        if(G[x]==0){ empty_idx = x; break; }\n    }\n    // pick the best acyclic comp (excluding the empty cell itself)\n    int best = 0;\n    for(int r=0;r<NN;r++){\n        if(r==empty_idx) continue;\n        if(uf.find(r)==r && !ccyc[r]){\n            best = max(best, csz[r]);\n        }\n    }\n    return best;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    cin >> N >> T;\n    vector<int> G(N*N);\n    int ex=-1, ey=-1;\n    for(int i=0;i<N;i++){\n        string s; cin >> s;\n        for(int j=0;j<N;j++){\n            char c = s[j];\n            int v = (c<='9' ? c-'0' : c-'a'+10);\n            G[i*N+j] = v;\n            if(v==0){\n                ex = i; \n                ey = j;\n            }\n        }\n    }\n\n    // Correct direction mapping:\n    // 'U' slides the tile above into empty \u21d2 empty moves up \u21d2 dx=-1,dy=0\n    // 'D' slides the tile below into empty \u21d2 empty moves down \u21d2 dx=+1,dy=0\n    // 'L' slides the tile left  into empty \u21d2 empty moves left \u21d2 dx=0, dy=-1\n    // 'R' slides the tile right into empty \u21d2 empty moves right\u21d2 dx=0, dy=+1\n    static const int dx[4] = {-1, +1,  0,  0};\n    static const int dy[4] = { 0,  0, -1, +1};\n    static const char dc[4] = {'U','D','L','R'};\n    static const int rev[4] = {1,0,3,2};\n\n    // initial score\n    int curS  = compute_best_tree(N, G);\n    int bestS = curS;\n\n    string curMoves, bestMoves;\n    curMoves.reserve(T);\n    bestMoves.reserve(T);\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    auto T0 = chrono::steady_clock::now();\n    const double NEG_PROB = 0.05;  // 5% chance to accept a downhill\n    int last_dir = -1;\n    int accepted = 0;\n\n    // keep proposing moves until we use up T or hit time\n    for(int iter=0; accepted < T; iter++){\n        if((iter & 127)==0){\n            auto now = chrono::steady_clock::now();\n            double ms = chrono::duration<double,milli>(now - T0).count();\n            if(ms > 2900.0) break;\n        }\n        // collect all legal candidate directions\n        int cand[4], nc=0;\n        for(int d=0;d<4;d++){\n            if(last_dir>=0 && d==rev[last_dir]) continue;\n            int nx = ex + dx[d], ny = ey + dy[d];\n            if(nx<0||nx>=N||ny<0||ny>=N) continue;\n            cand[nc++] = d;\n        }\n        if(nc==0) continue;  // should be very rare\n        int d = cand[rng()%nc];\n\n        // simulate\n        int epos = ex*N + ey;\n        int tpos = (ex+dx[d])*N + (ey+dy[d]);\n        swap(G[epos], G[tpos]);\n        int newS = compute_best_tree(N, G);\n\n        int delta = newS - curS;\n        bool accept = false;\n        if(delta >= 0){\n            accept = true;\n        } else if ((rng()%1000) < int(NEG_PROB*1000)){\n            accept = true;\n        }\n\n        if(accept){\n            // commit\n            ex += dx[d];\n            ey += dy[d];\n            curS = newS;\n            curMoves.push_back(dc[d]);\n            last_dir = d;\n            accepted++;\n\n            // record global best\n            if(curS > bestS){\n                bestS = curS;\n                bestMoves = curMoves;\n                if(bestS == N*N - 1) break;  // full tree!\n            }\n        } else {\n            // undo\n            swap(G[epos], G[tpos]);\n        }\n    }\n\n    // output the best sequence we ever saw\n    cout << bestMoves << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstatic const int OFF = 10000;\nstatic const int MAX_CAND = 200;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, K;\n    cin >> N >> K;\n    vector<int> a(11);\n    for(int d = 1; d <= 10; d++){\n        cin >> a[d];\n    }\n    vector<pair<int,int>> P(N);\n    vector<bool> xmark(2*OFF+1,false), ymark(2*OFF+1,false);\n    vector<int> xs(N), ys(N);\n    for(int i = 0; i < N; i++){\n        int x,y;\n        cin >> x >> y;\n        P[i] = {x,y};\n        xs[i] = x;  ys[i] = y;\n        if(-OFF <= x && x <= OFF) xmark[x+OFF] = true;\n        if(-OFF <= y && y <= OFF) ymark[y+OFF] = true;\n    }\n    sort(xs.begin(), xs.end());\n    sort(ys.begin(), ys.end());\n\n    // 1) approximate Poisson\u2010grid scoring for all (v,h)\n    struct Cand { double sc; int v,h; };\n    vector<Cand> approx;\n    approx.reserve(K*K/2);\n    for(int v = 1; v < K; v++){\n        int hmax = K - v;\n        for(int h = 1; h <= hmax; h++){\n            // #cells = (v+1)*(h+1), lambda = N / cells\n            int M = (v+1)*(h+1);\n            double lambda = double(N)/double(M);\n            double p0 = exp(-lambda);\n            double pd = p0;\n            double sc = 0;\n            for(int d = 1; d <= 10; d++){\n                pd = pd * lambda / double(d);       // P(d)\n                double bd = pd * double(M);         // approx #cells with d\n                sc += min(double(a[d]), bd);\n            }\n            approx.push_back({sc,v,h});\n        }\n    }\n    // pick top MAX_CAND by approx score\n    if((int)approx.size() > MAX_CAND){\n        nth_element(\n            approx.begin(),\n            approx.begin() + MAX_CAND,\n            approx.end(),\n            [](auto &L, auto &R){ return L.sc > R.sc; }\n        );\n        approx.resize(MAX_CAND);\n    }\n    sort(approx.begin(), approx.end(),\n         [](auto &L, auto &R){ return L.sc > R.sc; }\n    );\n\n    // 2) precompute quantile\u2010based cuts for all v,h\n    vector<vector<int>> qvx(K+1), qvy(K+1);\n    // helper to find an integer x not in mark[]\n    auto find_safe = [&](int tgt, vector<bool> &mark)->int{\n        for(int d=0; d<=2*OFF; d++){\n            int c1 = tgt - d;\n            if(c1>=-OFF && c1<=OFF && !mark[c1+OFF]) return c1;\n            int c2 = tgt + d;\n            if(c2>=-OFF && c2<=OFF && !mark[c2+OFF]) return c2;\n        }\n        // fallback\n        return tgt;\n    };\n    // quantile X\n    for(int v = 1; v <= K; v++){\n        if(v+1 > N) continue;\n        auto &out = qvx[v];\n        out.reserve(v);\n        for(int j = 1; j <= v; j++){\n            int idx = (j * N) / (v+1);\n            // boundary between xs[idx-1] and xs[idx]\n            int low = xs[idx-1], high = xs[idx];\n            int tgt = (low + high)/2;\n            out.push_back(find_safe(tgt, xmark));\n        }\n        sort(out.begin(), out.end());\n    }\n    // quantile Y\n    for(int h = 1; h <= K; h++){\n        if(h+1 > N) continue;\n        auto &out = qvy[h];\n        out.reserve(h);\n        for(int j = 1; j <= h; j++){\n            int idx = (j * N) / (h+1);\n            int low = ys[idx-1], high = ys[idx];\n            int tgt = (low + high)/2;\n            out.push_back(find_safe(tgt, ymark));\n        }\n        sort(out.begin(), out.end());\n    }\n\n    // 3) evaluate actual b_d for top candidates under both strategies\n    ll best_sum = -1;\n    int best_v=1, best_h=1;\n    bool useQuant = false;\n    vector<int> best_vx, best_vy;\n\n    // helper: compute b_d for given cuts\n    auto eval_grid = [&](int v, int h,\n                         const vector<int> &vx,\n                         const vector<int> &vy)\n                         -> ll\n    {\n        int cols = v+1, rows = h+1;\n        int M = cols * rows;\n        static vector<int> cnt;\n        cnt.assign(M,0);\n        // tally strawberries\n        for(auto &p: P){\n            int x = p.first, y = p.second;\n            int c = int(std::lower_bound(vx.begin(), vx.end(), x) - vx.begin());\n            int r = int(std::lower_bound(vy.begin(), vy.end(), y) - vy.begin());\n            cnt[r*cols + c]++;\n        }\n        // compute b_d\n        ll sum = 0;\n        static int bd[11];\n        fill(bd, bd+11, 0);\n        for(int i=0;i<M;i++){\n            int c = cnt[i];\n            if(1<=c && c<=10) bd[c]++;\n        }\n        for(int d=1; d<=10; d++){\n            sum += min<ll>(a[d], bd[d]);\n        }\n        return sum;\n    };\n\n    // uniform\u2010spacing helper\n    auto pick_uniform = [&](int steps, vector<bool> &mark)->vector<int>{\n        // want steps-1 cuts\n        vector<int> out;\n        out.reserve(steps-1);\n        for(int j=1; j<steps; j++){\n            double raw = -double(OFF) + (2.0*OFF * j)/double(steps);\n            int tgt = int(round(raw));\n            out.push_back(find_safe(tgt, mark));\n        }\n        sort(out.begin(), out.end());\n        return out;\n    };\n\n    for(auto &c: approx){\n        int v = c.v, h = c.h;\n        // skip impossible quantile if v+1>N\n        // 3a) uniform\n        {\n            auto vx = pick_uniform(v+1, xmark);\n            auto vy = pick_uniform(h+1, ymark);\n            ll s = eval_grid(v,h,vx,vy);\n            if(s > best_sum){\n                best_sum = s;\n                best_v = v; best_h = h;\n                useQuant = false;\n                best_vx = move(vx);\n                best_vy = move(vy);\n            }\n        }\n        // 3b) quantile (only if precomputed)\n        if(!qvx[v].empty() && !qvy[h].empty()){\n            ll s = eval_grid(v,h, qvx[v], qvy[h]);\n            if(s > best_sum){\n                best_sum = s;\n                best_v = v; best_h = h;\n                useQuant = true;\n                best_vx = qvx[v];\n                best_vy = qvy[h];\n            }\n        }\n    }\n\n    // 4) output\n    int k = int(best_vx.size() + best_vy.size());\n    if(k > K) k = K;\n    cout << k << \"\\n\";\n    // vertical\n    for(int i = 0; i < (int)best_vx.size() && i < k; i++){\n        ll c = best_vx[i];\n        cout << c << \" \" << -2*OFF << \" \" << c << \" \" << 2*OFF << \"\\n\";\n    }\n    // horizontal\n    int rem = k - int(best_vx.size());\n    for(int i = 0; i < rem; i++){\n        ll c = best_vy[i];\n        cout << -2*OFF << \" \" << c << \" \" << 2*OFF << \" \" << c << \"\\n\";\n    }\n\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\n// A single operation: we place a new dot at (x1,y1), using existing dots\n// at (x2,y2),(x3,y3),(x4,y4) in that cyclic order.\nstruct Op { \n    int x1,y1, x2,y2, x3,y3, x4,y4; \n};\n\nint N, M;\nstatic bool dotp[65][65];\nstatic bool used_h[65][65], used_v[65][65];\n// Precompute the weight of each grid point\nstatic long long wgt[65][65];\n\n// Check whether the rectangle p1->p2->p3->p4 is a valid axis-aligned\n// rectangle: no other dots on its perimeter and no previously used edges.\nbool validate_rect(int x1,int y1,int x2,int y2,int x3,int y3,int x4,int y4){\n    // We assume (p1,p2,p3,p4) go around the rectangle in order.\n    int xs[4] = {x1,x2,x3,x4}, ys[4] = {y1,y2,y3,y4};\n    for(int i=0;i<4;i++){\n        int j=(i+1)&3;\n        int sx=xs[i], sy=ys[i], ex=xs[j], ey=ys[j];\n        if(sx==ex){\n            // vertical side\n            int x = sx;\n            int y0 = min(sy,ey), y1 = max(sy,ey);\n            // no used edge\n            for(int y=y0; y<y1; y++){\n                if(used_v[y][x]) return false;\n            }\n            // no other dots on interior points\n            for(int y=y0+1; y<y1; y++){\n                if(dotp[x][y]) return false;\n            }\n        } else if(sy==ey){\n            // horizontal side\n            int y = sy;\n            int x0 = min(sx,ex), x1 = max(sx,ex);\n            for(int x=x0; x<x1; x++){\n                if(used_h[y][x]) return false;\n            }\n            for(int x=x0+1; x<x1; x++){\n                if(dotp[x][y]) return false;\n            }\n        } else {\n            // not axis-aligned\n            return false;\n        }\n    }\n    return true;\n}\n\n// After we choose a rectangle, mark its 4 sides' unit-edges as used.\nvoid mark_rect(int x1,int y1,int x2,int y2,int x3,int y3,int x4,int y4){\n    int xs[4] = {x1,x2,x3,x4}, ys[4] = {y1,y2,y3,y4};\n    for(int i=0;i<4;i++){\n        int j=(i+1)&3;\n        int sx=xs[i], sy=ys[i], ex=xs[j], ey=ys[j];\n        if(sx==ex){\n            int x=sx, y0=min(sy,ey), y1=max(sy,ey);\n            for(int y=y0; y<y1; y++){\n                used_v[y][x] = true;\n            }\n        } else {\n            int y=sy, x0=min(sx,ex), x1=max(sx,ex);\n            for(int x=x0; x<x1; x++){\n                used_h[y][x] = true;\n            }\n        }\n    }\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M;\n    vector<pair<int,int>> E;\n    E.reserve(N*N);\n\n    for(int i=0;i<M;i++){\n        int x,y; cin >> x >> y;\n        dotp[x][y] = true;\n        E.emplace_back(x,y);\n    }\n\n    // center coordinate\n    int C = (N-1)/2;\n    // precompute weights\n    for(int x=0;x<N;x++){\n        for(int y=0;y<N;y++){\n            long long dx = x - C, dy = y - C;\n            wgt[x][y] = dx*dx + dy*dy + 1;\n        }\n    }\n\n    // Random engine\n    mt19937_64 rng(1234567);\n\n    // record operations\n    vector<Op> ops;\n    ops.reserve(N*N);\n\n    // time\u2010limit guard\n    clock_t start = clock();\n    const double TL = 4.8;  // leave a small margin\n\n    while(true){\n        double used = double(clock() - start)/CLOCKS_PER_SEC;\n        if(used > TL) break;\n        int Esz = (int)E.size();\n        if(Esz < 2) break;\n\n        // sample up to T random diagonals per iteration\n        int T = min(1000, Esz*2);\n        long long bestW = -1;\n        Op    bestOp{};\n\n        for(int t=0;t<T; t++){\n            if((t & 511)==0 && double(clock() - start)/CLOCKS_PER_SEC > TL)\n                break;\n\n            int i = rng() % Esz;\n            int j = rng() % Esz;\n            if(i==j) continue;\n            auto [x2,y2] = E[i];\n            auto [x4,y4] = E[j];\n            // must form a proper diagonal\n            if(x2==x4 || y2==y4) continue;\n\n            // option 1: missing corner p1 = (x4,y2), opposite p3=(x2,y4)\n            int x1 = x4, y1 = y2;\n            int x3 = x2, y3 = y4;\n            if(!dotp[x1][y1] && dotp[x3][y3]){\n                if(validate_rect(x1,y1, x2,y2, x3,y3, x4,y4)){\n                    long long W = wgt[x1][y1];\n                    if(W > bestW){\n                        bestW = W;\n                        bestOp = {x1,y1, x2,y2, x3,y3, x4,y4};\n                    }\n                }\n            }\n            // option 2: missing corner p1 = (x2,y4), opposite p3=(x4,y2)\n            int x1b = x2, y1b = y4;\n            int x3b = x4, y3b = y2;\n            if(!dotp[x1b][y1b] && dotp[x3b][y3b]){\n                if(validate_rect(x1b,y1b, x2,y2, x3b,y3b, x4,y4)){\n                    long long W = wgt[x1b][y1b];\n                    if(W > bestW){\n                        bestW = W;\n                        bestOp = {x1b,y1b, x2,y2, x3b,y3b, x4,y4};\n                    }\n                }\n            }\n        }\n\n        // if we found a valid rectangle, commit it\n        if(bestW >= 0){\n            auto &o = bestOp;\n            dotp[o.x1][o.y1] = true;\n            E.emplace_back(o.x1,o.y1);\n            mark_rect(o.x1,o.y1, o.x2,o.y2, o.x3,o.y3, o.x4,o.y4);\n            ops.push_back(o);\n        } else {\n            // no more valid sample\u2192stop\n            break;\n        }\n    }\n\n    // Output\n    cout << ops.size() << \"\\n\";\n    for(auto &o: ops){\n        cout\n          << o.x1 << \" \" << o.y1 << \" \"\n          << o.x2 << \" \" << o.y2 << \" \"\n          << o.x3 << \" \" << o.y3 << \" \"\n          << o.x4 << \" \" << o.y4 << \"\\n\";\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n// simulate one tilt on a 10\u00d710 grid\n// dir = 'F','B','L','R'\nstatic void tilt(const int in[10][10], int out[10][10], char dir){\n    // temp buffer for one line\n    int buf[10];\n    if(dir=='F'){\n        // push everything to i=0\n        for(int j=0;j<10;j++){\n            int m=0;\n            for(int i=0;i<10;i++) if(in[i][j]) buf[m++] = in[i][j];\n            for(int i=0;i<10;i++){\n                out[i][j] = (i<m ? buf[i] : 0);\n            }\n        }\n    } else if(dir=='B'){\n        // push everything to i=9\n        for(int j=0;j<10;j++){\n            int m=0;\n            for(int i=9;i>=0;i--) if(in[i][j]) buf[m++] = in[i][j];\n            for(int i=9, k=0;i>=0;i--,k++){\n                out[i][j] = (k<m ? buf[k] : 0);\n            }\n        }\n    } else if(dir=='L'){\n        // push everything to j=0\n        for(int i=0;i<10;i++){\n            int m=0;\n            for(int j=0;j<10;j++) if(in[i][j]) buf[m++] = in[i][j];\n            for(int j=0;j<10;j++){\n                out[i][j] = (j<m ? buf[j] : 0);\n            }\n        }\n    } else { // 'R'\n        // push everything to j=9\n        for(int i=0;i<10;i++){\n            int m=0;\n            for(int j=9;j>=0;j--) if(in[i][j]) buf[m++] = in[i][j];\n            for(int j=9,k=0;j>=0;j--,k++){\n                out[i][j] = (k<m ? buf[k] : 0);\n            }\n        }\n    }\n}\n\n// compute sum of (component size)^2 on a 10\u00d710 grid\nstatic int calcScore(const int g[10][10]){\n    bool vis[10][10]={0};\n    int qx[100], qy[100];\n    int total = 0;\n    static const int di[4]={-1,1,0,0}, dj[4]={0,0,-1,1};\n    for(int i=0;i<10;i++) for(int j=0;j<10;j++){\n        if(g[i][j] && !vis[i][j]){\n            int f = g[i][j];\n            int head=0, tail=0;\n            vis[i][j]=true;\n            qx[tail]=i; qy[tail]=j; tail++;\n            while(head<tail){\n                int x=qx[head], y=qy[head]; head++;\n                for(int d=0;d<4;d++){\n                    int ni=x+di[d], nj=y+dj[d];\n                    if(ni>=0&&ni<10&&nj>=0&&nj<10\n                       && !vis[ni][nj] && g[ni][nj]==f){\n                        vis[ni][nj]=true;\n                        qx[tail]=ni; qy[tail]=nj; tail++;\n                    }\n                }\n            }\n            total += tail*tail;\n        }\n    }\n    return total;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // read in the 100 flavors\n    int F[101];\n    for(int i=1;i<=100;i++){\n        cin >> F[i];\n    }\n\n    // the board, 0=empty, 1/2/3=flavor\n    int grid[10][10]={0};\n\n    // our \u201cdefault\u201d mapping so we only break it if there's a real gain\n    char defdir[4] = {0,'L','R','F',};\n\n    for(int t=1;t<=100;t++){\n        int p; \n        if(!(cin>>p)) break;\n        // locate the p-th empty cell in row-major (front-to-back, left-to-right)\n        int cnt=0, si=0, sj=0;\n        for(int i=0;i<10;i++){\n            for(int j=0;j<10;j++){\n                if(grid[i][j]==0){\n                    cnt++;\n                    if(cnt==p){\n                        si=i; sj=j;\n                        goto FOUND;\n                    }\n                }\n            }\n        }\n    FOUND:\n        grid[si][sj] = F[t];\n\n        // build candidate list: default first, then the other 3\n        char cand[4];\n        cand[0] = defdir[F[t]];\n        int m=1;\n        for(char c: {'F','B','L','R'}){\n            if(c!=cand[0]) cand[m++]=c;\n        }\n\n        // greedy pick\n        int bestScore = -1;\n        char bestDir = cand[0];\n        int tmp[10][10];\n        for(int k=0;k<4;k++){\n            char d = cand[k];\n            tilt(grid, tmp, d);\n            int sc = calcScore(tmp);\n            if(sc > bestScore){\n                bestScore = sc;\n                bestDir = d;\n            }\n        }\n\n        // apply bestDir to our real grid\n        tilt(grid, tmp, bestDir);\n        for(int i=0;i<10;i++)\n            for(int j=0;j<10;j++)\n                grid[i][j] = tmp[i][j];\n\n        // output & flush\n        cout << bestDir << '\\n' << flush;\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    // 1) pick minimal N so that L = N*(N-1)/2 >= M-1\n    int N = 4;\n    int L = N*(N-1)/2;\n    while(L < M-1){\n        ++N;\n        L = N*(N-1)/2;\n    }\n    cout << N << \"\\n\";\n\n    // 2) precompute the lex\u2010order edge list edges[b] = (i,j)\n    vector<pair<int,int>> edges;\n    edges.reserve(L);\n    for(int i=0;i<N;i++){\n        for(int j=i+1;j<N;j++){\n            edges.emplace_back(i,j);\n        }\n    }\n\n    // 3) emit G_k as first k edges = '1', rest '0'\n    //    also build degG[k] = sorted degree\u2010vector of G_k\n    vector<vector<int>> degG(M, vector<int>(N, 0));\n    for(int k=0;k<M;k++){\n        // output bitstring\n        int ones = min(k, L);\n        cout << string(ones, '1') << string(L - ones, '0') << \"\\n\";\n        // build degree vector incrementally\n        if(k>0){\n            degG[k] = degG[k-1];\n            if(k-1 < L){\n                auto [u,v] = edges[k-1];\n                degG[k][u]++;\n                degG[k][v]++;\n            }\n        }\n        // for k=0 already zeroed\n    }\n    cout << flush;\n\n    // sort each prototype's degree\u2010vector\n    for(int k=0;k<M;k++){\n        sort(degG[k].begin(), degG[k].end());\n    }\n\n    // 4) answer 100 queries\n    const int W = 3;  // window around raw estimate\n    for(int qi=0; qi<100; qi++){\n        string H;\n        cin >> H;\n        if(!cin) break;\n        // count 1's and build H's degree\u2010vector\n        int cnt = 0;\n        vector<int> degH(N, 0);\n        for(int b=0;b<L;b++){\n            if(H[b]=='1'){\n                ++cnt;\n                auto [u,v] = edges[b];\n                degH[u]++;\n                degH[v]++;\n            }\n        }\n        // sort H's degrees\n        sort(degH.begin(), degH.end());\n\n        // 4a) raw linear inverse\n        double denom = 1.0 - 2.0*eps;\n        double kd = eps*L;\n        double x;\n        if(fabs(denom) < 1e-9){\n            x = cnt; // fallback (shouldn't happen for eps<=0.4)\n        } else {\n            x = double(cnt - kd) / denom;\n        }\n        int k0 = int(round(x));\n        k0 = max(0, min(M-1, k0));\n\n        // 4b) refine on [k0-W .. k0+W]\n        int lo = max(0, k0 - W), hi = min(M-1, k0 + W);\n        int bestK = k0;\n        long long bestCost = LLONG_MAX;\n        for(int k=lo; k<=hi; k++){\n            // L1 distance between degH and degG[k]\n            long long c = 0;\n            for(int i=0;i<N;i++){\n                c += abs(degH[i] - degG[k][i]);\n            }\n            // prefer smaller cost, tie\u2010break by closeness to k0\n            if(c < bestCost || (c==bestCost && abs(k - k0) < abs(bestK - k0))){\n                bestCost = c;\n                bestK = k;\n            }\n        }\n\n        cout << bestK << \"\\n\" << flush;\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll INFLL = (ll)4e18;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, D, K;\n    cin >> N >> M >> D >> K;\n    vector<int> U(M), V(M);\n    vector<ll> 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    // discard coords\n    for(int i = 0; i < N; i++){\n        int x,y; cin >> x >> y;\n    }\n\n    // build incidence lists & degrees\n    vector<vector<int>> inc(N);\n    vector<int> deg(N,0);\n    inc.reserve(N);\n    for(int e = 0; e < M; e++){\n        inc[U[e]].push_back(e);\n        inc[V[e]].push_back(e);\n        deg[U[e]]++;\n        deg[V[e]]++;\n    }\n\n    // --- 1) choose B sources for weighted\u2010Brandes ---\n    int B = min(N, 200);\n    vector<int> vid(N);\n    iota(vid.begin(), vid.end(), 0);\n    // pick top B/2 by degree\n    nth_element(vid.begin(), vid.begin()+B/2, vid.end(),\n                [&](int a,int b){ return deg[a] > deg[b]; });\n    vector<int> srcs;\n    srcs.reserve(B);\n    for(int i = 0; i < B/2; i++){\n        srcs.push_back(vid[i]);\n    }\n    // plus B/2 random\n    mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());\n    shuffle(vid.begin(), vid.end(), rng);\n    for(int i = 0; (int)srcs.size() < B; i++){\n        srcs.push_back(vid[i]);\n    }\n\n    // --- 2) approximate edge\u00ad-betweenness (Brandes) ---\n    vector<double> central(M, 0.0);\n    vector<ll> dist(N);\n    vector<double> sigma(N), delta(N);\n    vector<vector<pair<int,int>>> pred(N);\n    vector<int> S; S.reserve(N);\n\n    for(int s : srcs){\n        // init\n        fill(dist.begin(), dist.end(), INFLL);\n        fill(sigma.begin(), sigma.end(), 0.0);\n        for(auto &v : pred) v.clear();\n        dist[s] = 0;\n        sigma[s] = 1.0;\n        S.clear();\n\n        // Dijkstra\n        using pli = pair<ll,int>;\n        priority_queue<pli, vector<pli>, greater<pli>> pq;\n        pq.push({0,s});\n        while(!pq.empty()){\n            auto [d,u] = pq.top(); pq.pop();\n            if(d != dist[u]) continue;\n            S.push_back(u);\n            for(int e : inc[u]){\n                int v = U[e]^V[e]^u;\n                ll nd = d + W[e];\n                if(nd < dist[v]){\n                    dist[v] = nd;\n                    sigma[v] = sigma[u];\n                    pred[v].clear();\n                    pred[v].push_back({u,e});\n                    pq.push({nd,v});\n                } else if(nd == dist[v]){\n                    sigma[v] += sigma[u];\n                    pred[v].push_back({u,e});\n                }\n            }\n        }\n        // accumulate\n        fill(delta.begin(), delta.end(), 0.0);\n        for(int i = (int)S.size()-1; i >= 0; i--){\n            int w = S[i];\n            for(auto &pe : pred[w]){\n                int v = pe.first, e = pe.second;\n                double c = (sigma[v]/sigma[w])*(1.0 + delta[w]);\n                delta[v] += c;\n                central[e] += c;\n            }\n        }\n    }\n\n    // --- 3) compute weighted scores and sort edges desc ---\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    vector<double> wscore(M);\n    for(int e = 0; e < M; e++){\n        wscore[e] = central[e] * (double)W[e];\n    }\n    sort(order.begin(), order.end(),\n         [&](int a, int b){\n             return wscore[a] > wscore[b];\n         });\n\n    // --- 4) LPT\u2010style packing with capacity K and conflict\u2010avoidance ---\n    vector<double> daysum(D+1, 0.0);\n    vector<int> daycnt(D+1, 0);\n    vector<int> ans(M, 0);\n\n    for(int idx = 0; idx < M; idx++){\n        int e = order[idx];\n        int bestDay = -1;\n        double bestSum = numeric_limits<double>::infinity();\n\n        // 4a) try days with capacity and no conflict\n        for(int d = 1; d <= D; d++){\n            if(daycnt[d] >= K) continue;\n            // check endpoint conflicts\n            bool conflict = false;\n            for(int f : inc[U[e]]){\n                if(ans[f] == d){ conflict = true; break; }\n            }\n            if(conflict) continue;\n            for(int f : inc[V[e]]){\n                if(ans[f] == d){ conflict = true; break; }\n            }\n            if(conflict) continue;\n            // candidate\n            if(daysum[d] < bestSum){\n                bestSum = daysum[d];\n                bestDay = d;\n            }\n        }\n        // 4b) if none found, just use the least\u2010loaded day with capacity\n        if(bestDay < 0){\n            for(int d = 1; d <= D; d++){\n                if(daycnt[d] >= K) continue;\n                if(daysum[d] < bestSum){\n                    bestSum = daysum[d];\n                    bestDay = d;\n                }\n            }\n        }\n\n        // assign\n        ans[e]    = bestDay;\n        daysum[bestDay] += wscore[e];\n        daycnt[bestDay]++;\n    }\n\n    // --- 5) output ---\n    for(int i = 0; i < M; i++){\n        cout << ans[i] << (i+1 < M ? ' ' : '\\n');\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\n    int D;\n    cin >> D;\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for(int i = 0; i < D; i++) cin >> f1[i];\n    for(int i = 0; i < D; i++) cin >> r1[i];\n    for(int i = 0; i < D; i++) cin >> f2[i];\n    for(int i = 0; i < D; i++) cin >> r2[i];\n\n    int N = D*D*D;\n    auto idx = [&](int x,int y,int z){ return x*D*D + y*D + z; };\n\n    // build minimal\u2010cover shapes\n    vector<char> need1(N,0), need2(N,0);\n\n    auto build_min_shape = [&](const vector<string>& F, const vector<string>& R, vector<char>& need){\n        // for each z\u2010slice, solve the bipartite min\u2010edge\u2010cover on Sx\u00d7Sy\n        for(int z = 0; z < D; z++){\n            vector<int> Sx, Sy;\n            Sx.reserve(D); Sy.reserve(D);\n            for(int x = 0; x < D; x++) if(F[z][x]=='1') Sx.push_back(x);\n            for(int y = 0; y < D; y++) if(R[z][y]=='1') Sy.push_back(y);\n            int a = Sx.size(), b = Sy.size();\n            if(a==0 || b==0) continue;  // by problem guarantee this won't happen\n            \n            int m = min(a,b);\n            // 1) matching edges Sx[i]\u2013Sy[i] for i<m\n            for(int i = 0; i < m; i++){\n                int x = Sx[i], y = Sy[i];\n                need[idx(x,y,z)] = 1;\n            }\n            // 2) cover the leftover vertices\n            if(a > b){\n                // some x are unmatched, cover them by pairing to Sy[0]\n                int y0 = Sy[0];\n                for(int i = b; i < a; i++){\n                    int x = Sx[i];\n                    need[idx(x,y0,z)] = 1;\n                }\n            } else if(b > a){\n                // some y unmatched, cover by pairing to Sx[0]\n                int x0 = Sx[0];\n                for(int i = a; i < b; i++){\n                    int y = Sy[i];\n                    need[idx(x0,y,z)] = 1;\n                }\n            }\n        }\n    };\n\n    build_min_shape(f1, r1, need1);\n    build_min_shape(f2, r2, need2);\n\n    // We'll extract the intersection voxels, BFS to get 6\u2010connected components,\n    // and assign each component one common block.\n    vector<int> b1(N,0), b2(N,0);\n    vector<char> vis(N,0);\n    int block_id = 0;\n    static const int dx[6]={1,-1,0,0,0,0},\n                     dy[6]={0,0,1,-1,0,0},\n                     dz[6]={0,0,0,0,1,-1};\n\n    // 1) find CCs in intersection\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          int i = idx(x,y,z);\n          if(!vis[i] && need1[i] && need2[i]){\n            // BFS this component\n            queue<array<int,3>> q;\n            q.push({x,y,z});\n            vis[i]=1;\n            vector<int> comp;\n            comp.reserve(64);\n\n            while(!q.empty()){\n              auto c = q.front(); q.pop();\n              int cx=c[0], cy=c[1], cz=c[2];\n              int ci = idx(cx,cy,cz);\n              comp.push_back(ci);\n              for(int d=0;d<6;d++){\n                int nx=cx+dx[d], ny=cy+dy[d], nz=cz+dz[d];\n                if(nx<0||nx>=D||ny<0||ny>=D||nz<0||nz>=D) continue;\n                int ni = idx(nx,ny,nz);\n                if(!vis[ni] && need1[ni] && need2[ni]){\n                  vis[ni]=1;\n                  q.push({nx,ny,nz});\n                }\n              }\n            }\n            // assign one block to the entire component\n            ++block_id;\n            for(int vi: comp){\n              b1[vi] = block_id;\n              b2[vi] = block_id;\n            }\n          }\n        }\n      }\n    }\n\n    // 2) leftover voxels unique to silhouette1\n    for(int i=0;i<N;i++){\n      if(need1[i] && !need2[i]){\n        ++block_id;\n        b1[i] = block_id;\n      }\n    }\n    // 3) leftover voxels unique to silhouette2\n    for(int i=0;i<N;i++){\n      if(need2[i] && !need1[i]){\n        ++block_id;\n        b2[i] = block_id;\n      }\n    }\n\n    // output\n    cout << block_id << \"\\n\";\n    for(int i=0;i<N;i++){\n      cout << b1[i] << (i+1==N?'\\n':' ');\n    }\n    for(int i=0;i<N;i++){\n      cout << b2[i] << (i+1==N?'\\n':' ');\n    }\n\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll INF = (1LL<<60);\n\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n): p(n), r(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 SteinerInfo {\n    vector<int> sourceList;              // terminal station IDs\n    vector<pair<int,int>> steinerPairs;  // edges in the MST of the metric closure\n    vector<ll> steinerW;                 // their weights\n    vector<int> B;                        // length M: which original edges are ON\n    ll cableCost;\n};\n\nint N, M;\nvector<vector<pair<int,pair<ll,int>>>> g;  // g[u] = list of (v, (w, edge_id))\n\n// Given terminals (by station\u2010ID), compute the 2\u2010approx Steiner\u2010tree\nSteinerInfo buildSteiner(const vector<int>& terminals){\n    int T = (int)terminals.size();\n    // 1) all\u2010pairs shortest paths from each terminal\n    vector<vector<ll>> distFrom(T, vector<ll>(N, INF));\n    vector<vector<int>> parentEdge(T, vector<int>(N,-1)), parentNode(T, vector<int>(N,-1));\n    for(int si=0; si<T; si++){\n        int src = terminals[si];\n        auto &dist = distFrom[si];\n        dist[src]=0;\n        priority_queue<pair<ll,int>,vector<pair<ll,int>>,greater<>> pq;\n        pq.push({0,src});\n        while(!pq.empty()){\n            auto [cd,u]=pq.top(); pq.pop();\n            if(cd>dist[u]) continue;\n            for(auto &ed: g[u]){\n                int v=ed.first, id=ed.second.second;\n                ll w=ed.second.first;\n                if(dist[v]>cd+w){\n                    dist[v]=cd+w;\n                    parentEdge[si][v]=id;\n                    parentNode[si][v]=u;\n                    pq.push({dist[v],v});\n                }\n            }\n        }\n    }\n    // 2) complete graph on T terminals\n    struct E{ ll w; int i,j; };\n    vector<E> Kedges;\n    Kedges.reserve(T*(T-1)/2);\n    for(int i=0;i<T;i++){\n        for(int j=i+1;j<T;j++){\n            ll d = distFrom[i][ terminals[j] ];\n            Kedges.push_back({d,i,j});\n        }\n    }\n    sort(Kedges.begin(), Kedges.end(),\n         [](auto &A, auto &B){ return A.w<B.w; });\n    // 3) Kruskal\u2010MST on those T\n    DSU dsu(T);\n    vector<pair<int,int>> steinerPairs;\n    vector<ll> steinerW;\n    steinerPairs.reserve(T-1);\n    steinerW.reserve(T-1);\n    ll cableCost=0;\n    for(auto &e: Kedges){\n        if(dsu.unite(e.i,e.j)){\n            steinerPairs.emplace_back(e.i,e.j);\n            steinerW.push_back(e.w);\n            cableCost += e.w;\n            if((int)steinerPairs.size()==T-1) break;\n        }\n    }\n    // 4) reconstruct original\u2010graph edges\n    vector<int> B(M,0);\n    for(int k=0;k<(int)steinerPairs.size();k++){\n        int si=steinerPairs[k].first,\n            sj=steinerPairs[k].second;\n        int u=terminals[si], v=terminals[sj];\n        int cur=v;\n        while(cur!=u){\n            int eid = parentEdge[si][cur];\n            B[eid]=1;\n            cur = parentNode[si][cur];\n        }\n    }\n    return {terminals, steinerPairs, steinerW, B, cableCost};\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int K;\n    cin>>N>>M>>K;\n    vector<ll> x(N), y(N);\n    for(int i=0;i<N;i++) cin>>x[i]>>y[i];\n    g.assign(N,{});\n    for(int j=0;j<M;j++){\n        int u,v; ll w;\n        cin>>u>>v>>w;\n        --u; --v;\n        g[u].push_back({v,{w,j}});\n        g[v].push_back({u,{w,j}});\n    }\n    vector<ll> a(K), b(K);\n    for(int i=0;i<K;i++) cin>>a[i]>>b[i];\n\n    // Initial \u201cnearest\u2010station\u201d assignment\n    vector<vector<int>> assignedLists(N);\n    for(int r=0;r<K;r++){\n        ll best=LLONG_MAX; int bi=0;\n        for(int i=0;i<N;i++){\n            ll dx=x[i]-a[r], dy=y[i]-b[r];\n            ll d2=dx*dx+dy*dy;\n            if(d2<best){ best=d2; bi=i; }\n        }\n        assignedLists[bi].push_back(r);\n    }\n\n    vector<int> bestP(N), bestB(M);\n    ll bestCost = INF;\n\n    const int MAX_ITERS = 20;\n    const int CUTOFF    = 2;   // now try dropping stations serving \u22642 residents\n\n    for(int iter=0; iter<MAX_ITERS; iter++){\n        // 1) recompute P[i]\n        vector<ll> max_d2(N,0);\n        for(int i=0;i<N;i++){\n            for(int r: assignedLists[i]){\n                ll dx=x[i]-a[r], dy=y[i]-b[r];\n                max_d2[i]=max(max_d2[i], dx*dx+dy*dy);\n            }\n        }\n        vector<int> P(N,0);\n        for(int i=0;i<N;i++){\n            if(max_d2[i]){\n                ll d2=max_d2[i];\n                ll s=(ll)floor(sqrt((long double)d2));\n                while(s*s<d2) s++;\n                while(s>0 && (s-1)*(s-1)>=d2) s--;\n                P[i]=(int)s;\n            }\n        }\n        // 2) build terminal list\n        vector<int> terminals;\n        terminals.push_back(0);\n        for(int i=1;i<N;i++) if(P[i]>0) terminals.push_back(i);\n        if(terminals.size()<=1) break;\n\n        // 3) build Steiner\u2010tree\n        auto info = buildSteiner(terminals);\n\n        // 4) evaluate cost\n        ll cableCost=info.cableCost;\n        ll bc=0; for(int i=0;i<N;i++) bc += (ll)P[i]*P[i];\n        ll total = cableCost + bc;\n        if(total<bestCost){\n            bestCost=total;\n            bestP=P;\n            bestB=info.B;\n        }\n\n        // 5) index of each terminal\n        int T = (int)terminals.size();\n        vector<int> termIdx(N,-1);\n        for(int si=0;si<T;si++) termIdx[terminals[si]]=si;\n\n        // 6) find best single\u2010drop move among stations with \u2264CUTOFF residents\n        ll bestDelta=0; \n        int bestI=-1;\n        for(int i=1;i<N;i++){\n            int cnt=(int)assignedLists[i].size();\n            if(cnt==0 || cnt>CUTOFF) continue;\n            int si = termIdx[i];\n            if(si<0) continue; // not a terminal\n            // cable saving = sum of MST\u2010edge\u2010weights incident to si\n            ll cableSaving=0;\n            for(int k=0;k<(int)info.steinerPairs.size();k++){\n                auto &pp=info.steinerPairs[k];\n                if(pp.first==si||pp.second==si)\n                    cableSaving += info.steinerW[k];\n            }\n            // broadcast increase: reassign each resident r\u2192best other station\n            unordered_map<int,ll> newDem;\n            newDem.reserve(cnt);\n            for(int r: assignedLists[i]){\n                ll bd=LLONG_MAX; int bj=-1;\n                for(int j=0;j<N;j++){\n                    if(j==i) continue;\n                    ll dx=x[j]-a[r], dy=y[j]-b[r], d2=dx*dx+dy*dy;\n                    if(d2<bd){ bd=d2; bj=j; }\n                }\n                newDem[bj] = max(newDem[bj], bd);\n            }\n            ll deltaB=0;\n            for(auto &pr: newDem){\n                int j=pr.first; ll nd2=pr.second;\n                ll od2 = max_d2[j];\n                ll md2 = max(od2, nd2);\n                ll oldP=(ll)P[j];\n                ll s=(ll)floor(sqrt((long double)md2));\n                while(s*s<md2) s++;\n                while(s>0&&(s-1)*(s-1)>=md2) s--;\n                ll newP=s;\n                deltaB += (newP*newP - oldP*oldP);\n            }\n            ll delta = cableSaving + (ll)P[i]*P[i] - deltaB;\n            if(delta>bestDelta){\n                bestDelta=delta;\n                bestI=i;\n            }\n        }\n\n        // 7) if no profitable drop, stop\n        if(bestI<0) break;\n\n        // 8) apply the drop\n        int dropI = bestI;\n        auto residents = assignedLists[dropI];\n        assignedLists[dropI].clear();\n        for(int r: residents){\n            ll bd=LLONG_MAX; int bj=0;\n            for(int j=0;j<N;j++){\n                if(j==dropI) continue;\n                ll dx=x[j]-a[r], dy=y[j]-b[r], d2=dx*dx+dy*dy;\n                if(d2<bd){ bd=d2; bj=j; }\n            }\n            assignedLists[bj].push_back(r);\n        }\n        // next iter will rebuild everything\n    }\n\n    // final output\n    for(int i=0;i<N;i++){\n        cout<<bestP[i]<<(i+1<N?' ':'\\n');\n    }\n    for(int j=0;j<M;j++){\n        cout<<bestB[j]<<(j+1<M?' ':'\\n');\n    }\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nstatic const int N = 30;\nstatic const int M = N*(N+1)/2;  // 465\n\nstruct Move { int x1,y1,x2,y2; };\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // 1) Read the initial permutation\n    vector<int> posBall(M), curPos(M);\n    for(int x=0, idx=0; x<N; x++){\n        for(int y=0; y<=x; y++, idx++){\n            int b; \n            cin >> b;\n            posBall[idx] = b;\n            curPos[b] = idx;\n        }\n    }\n\n    // 2) id <-> (x,y) mappings\n    static int id2x[M], id2y[M];\n    auto xy2id = [&](int x,int y){ return x*(x+1)/2 + y; };\n    for(int x=0, idx=0; x<N; x++){\n        for(int y=0; y<=x; y++, idx++){\n            id2x[idx]=x;\n            id2y[idx]=y;\n        }\n    }\n\n    // 3) Build the 6\u2010neighbor adjacency on the triangular grid\n    static vector<int> adj[M];\n    for(int u=0; u<M; u++){\n        auto X = id2x[u], Y = id2y[u];\n        adj[u].clear();\n        if(X>0 && Y>0)      adj[u].push_back(xy2id(X-1,Y-1));\n        if(X>0 && Y<=X-1)   adj[u].push_back(xy2id(X-1,Y));\n        if(Y>0)             adj[u].push_back(xy2id(X  ,Y-1));\n        if(Y< X)            adj[u].push_back(xy2id(X  ,Y+1));\n        if(X+1< N){\n            adj[u].push_back(xy2id(X+1,Y));\n            adj[u].push_back(xy2id(X+1,Y+1));\n        }\n    }\n\n    // 4) Precompute all\u2010pairs shortest\u2010path distances distAll[u][v]\n    static int distAll[M][M];\n    static int Qtmp[M];\n    for(int s=0; s<M; s++){\n        auto dist = distAll[s];\n        // initialize\n        for(int i=0;i<M;i++) dist[i]=INT_MAX;\n        int qh=0, qt=0;\n        dist[s]=0;\n        Qtmp[qt++]=s;\n        while(qh<qt){\n            int u=Qtmp[qh++], du=dist[u];\n            for(int v: adj[u]){\n                if(dist[v] > du+1){\n                    dist[v]=du+1;\n                    Qtmp[qt++]=v;\n                }\n            }\n        }\n    }\n\n    // 5) We'll collect our swaps here\n    vector<Move> moves;\n    moves.reserve(M*8);\n\n    // 6) Prepare scratch space for the per\u2010ball BFS\n    static bool seen[M];\n    static int parentArr[M], Q[M], path[M];\n\n    // 7) Place balls in ascending label L=0..464\n    //    But skip L in the bottom row (no children, no E\u2010impact)\n    for(int L=0; L<M-N; L++){\n        int s = curPos[L], t = L;\n        if(s==t) continue;\n\n        // BFS on the subgraph { id>=L }, which is guaranteed connected\n        memset(seen, 0, sizeof(seen));\n        int qh=0, qt=0;\n        seen[s]=true;\n        parentArr[s]=-1;\n        Q[qt++]=s;\n\n        bool found=false;\n        while(qh<qt && !found){\n            int u = Q[qh++];\n            // gather up to 6 neighbors in a tiny array\n            int nbCnt=0;\n            static int nbV[6], nbD[6];\n            for(int v: adj[u]){\n                if(v < L) continue;      // locked prefix\n                if(seen[v]) continue;\n                seen[v]=true;\n                parentArr[v]=u;\n                // record for sorting\n                nbV[nbCnt] = v;\n                nbD[nbCnt] = distAll[v][t];\n                nbCnt++;\n            }\n            // insertion\u2010sort nbV[0..nbCnt) by nbD ascending\n            for(int i=1;i<nbCnt;i++){\n                int dv = nbD[i], vv=nbV[i], j=i;\n                while(j>0 && nbD[j-1] > dv){\n                    nbD[j]=nbD[j-1];\n                    nbV[j]=nbV[j-1];\n                    --j;\n                }\n                nbD[j]=dv; \n                nbV[j]=vv;\n            }\n            // enqueue in that \u201cbest\u2010first\u201d order\n            for(int i=0;i<nbCnt;i++){\n                int v=nbV[i];\n                Q[qt++]=v;\n                if(v==t){ found=true; break; }\n            }\n        }\n        // Reconstruct the path s -> \u2026 -> t\n        int plen=0;\n        for(int cur=t; cur!=-1; cur=parentArr[cur]){\n            path[plen++]=cur;\n        }\n        // path[] is in reverse (t\u2192\u2026\u2192s), so reverse it\n        for(int i=0;i<plen/2;i++){\n            swap(path[i], path[plen-1-i]);\n        }\n        // \u201cBubble\u201d L along that path\n        for(int i=1;i<plen;i++){\n            int u0=path[i-1], v0=path[i];\n            int A=posBall[u0], B=posBall[v0];\n            // swap in our model\n            posBall[u0]=B;  posBall[v0]=A;\n            curPos[A]=v0;   curPos[B]=u0;\n            // record the move\n            moves.push_back({\n                id2x[u0], id2y[u0],\n                id2x[v0], id2y[v0]\n            });\n        }\n    }\n\n    // 8) One final linear pass to strip out immediate \u201cundo\u201d swaps\n    vector<Move> clean;\n    clean.reserve(moves.size());\n    int K = (int)moves.size();\n    for(int i=0; i<K; i++){\n        if(i+1<K){\n            auto &a=moves[i], &b=moves[i+1];\n            bool same = (a.x1==b.x1 && a.y1==b.y1 && a.x2==b.x2 && a.y2==b.y2);\n            bool rev  = (a.x1==b.x2 && a.y1==b.y2 && a.x2==b.x1 && a.y2==b.y1);\n            if(same||rev){\n                i++; // skip both\n                continue;\n            }\n        }\n        clean.push_back(moves[i]);\n    }\n\n    // 9) Output\n    cout << clean.size() << \"\\n\";\n    for(auto &m: clean){\n        cout << m.x1 << \" \" << m.y1 << \" \"\n             << m.x2 << \" \" << m.y2 << \"\\n\";\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\n// We know D==9 always\nstatic const int MAXD = 9;\nstatic int D, N, C;\nstatic bool isObs[MAXD][MAXD];\nstatic int dist0[MAXD][MAXD], maxDist;\nstatic int occ[MAXD][MAXD], posT[MAXD][MAXD];\nstatic int ex, ey;\nstatic int dx[4] = {1,-1,0,0}, dy[4] = {0,0,1,-1};\n\n// For BFS\nstruct P { int x,y; };\nstatic P Q[MAXD*MAXD];\n\n// For AP\u2010finding\nstatic bool visitedAP[MAXD*MAXD], isAP[MAXD*MAXD];\nstatic int disc[MAXD*MAXD], low[MAXD*MAXD], parentAP[MAXD*MAXD], dfsTime;\n\nvoid dfs_art(int u){\n    visitedAP[u] = true;\n    disc[u] = low[u] = ++dfsTime;\n    int ux = u / D, uy = u % D;\n    int child = 0;\n    for(int k=0;k<4;k++){\n        int vx = ux + dx[k], vy = uy + dy[k];\n        if(vx<0||vx>=D||vy<0||vy>=D) continue;\n        if(occ[vx][vy]!=0) continue; // only traverse free squares\n        int v = vx*D + vy;\n        if(!visitedAP[v]){\n            parentAP[v] = u;\n            ++child;\n            dfs_art(v);\n            low[u] = min(low[u], low[v]);\n            // non\u2010root condition\n            if(parentAP[u]!=-1 && low[v]>=disc[u]){\n                isAP[u] = true;\n            }\n        } else if(v != parentAP[u]){\n            low[u] = min(low[u], disc[v]);\n        }\n    }\n    // root condition\n    if(parentAP[u]==-1 && child>1){\n        isAP[u] = true;\n    }\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> D >> N;\n    // entrance\n    ex = 0; \n    ey = (D-1)/2;\n    // obstacles\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        isObs[i][j] = false;\n    }\n    for(int i=0;i<N;i++){\n        int r,c; \n        cin >> r >> c;\n        isObs[r][c] = true;\n    }\n    // precompute static BFS\u2010distances from entrance\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        dist0[i][j] = -1;\n    }\n    int qs=0, qe=0;\n    dist0[ex][ey] = 0;\n    Q[qe++] = {ex,ey};\n    while(qs<qe){\n        auto [x,y] = Q[qs++];\n        for(int k=0;k<4;k++){\n            int nx=x+dx[k], ny=y+dy[k];\n            if(nx<0||nx>=D||ny<0||ny>=D) continue;\n            if(isObs[nx][ny]) continue;\n            if(dist0[nx][ny]!=-1) continue;\n            dist0[nx][ny] = dist0[x][y] + 1;\n            Q[qe++] = {nx,ny};\n        }\n    }\n    maxDist = 0;\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        if(!isObs[i][j] && !(i==ex && j==ey)){\n            maxDist = max(maxDist, dist0[i][j]);\n        }\n    }\n\n    C = D*D - 1 - N;  // total containers\n    // occ: -1=obstacle, 0=free, 1=occupied\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        occ[i][j]   = isObs[i][j] ? -1 : 0;\n        posT[i][j] = -1;\n    }\n\n    // --- Storing phase (interactive) ---\n    for(int step=0; step<C; step++){\n        int t; \n        cin >> t;\n\n        // 1) BFS to find currently reachable FREE squares\n        static bool vis[MAXD][MAXD];\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++) vis[i][j]=false;\n        qs=0; qe=0;\n        vis[ex][ey] = true;\n        Q[qe++] = {ex,ey};\n        while(qs<qe){\n            auto [x,y] = Q[qs++];\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(vis[nx][ny]) continue;\n                if(occ[nx][ny]!=0) continue;   // only walk on free\n                vis[nx][ny] = true;\n                Q[qe++] = {nx,ny};\n            }\n        }\n\n        // 2) find articulation points in *this* free\u2010graph\n        //    so we never break connectivity\n        int totalNodes = D*D;\n        for(int id=0; id<totalNodes; id++){\n            visitedAP[id] = false;\n            isAP[id]      = false;\n            parentAP[id] = -1;\n        }\n        dfsTime = 0;\n        int root = ex*D + ey;\n        dfs_art(root);\n        // (we trust the graph is still connected)\n\n        // 3) pick among non\u2010AP reachable free squares\n        double target = (C>1 ? (double)t/(C-1)*maxDist : 0.0);\n        double bestErr = 1e100;\n        int bestX=-1, bestY=-1, bestD0=-1;\n\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            if(i==ex && j==ey) continue;\n            if(!vis[i][j])       continue;  // not reachable\n            if(occ[i][j]!=0)     continue;  // not free\n            int id = i*D + j;\n            if(isAP[id])         continue;  // would disconnect!\n\n            int d0 = dist0[i][j];\n            double e = fabs(d0 - target);\n            if(e + 1e-9 < bestErr ||\n               (fabs(e - bestErr)<1e-9 && d0 < bestD0))\n            {\n                bestErr = e;\n                bestD0  = d0;\n                bestX   = i;\n                bestY   = j;\n            }\n        }\n        // Fallback (should never really be needed):\n        if(bestX<0){\n            for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n                if(i==ex && j==ey) continue;\n                if(!vis[i][j])       continue;\n                if(occ[i][j]!=0)     continue;\n                int d0 = dist0[i][j];\n                double e = fabs(d0 - target);\n                if(e + 1e-9 < bestErr ||\n                   (fabs(e - bestErr)<1e-9 && d0 < bestD0))\n                {\n                    bestErr = e;\n                    bestD0  = d0;\n                    bestX   = i;\n                    bestY   = j;\n                }\n            }\n        }\n        // commit\n        occ[bestX][bestY] = 1;\n        posT[bestX][bestY] = t;\n        // output + flush\n        cout << bestX << \" \" << bestY << \"\\n\" << flush;\n    }\n\n    // --- Retrieval phase (offline) ---\n    vector<pair<int,int>> ans;\n    ans.reserve(C);\n    for(int iter=0; iter<C; iter++){\n        // BFS over empty squares\n        static bool vis2[MAXD][MAXD];\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++) vis2[i][j]=false;\n        qs=0; qe=0;\n        vis2[ex][ey] = true;\n        Q[qe++] = {ex,ey};\n        while(qs<qe){\n            auto [x,y] = Q[qs++];\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(vis2[nx][ny]) continue;\n                if(occ[nx][ny]!=0) continue;\n                vis2[nx][ny] = true;\n                Q[qe++] = {nx,ny};\n            }\n        }\n        // among occupied neighbours pick smallest tag\n        int pickT = INT_MAX, px=-1, py=-1;\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            if(occ[i][j]!=1) continue;\n            bool reachable = false;\n            for(int k=0;k<4 && !reachable;k++){\n                int nx=i+dx[k], ny=j+dy[k];\n                if(nx>=0&&nx<D&&ny>=0&&ny<D && vis2[nx][ny]){\n                    reachable = true;\n                }\n            }\n            if(!reachable) continue;\n            int tt = posT[i][j];\n            if(tt < pickT){\n                pickT = tt;\n                px = i; py = j;\n            }\n        }\n        // remove it\n        occ[px][py] = 0;\n        ans.emplace_back(px,py);\n    }\n\n    // print all retrieval moves\n    for(auto &p: ans){\n        cout << p.first << \" \" << p.second << \"\\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    const int MAXN = 50, MAXM = 100;\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> c(n, vector<int>(n)), d(n, vector<int>(n));\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < n; j++){\n            cin >> c[i][j];\n            d[i][j] = c[i][j];\n        }\n    }\n\n    // Counts and adjacency trackers\n    vector<int> color_count(m+1, 0);\n    vector<vector<bool>> initial_adj(m+1, vector<bool>(m+1, false));\n    vector<bool> initial_adjOutside(m+1, false);\n    vector<vector<int>> adjCnt(m+1, vector<int>(m+1, 0));\n    vector<vector<int>> deg(n, vector<int>(n, 0));\n\n    int dx[4]={-1,1,0,0}, dy[4]={0,0,-1,1};\n\n    // 1) Build initial color counts & adjacency\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < n; j++){\n            int x = c[i][j];\n            color_count[x]++;\n            if(i==0||i==n-1||j==0||j==n-1){\n                initial_adjOutside[x] = true;\n            }\n            for(int k = 0; k < 4; k++){\n                int ni = i+dx[k], nj = j+dy[k];\n                if(ni<0||ni>=n||nj<0||nj>=n){\n                    adjCnt[x][0]++;\n                } else {\n                    int y = c[ni][nj];\n                    adjCnt[x][y]++;\n                    initial_adj[x][y] = true;\n                }\n            }\n        }\n    }\n\n    // 2) Degrees in the *current* map (starts identical to c[][])\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < n; j++){\n            int x = d[i][j], cnt = 0;\n            for(int k = 0; k < 4; k++){\n                int ni = i+dx[k], nj = j+dy[k];\n                if(ni>=0&&ni<n&&nj>=0&&nj<n && d[ni][nj]==x) cnt++;\n            }\n            deg[i][j] = cnt;\n        }\n    }\n\n    // 3) Can we safely turn (i,j) into 0?\n    auto is_removable = [&](int i,int j)->bool {\n        int x = d[i][j];\n        if(x==0) return false;\n        // never create new 0\u2013x if x never touched outside initially\n        if(!initial_adjOutside[x]) return false;\n        // keep at least one cell of x\n        if(color_count[x] <= 1) return false;\n        // must be a leaf\n        if(deg[i][j] > 1) return false;\n\n        bool touchZero = false;\n        int boundary_adj = 0;\n        vector<int> neighs;\n        vector<int> neighCount(m+1, 0);\n\n        // scan neighbors\n        for(int k = 0; k < 4; k++){\n            int ni = i+dx[k], nj = j+dy[k];\n            if(ni<0||ni>=n||nj<0||nj>=n){\n                touchZero = true;\n                boundary_adj++;\n            } else {\n                int y = d[ni][nj];\n                if(y==0){\n                    touchZero = true;\n                } else if(y!=x){\n                    if(neighCount[y]==0) neighs.push_back(y);\n                    neighCount[y]++;\n                }\n            }\n        }\n        if(!touchZero) return false;  // must stay connected into the zero\u2010region\n\n        // never create 0\u2013y for any neighbor y that didn't touch outside\n        for(int y:neighs){\n            if(!initial_adjOutside[y]) return false;\n        }\n        // preserve all needed x\u2013y adjacencies\n        for(int y:neighs){\n            if(initial_adj[x][y] && adjCnt[x][y] <= neighCount[y])\n                return false;\n        }\n        // preserve x\u2013outside adjacency\n        if(initial_adjOutside[x] && adjCnt[x][0] <= boundary_adj)\n            return false;\n\n        return true;\n    };\n\n    // 4) Peel off all removable leaves in BFS/queue order\n    vector<pair<int,int>> que;\n    que.reserve(n*n);\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < n; j++){\n            if(is_removable(i,j)) que.emplace_back(i,j);\n        }\n    }\n\n    for(size_t qi = 0; qi < que.size(); qi++){\n        auto [i,j] = que[qi];\n        int x = d[i][j];\n        if(x==0) continue;\n        if(!is_removable(i,j)) continue;\n        // remove it\n        d[i][j] = 0;\n        color_count[x]--;\n\n        // update adjCnt and degrees\n        for(int k = 0; k < 4; k++){\n            int ni = i+dx[k], nj = j+dy[k];\n            if(ni<0||ni>=n||nj<0||nj>=n){\n                adjCnt[x][0]--;\n            } else {\n                int y = d[ni][nj];\n                if(y==x){\n                    deg[ni][nj]--;\n                } else if(y!=0){\n                    adjCnt[x][y]--;\n                    adjCnt[y][x]--;\n                }\n            }\n        }\n        // neighbors might now become removable\n        for(int k = 0; k < 4; k++){\n            int ni = i+dx[k], nj = j+dy[k];\n            if(ni>=0&&ni<n&&nj>=0&&nj<n && d[ni][nj]!=0){\n                if(is_removable(ni,nj))\n                    que.emplace_back(ni,nj);\n            }\n        }\n    }\n\n    // 5) Output the final map\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < n; j++){\n            cout << d[i][j] << (j+1<n?' ':'\\n');\n        }\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, D, Q, usedQ;\nvector<int> comp_cache;\n\n// Always\u2010issue one balance query {i} vs {j}, read exactly one response.\nint raw_query(int i, int j){\n    cout << 1 << ' ' << 1 << ' ' << i << ' ' << j << '\\n' << flush;\n    char resp; \n    cin >> resp;\n    usedQ++;\n    return (resp=='>'? 1 : (resp=='<'? -1 : 0));\n}\n\n// A cached comparator: only calls raw_query on a cache\u2010miss.\nint compare_cached(int i, int j){\n    if(i==j) return 0;\n    int &c = comp_cache[i*N + j];\n    if(c != -2) return c;\n    int r = raw_query(i, j);\n    c = r;\n    comp_cache[j*N + i] = -r;\n    return r;\n}\n\n// Classic mergesort using compare_cached as the comparator.\nvector<int> interactive_mergesort(const vector<int>& A){\n    int n = A.size();\n    if(n <= 1) return A;\n    int m = n/2;\n    auto L = interactive_mergesort(vector<int>(A.begin(), A.begin()+m));\n    auto R = interactive_mergesort(vector<int>(A.begin()+m, A.end()));\n    vector<int> M; M.reserve(n);\n    int i=0, j=0;\n    while(i < (int)L.size() && j < (int)R.size()){\n        int v = compare_cached(L[i], R[j]);\n        if(v>0 || (v==0 && L[i]<R[j])) M.push_back(L[i++]);\n        else                           M.push_back(R[j++]);\n    }\n    while(i < (int)L.size())  M.push_back(L[i++]);\n    while(j < (int)R.size())  M.push_back(R[j++]);\n    return M;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> D >> Q;\n    comp_cache.assign(N*N, -2);\n    usedQ = 0;\n\n    // A tiny random jitter to break ties\n    mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());\n    vector<int> jitter(N);\n    for(int i=0;i<N;i++) jitter[i] = rng() % (N+1);\n\n    // How many queries we need to guarantee an N\u00b7ceil(log2 N) mergesort\n    int LG = 0; \n    while((1<<LG) < N) LG++;\n    long long needSortQ = 1LL * N * LG;\n\n    vector<long long> weight(N,0), bin_sum(D,0);\n    vector<int> final_assign(N,0);\n\n    if(Q >= needSortQ){\n        // \u2500\u2500\u2500 Full sort branch \u2500\u2500\u2500\n        vector<int> ids(N);\n        iota(ids.begin(), ids.end(), 0);\n        auto sorted = interactive_mergesort(ids);\n\n        // Burn any leftover queries so we issue exactly Q\n        while(usedQ < Q){\n            raw_query(0,1);\n        }\n\n        // Assign pseudo\u2010weights = (N\u2010rank)\u00b7(N+1)+jitter\n        for(int r=0;r<N;r++){\n            int id = sorted[r];\n            weight[id] = (long long)(N-r)*(N+1) + jitter[id];\n        }\n    }\n    else {\n        // \u2500\u2500\u2500 Fallback branch \u2500\u2500\u2500\n        // We must spend exactly Q raw queries, so we never call compare_cached here.\n        vector<int> wins(N, 0);\n        int base = Q / N, rem = Q % N;\n        for(int i = 0; i < N; i++){\n            int comps = base + (i < rem ? 1 : 0);\n            for(int k = 0; k < comps; k++){\n                // pick a random opponent j != i\n                int j = (i + 1 + (rng() % (N-1))) % N;\n                int res = raw_query(i, j);\n                if(res >= 0) wins[i]++;  // count \u2018=\u2019 as a half\u2010win\n            }\n        }\n        // Build pseudo\u2010weights = wins[i]\u00b7(N+1) + jitter[i]\n        for(int i = 0; i < N; i++){\n            weight[i] = (long long)wins[i]*(N+1) + jitter[i];\n        }\n    }\n\n    // \u2500\u2500\u2500 Greedy LPT on our pseudo\u2010weights \u2500\u2500\u2500\n    vector<int> order(N);\n    iota(order.begin(), order.end(), 0);\n    shuffle(order.begin(), order.end(), rng);\n    stable_sort(order.begin(), order.end(),\n        [&](int a,int b){ return weight[a] > weight[b]; });\n\n    for(int id: order){\n        int best = 0;\n        for(int b = 1; b < D; b++){\n            if(bin_sum[b] < bin_sum[best]) best = b;\n        }\n        final_assign[id] = best;\n        bin_sum[best] += weight[id];\n    }\n\n    // \u2500\u2500\u2500 Output final division \u2500\u2500\u2500\n    for(int i = 0; i < N; i++){\n        cout << final_assign[i] << (i+1==N?'\\n':' ');\n    }\n    cout << flush;\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int,int>;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int INF = 1000000;\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> st(m);\n    for(int i = 0; i < m; i++){\n        st[i].resize(n/m);\n        for(int j = 0; j < n/m; j++){\n            cin >> st[i][j];\n        }\n    }\n\n    // min_content[i] = minimum label currently in stack i (or INF if empty)\n    vector<int> min_content(m, INF);\n    for(int i = 0; i < m; i++){\n        if(!st[i].empty()){\n            int mn = INF;\n            for(int x: st[i]) mn = min(mn, x);\n            min_content[i] = mn;\n        }\n    }\n\n    vector<pii> ops;\n    ops.reserve(2*n);\n\n    // For each v=1..n we need to expose and remove it.\n    for(int v = 1; v <= n; v++){\n        // 1) find v in some stack s at depth j\n        int s = -1, j = -1;\n        for(int i = 0; i < m && s==-1; i++){\n            for(int k = 0; k < (int)st[i].size(); k++){\n                if(st[i][k] == v){\n                    s = i; j = k;\n                    break;\n                }\n            }\n        }\n        int sz = st[s].size();\n        int above = sz - (j+1);\n        // 2) if there are boxes above it, move that entire segment\n        if(above > 0){\n            // collect the segment and its minimum\n            vector<int> segment;\n            segment.reserve(above);\n            int segment_min = INF;\n            for(int p = j+1; p < sz; p++){\n                segment.push_back(st[s][p]);\n                segment_min = min(segment_min, st[s][p]);\n            }\n            // choose destination stack t != s\n            int best_t = -1;\n            // 2a) first try to find \"safe\" stacks whose min_content > segment_min\n            //     among those pick the one of minimal height\n            int best_h = INT_MAX;\n            for(int t = 0; t < m; t++){\n                if(t == s) continue;\n                if(min_content[t] > segment_min){\n                    int h = st[t].size();\n                    if(h < best_h){\n                        best_h = h;\n                        best_t = t;\n                    }\n                }\n            }\n            // 2b) if no safe stack found, pick t with maximal min_content[t],\n            //     tie\u2010break on minimal height\n            if(best_t == -1){\n                int best_min = -1;\n                best_h = INT_MAX;\n                for(int t = 0; t < m; t++){\n                    if(t == s) continue;\n                    int mc = min_content[t];\n                    if(mc > best_min || (mc == best_min && (int)st[t].size() < best_h)){\n                        best_min = mc;\n                        best_h = st[t].size();\n                        best_t = t;\n                    }\n                }\n            }\n            // perform the move: we must specify the box immediately above v\n            int w = st[s][j+1];\n            ops.emplace_back(w, best_t+1);\n            // physically move it in our simulation\n            st[s].resize(j+1);\n            min_content[s] = INF;\n            for(int x: st[s]) min_content[s] = min(min_content[s], x);\n            for(int x: segment){\n                st[best_t].push_back(x);\n                min_content[best_t] = min(min_content[best_t], x);\n            }\n        }\n        // 3) now v is at the top of stack s, carry it out\n        ops.emplace_back(v, 0);\n        st[s].pop_back();\n        // update min_content[s]\n        min_content[s] = INF;\n        for(int x: st[s]) min_content[s] = min(min_content[s], x);\n    }\n\n    // output all operations\n    for(auto &op: ops){\n        cout << op.first << \" \" << op.second << \"\\n\";\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\n// fast xorshift64 for randomness\nstatic uint64_t _xr = chrono::high_resolution_clock::now().time_since_epoch().count();\ninline uint64_t xor64() {\n    _xr ^= _xr << 13;\n    _xr ^= _xr >> 7;\n    _xr ^= _xr << 17;\n    return _xr;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<string> h(N-1), v(N);\n    for(int i=0;i<N-1;i++) cin >> h[i];\n    for(int i=0;i<N;i++)   cin >> v[i];\n\n    int V = N*N;\n    vector<int> dirt(V);\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            cin >> dirt[i*N+j];\n        }\n    }\n\n    auto id = [&](int i,int j){ return i*N + j; };\n\n    // Build adjacency with move\u2010labels\n    vector<vector<pair<int,char>>> nbr(V);\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            int u = id(i,j);\n            if(i+1<N && h[i][j]=='0'){\n                int w = id(i+1,j);\n                nbr[u].emplace_back(w,'D');\n                nbr[w].emplace_back(u,'U');\n            }\n            if(j+1<N && v[i][j]=='0'){\n                int w = id(i,j+1);\n                nbr[u].emplace_back(w,'R');\n                nbr[w].emplace_back(u,'L');\n            }\n        }\n    }\n\n    // All\u2010pairs BFS: dist[src*V + x] = distance, fm[...] = first move from src toward x\n    vector<int16_t> dist(V*V);\n    vector<char>   fm  (V*V);\n    deque<int>    q;\n    for(int src=0;src<V;src++){\n        int base = src*V;\n        // mark unvisited\n        for(int i=0;i<V;i++) dist[base+i] = -1;\n        dist[base+src] = 0;\n        q.clear();\n        // seed neighbors\n        for(auto &pc: nbr[src]){\n            int to = pc.first;\n            dist[base+to] = 1;\n            fm  [base+to] = pc.second;\n            q.push_back(to);\n        }\n        // BFS\n        while(!q.empty()){\n            int u = q.front(); q.pop_front();\n            int du = dist[base+u];\n            for(auto &pc: nbr[u]){\n                int to = pc.first;\n                if(dist[base+to]==-1){\n                    dist[base+to] = du+1;\n                    fm  [base+to] = fm[base+u];\n                    q.push_back(to);\n                }\n            }\n        }\n    }\n    auto dptr = dist.data();\n\n    // Helper: build a greedy tour, mode=0 pure NN, mode=1 jittered among topK\n    auto build_tour = [&](int mode){\n        const int K = 3;               // pick randomly among top K\n        vector<char> used(V,0);\n        vector<int>  ord; ord.reserve(V);\n        int cur = 0;\n        used[cur]=1; ord.push_back(cur);\n        vector<pair<double,int>> best; best.reserve(K);\n        for(int step=1;step<V;step++){\n            int bbase = cur*V;\n            int choice = -1;\n            if(mode==0){\n                // pure max dirt/dist\n                double bs=-1;\n                for(int j=0;j<V;j++){\n                    if(used[j]) continue;\n                    double sc = double(dirt[j]) / double(dptr[bbase+j]);\n                    if(sc>bs){ bs=sc; choice=j; }\n                }\n            } else {\n                // jitter: maintain top K by sc\n                best.clear();\n                for(int j=0;j<V;j++){\n                    if(used[j]) continue;\n                    double sc = double(dirt[j]) / double(dptr[bbase+j]);\n                    if((int)best.size()<K){\n                        best.emplace_back(sc,j);\n                        if(best.size()==K) sort(best.begin(),best.end());\n                    } else if(sc>best[0].first){\n                        best[0]={sc,j};\n                        // bubble up the new entry\n                        for(int t=0;t+1<K;t++){\n                            if(best[t].first>best[t+1].first) swap(best[t],best[t+1]);\n                            else break;\n                        }\n                    }\n                }\n                // pick random among best[0..sz-1]\n                int sz = (int)best.size();\n                int idx = xor64()%sz;\n                choice = best[idx].second;\n            }\n            used[choice]=1;\n            ord.push_back(choice);\n            cur = choice;\n        }\n        return ord;\n    };\n\n    // build two tours and pick the shorter (by sum of BFS-distances)\n    auto sum_dist = [&](const vector<int>& ord){\n        long long s=0;\n        for(int i=0;i+1<V;i++){\n            int u=ord[i], w=ord[i+1];\n            s += dptr[u*V + w];\n        }\n        s += dptr[ord[V-1]*V + 0];\n        return s;\n    };\n\n    auto tour0 = build_tour(0);\n    auto tour1 = build_tour(1);\n    long long s0 = sum_dist(tour0), s1 = sum_dist(tour1);\n    vector<int> order = (s1<s0 ? tour1 : tour0);\n\n    // aggressive random 2-opt with early-exit\n    int n = V;\n    int fail=0, fail_limit = n*5;\n    int budget = n*200;\n    for(int it=0; it<budget && fail<fail_limit; it++){\n        int i = int(xor64()%(n-2)) + 1;\n        int j = int(xor64()%(n-i-1)) + i + 1;\n        int a=order[i-1], b=order[i], c=order[j], d2=(j+1<n?order[j+1]:order[0]);\n        int oldc = dptr[a*V+b] + dptr[c*V + d2];\n        int newc = dptr[a*V+c] + dptr[b*V + d2];\n        if(newc < oldc){\n            reverse(order.begin()+i, order.begin()+j+1);\n            fail = 0;\n        } else {\n            fail++;\n        }\n    }\n\n    // Build the final move\u2010string\n    string ans;\n    ans.reserve(n*(N/2));\n    auto apply_path = [&](int u, int v){\n        int cu=u;\n        while(cu!=v){\n            char mv = fm[cu*V + v];\n            ans.push_back(mv);\n            int ii=cu/N, jj=cu%N;\n            if(mv=='U')     ii--;\n            else if(mv=='D')ii++;\n            else if(mv=='L')jj--;\n            else            jj++;\n            cu = id(ii,jj);\n        }\n    };\n    for(int i=0;i+1<n;i++){\n        apply_path(order[i], order[i+1]);\n    }\n    apply_path(order[n-1], 0);\n\n    // Fallback to DFS-Euler if we somehow got longer than 2*(V-1)\n    int dfsLen = 2*(V-1);\n    if((int)ans.size() > dfsLen){\n        vector<vector<bool>> vis(N, vector<bool>(N,false));\n        string ans2; ans2.reserve(dfsLen);\n        static int di[4]={0,1,0,-1}, dj[4]={1,0,-1,0};\n        static char dc[4]={'R','D','L','U'};\n        function<void(int,int)> dfs = [&](int i,int j){\n            vis[i][j]=true;\n            for(int dir=0;dir<4;dir++){\n                int ni=i+di[dir], nj=j+dj[dir];\n                if(ni<0||ni>=N||nj<0||nj>=N) continue;\n                if(vis[ni][nj]) continue;\n                if(dir==0 && v[i][j]!='0') continue;\n                if(dir==1 && h[i][j]!='0') continue;\n                if(dir==2 && v[i][nj]!='0') continue;\n                if(dir==3 && h[ni][j]!='0') continue;\n                ans2.push_back(dc[dir]);\n                dfs(ni,nj);\n                ans2.push_back(dc[dir^2]);\n            }\n        };\n        dfs(0,0);\n        cout << ans2 << \"\\n\";\n    } else {\n        cout << ans << \"\\n\";\n    }\n\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int,int>;\nstatic const int INF = 1e9;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    cin >> N >> M;\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<string> A(N);\n    for(int i = 0; i < N; i++){\n        cin >> A[i];\n    }\n    vector<string> t(M);\n    for(int k = 0; k < M; k++){\n        cin >> t[k];\n    }\n\n    // Precompute positions of each letter\n    vector<vector<pii>> pos(26);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            pos[A[i][j] - 'A'].emplace_back(i, j);\n        }\n    }\n\n    vector<bool> used(M, false);\n    vector<pii> moves;\n    moves.reserve(5000);\n\n    int cur_i = si, cur_j = sj;\n    string lastS;    // keep up to the last 4 typed chars\n\n    // Temporary arrays for the small DP on rem letters\n    static int dp1[225], dp2[225];\n    // For reconstruction when we actually commit to the best word\n    static int parentArr[5][225];\n    int occSz[5];\n\n    // Greedy loop: pick one word at a time\n    for(int done = 0; done < M; done++){\n        int bestK = -1;\n        int bestCost = INF;\n        int bestOv = -1;\n\n        // Scan all unused words\n        for(int k = 0; k < M; k++){\n            if(used[k]) continue;\n            const string &w = t[k];\n            // Compute overlap with lastS (up to 4)\n            int maxOv = min((int)lastS.size(), 4);\n            int ov = 0;\n            for(int o = maxOv; o >= 1; o--){\n                bool ok = true;\n                for(int x = 0; x < o; x++){\n                    if(lastS[lastS.size()-o + x] != w[x]){\n                        ok = false;\n                        break;\n                    }\n                }\n                if(ok){\n                    ov = o;\n                    break;\n                }\n            }\n            int rem = 5 - ov;\n            int travel = 0;\n            if(rem > 0){\n                // DP over the rem letters w[ov..4], only Manhattan distances\n                // Stage 0: distance from (cur_i,cur_j) to each pos of w[ov]\n                int c0 = w[ov] - 'A';\n                int sz0 = pos[c0].size();\n                for(int j = 0; j < sz0; j++){\n                    dp1[j] = abs(cur_i - pos[c0][j].first)\n                           + abs(cur_j - pos[c0][j].second);\n                }\n                int prevSz = sz0;\n                // Stages 1..rem-1\n                for(int s2 = 1; s2 < rem; s2++){\n                    int cprev = w[ov + s2 - 1] - 'A';\n                    int ccur  = w[ov + s2]     - 'A';\n                    int szc   = pos[ccur].size();\n                    // init\n                    for(int j = 0; j < szc; j++) dp2[j] = INF;\n                    // relax\n                    for(int u = 0; u < prevSz; u++){\n                        auto &p0 = pos[cprev][u];\n                        int base = dp1[u];\n                        for(int v = 0; v < szc; v++){\n                            auto &p1 = pos[ccur][v];\n                            int cand = base\n                                     + abs(p0.first  - p1.first)\n                                     + abs(p0.second - p1.second);\n                            if(cand < dp2[v]) dp2[v] = cand;\n                        }\n                    }\n                    // swap in\n                    for(int j = 0; j < szc; j++) dp1[j] = dp2[j];\n                    prevSz = szc;\n                }\n                // take minimum\n                travel = INF;\n                for(int j = 0; j < prevSz; j++){\n                    travel = min(travel, dp1[j]);\n                }\n            }\n            int cost = travel + rem;  // +1 per keystroke for each of rem letters\n            // Tie-break on *larger* overlap\n            if(cost < bestCost || (cost == bestCost && ov > bestOv)){\n                bestCost = cost;\n                bestK = k;\n                bestOv = ov;\n            }\n        }\n\n        // Commit to bestK\n        used[bestK] = true;\n        const string &w = t[bestK];\n        // Recompute overlap\n        int maxOv = min((int)lastS.size(), 4);\n        int ov = 0;\n        for(int o = maxOv; o >= 1; o--){\n            bool ok = true;\n            for(int x = 0; x < o; x++){\n                if(lastS[lastS.size()-o + x] != w[x]){\n                    ok = false; break;\n                }\n            }\n            if(ok){ ov = o; break; }\n        }\n        int rem = 5 - ov;\n        if(rem > 0){\n            // We now do the DP *with* back\u2010pointers to recover the exact path\n            // Stage sizes\n            for(int s2 = 0; s2 < rem; s2++){\n                occSz[s2] = pos[w[ov + s2] - 'A'].size();\n            }\n            // Stage 0\n            {\n                int c0 = w[ov] - 'A';\n                for(int j = 0; j < occSz[0]; j++){\n                    auto &p0 = pos[c0][j];\n                    dp1[j] = abs(cur_i - p0.first)\n                           + abs(cur_j - p0.second);\n                    parentArr[0][j] = -1;\n                }\n            }\n            int prevSz = occSz[0];\n            // Stages 1..rem-1\n            for(int s2 = 1; s2 < rem; s2++){\n                int cprev = w[ov + s2 - 1] - 'A';\n                int ccur  = w[ov + s2]     - 'A';\n                int szc   = occSz[s2];\n                // init\n                for(int v = 0; v < szc; v++){\n                    dp2[v] = INF;\n                    parentArr[s2][v] = -1;\n                }\n                // relax\n                for(int u = 0; u < prevSz; u++){\n                    auto &pp = pos[cprev][u];\n                    int base = dp1[u];\n                    for(int v = 0; v < szc; v++){\n                        auto &pc = pos[ccur][v];\n                        int cand = base\n                                 + abs(pp.first  - pc.first)\n                                 + abs(pp.second - pc.second);\n                        if(cand < dp2[v]){\n                            dp2[v] = cand;\n                            parentArr[s2][v] = u;\n                        }\n                    }\n                }\n                // swap in\n                for(int v = 0; v < szc; v++){\n                    dp1[v] = dp2[v];\n                }\n                prevSz = szc;\n            }\n            // pick best end\n            int bestEnd = 0;\n            for(int j = 1; j < prevSz; j++){\n                if(dp1[j] < dp1[bestEnd]) bestEnd = j;\n            }\n            // backtrack indices\n            vector<int> idx(rem);\n            {\n                int cur = bestEnd;\n                for(int s2 = rem - 1; s2 >= 0; s2--){\n                    idx[s2] = cur;\n                    cur = parentArr[s2][cur];\n                }\n            }\n            // emit moves\n            for(int s2 = 0; s2 < rem; s2++){\n                int c = w[ov + s2] - 'A';\n                auto &p = pos[c][ idx[s2] ];\n                moves.emplace_back(p);\n                cur_i = p.first;\n                cur_j = p.second;\n                // update tail\u2010buffer\n                lastS.push_back(w[ov + s2]);\n                if((int)lastS.size() > 4){\n                    lastS.erase(lastS.begin(),\n                                lastS.end() - 4);\n                }\n            }\n        }\n    }\n\n    // Output all moves (\u2264 200*5 = 1000)\n    for(auto &mv : moves){\n        cout << mv.first << \" \" << mv.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    cin >> N >> M >> eps;\n\n    // 1) Read shapes\n    vector<vector<pair<int,int>>> shape(M);\n    vector<int> shape_max_i(M), shape_max_j(M);\n    long long total_shape_cells = 0;\n    for(int k = 0; k < M; k++){\n        int d;\n        cin >> d;\n        total_shape_cells += d;\n        int mx_i = 0, mx_j = 0;\n        shape[k].resize(d);\n        for(int t = 0; t < d; t++){\n            int ii, jj;\n            cin >> ii >> jj;\n            shape[k][t] = {ii,jj};\n            mx_i = max(mx_i, ii);\n            mx_j = max(mx_j, jj);\n        }\n        shape_max_i[k] = mx_i;\n        shape_max_j[k] = mx_j;\n    }\n\n    // 2) Enumerate all placements for each shape\n    //    and build a reverse\u2010map from cell -> list of (k,placement_id).\n    //    Also store for each placement the list of its covered cell\u2010IDs.\n    //    We flatten cells by id = i*N + j.\n    vector<vector<vector<int>>> placement_cells(M);\n    vector<vector<bool>> alive(M);\n    vector<vector<pair<int,int>>> coverList(N*N);\n    for(int k = 0; k < M; k++){\n        int mx_i = shape_max_i[k];\n        int mx_j = shape_max_j[k];\n        for(int di = 0; di + mx_i < N; di++){\n            for(int dj = 0; dj + mx_j < N; dj++){\n                int pid = (int)placement_cells[k].size();\n                placement_cells[k].push_back({});\n                alive[k].push_back(true);\n                auto &cells = placement_cells[k].back();\n                for(auto &p : shape[k]){\n                    int ii = di + p.first;\n                    int jj = dj + p.second;\n                    int id = ii*N + jj;\n                    cells.push_back(id);\n                    coverList[id].emplace_back(k, pid);\n                }\n            }\n        }\n    }\n\n    // 3) coverCount[i] = # of (k,pid) alive that cover that cell\n    vector<int> coverCount(N*N, 0);\n    for(int id = 0; id < N*N; id++){\n        coverCount[id] = (int)coverList[id].size();\n    }\n\n    // 4) vgrid: -1=unknown, >=0 = drilled value or inferred zero\n    vector<int> vgrid(N*N, -1);\n    vector<char> drilled(N*N, 0);\n\n    auto eliminate_at_zero = [&](int id){\n        // kill every placement that covers 'id'\n        for(auto &kp : coverList[id]){\n            int k   = kp.first;\n            int pid = kp.second;\n            if(!alive[k][pid]) continue;\n            alive[k][pid] = false;\n            // decrement coverCount for its cells\n            for(int cid : placement_cells[k][pid]){\n                coverCount[cid]--;\n            }\n        }\n    };\n\n    // 5) drill function that also updates the shape\u2010elimination\n    auto drill = [&](int i,int j){\n        int id = i*N + j;\n        cout << \"q 1 \" << i << \" \" << j << \"\\n\" << flush;\n        int v;\n        if(!(cin >> v)) exit(0);\n        drilled[id] = 1;\n        vgrid[id]   = v;\n        if(v == 0){\n            eliminate_at_zero(id);\n        }\n    };\n\n    // 6) helper to ensure we skip certainly\u2010zero cells\n    auto ensure_known_zero = [&](int i,int j){\n        int id = i*N + j;\n        if(vgrid[id] == -1 && coverCount[id] == 0){\n            vgrid[id] = 0;\n            drilled[id] = 1;\n        }\n    };\n\n    // Phase 1) drill all even\u2010parity cells, except those we can infer to be zero\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(((i + j) & 1) == 0){\n                int id = i*N + j;\n                if(drilled[id]) continue;\n                ensure_known_zero(i,j);\n                if(drilled[id]) continue; // it was infered zero\n                // otherwise we really drill\n                drill(i,j);\n            }\n        }\n    }\n\n    // Phase 2) odd cells but only those adjacent to an even\u2010parity oil cell\n    static const int di[4] = {1,-1,0,0}, dj[4] = {0,0,1,-1};\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(((i + j) & 1) == 1){\n                int id = i*N + j;\n                if(drilled[id]) continue;\n                // first see if _all_ 4\u2010neighbors are either out\u2010of\u2010bounds\n                // or have v=0 => then this odd cell must be zero\n                bool any_oil_neighbor = false;\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                    int nid = ni*N + nj;\n                    if(vgrid[nid] > 0){\n                        any_oil_neighbor = true;\n                        break;\n                    }\n                }\n                if(!any_oil_neighbor){\n                    // we know v(i,j)=0\n                    vgrid[id] = 0;\n                    drilled[id]=1;\n                    continue;\n                }\n                // otherwise it _could_ be oil\n                // but maybe shape\u2010elimination tells us it is impossible\n                ensure_known_zero(i,j);\n                if(drilled[id]) continue;\n                // if still unknown, we must drill\n                drill(i,j);\n            }\n        }\n    }\n\n    // 7) Collect all v>0\n    vector<pair<int,int>> answer;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(vgrid[i*N+j] > 0){\n                answer.emplace_back(i,j);\n            }\n        }\n    }\n\n    // 8) Output the final answer\n    cout << \"a \" << answer.size();\n    for(auto &p : answer){\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << \"\\n\" << flush;\n    int verdict;\n    if(cin >> verdict){\n        // 1 = OK, 0 = WA\n    }\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int W = 1000;\n    int D, N;\n    cin >> ws >> ws; // skip potential leading whitespace (safe no\u2010op)\n    // Actually the problem gives W=1000 first:\n    cin.clear();\n    cin.seekg(0);\n    int tmpW;\n    cin >> tmpW >> D >> N;\n    // tmpW should be 1000\n    vector<vector<int>> a(D, vector<int>(N));\n    for(int d = 0; d < D; d++)\n        for(int k = 0; k < N; k++)\n            cin >> a[d][k];\n\n    // For each day independently, we build w[k] \u2265 1 so as to minimize:\n    //   100*max(0, a[d][k] - 1000*w[k])  subject to sum w[k] \u2264 1000\n    // By classic \u201cmarginal\u2010benefit\u201d greedy: start w[k]=1 (used=N), then\n    // collect all positive marginals m[k][t]=min(1000, a-1000*t) for t=1..ceil(a/1000)-1,\n    // sort them descending, and take the top (W-N).\n    vector<pair<int,int>> M; \n    M.reserve(2000);\n\n    vector<int> w(N), X(N+1);\n    for(int d = 0; d < D; d++){\n        // 1) init\n        for(int k = 0; k < N; k++) w[k] = 1;\n        int used = N;\n        int rem = W - used;\n\n        // 2) build all positive marginals\n        M.clear();\n        for(int k = 0; k < N; k++){\n            int ad = a[d][k];\n            // for t=1.. until ad - 1000*t <= 0\n            // marginal of the t-th extra column (beyond the first)\n            // is min(1000, ad - 1000*t).\n            for(int t = 1; ; t++){\n                int leftover = ad - 1000 * t;\n                if(leftover <= 0) break;\n                M.emplace_back(min(1000, leftover), k);\n            }\n        }\n\n        // 3) pick the top rem marginals\n        if(!M.empty()){\n            nth_element(M.begin(), M.begin() + min(rem, (int)M.size()), M.end(),\n                        [](auto &A, auto &B){ return A.first > B.first; });\n            int take = min(rem, (int)M.size());\n            // count how many times each k appears in the top\u2010take\n            static vector<int> cnt;\n            cnt.assign(N, 0);\n            for(int i = 0; i < take; i++){\n                if(M[i].first <= 0) break;\n                cnt[M[i].second]++;\n            }\n            for(int k = 0; k < N; k++){\n                w[k] += cnt[k];\n            }\n        }\n\n        // 4) compute X\u2010coordinates\n        X[0] = 0;\n        for(int k = 0; k < N; k++){\n            X[k+1] = X[k] + w[k];\n        }\n        // 5) output this day's rectangles\n        //    rectangle k:  i0=0, j0=X[k], i1=1000, j1=X[k+1]\n        for(int k = 0; k < N; k++){\n            cout << 0 << ' ' << X[k] << ' ' << W << ' ' << X[k+1] << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\nstatic const int MOD = 998244353;\n\n// one candidate placement\nstruct Cand { long long d; int m,p,q; };\n\nint N,M,K;\nint B[9][9];\nint stamps[20][3][3];\n\n// compute immediate score\u2010delta if we press stamp m at (p,q)\ninline long long compute_delta(const int A[9][9], int m, int p, int q){\n    long long d = 0;\n    auto &S = stamps[m];\n    for(int i=0;i<3;i++) for(int j=0;j<3;j++){\n        int oldv = A[p+i][q+j];\n        int s    = S[i][j];\n        int su   = oldv + s;\n        if(su < MOD)      d += s;\n        else              d += (long long)s - MOD;\n    }\n    return d;\n}\n\n// apply the stamp (mod MOD) in\u2010place on A\ninline void apply_op(int A[9][9], int m, int p, int q){\n    auto &S = stamps[m];\n    for(int i=0;i<3;i++) for(int j=0;j<3;j++){\n        int &c = A[p+i][q+j];\n        c += S[i][j];\n        if(c >= MOD) c -= MOD;\n    }\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M >> K; // N=9, M=20, K=81\n    for(int i=0;i<N;i++) for(int j=0;j<N;j++){\n        long long x; cin >> x;\n        B[i][j] = int(x % MOD);\n    }\n    for(int m=0;m<M;m++) for(int i=0;i<3;i++) for(int j=0;j<3;j++){\n        long long x; cin >> x;\n        stamps[m][i][j] = int(x % MOD);\n    }\n\n    vector<array<int,3>> ops;\n    ops.reserve(K);\n\n    // temporary boards for lookahead\n    static int T1[9][9], T2[9][9], T3[9][9];\n\n    while((int)ops.size() < K){\n        int rem = K - (int)ops.size();\n\n        // 1) find top\u20102 immediate moves on current B\n        Cand best1{LLONG_MIN,0,0,0}, best2{LLONG_MIN,0,0,0};\n        for(int m=0;m<M;m++){\n            for(int p=0;p+2<N;p++){\n                for(int q=0;q+2<N;q++){\n                    long long d = compute_delta(B,m,p,q);\n                    if(d > best1.d){\n                        best2 = best1;\n                        best1 = {d,m,p,q};\n                    } else if(d > best2.d){\n                        best2 = {d,m,p,q};\n                    }\n                }\n            }\n        }\n\n        // if only 1 move left, do the trivial greedy\n        if(rem == 1){\n            if(best1.d <= 0) break;\n            apply_op(B,best1.m,best1.p,best1.q);\n            ops.push_back({best1.m,best1.p,best1.q});\n            break;\n        }\n\n        // --- branch 0 = best1: do a 3\u2010step lookahead ---\n        // step 1 \u2192 T1\n        memcpy(T1,B,sizeof B);\n        apply_op(T1,best1.m,best1.p,best1.q);\n        // find best 2nd on T1\n        Cand best2_0{LLONG_MIN,0,0,0};\n        for(int m=0;m<M;m++){\n            for(int p=0;p+2<N;p++){\n                for(int q=0;q+2<N;q++){\n                    long long d = compute_delta(T1,m,p,q);\n                    if(d > best2_0.d) best2_0 = {d,m,p,q};\n                }\n            }\n        }\n        // step 2 \u2192 T2\n        memcpy(T2,T1,sizeof T1);\n        apply_op(T2,best2_0.m,best2_0.p,best2_0.q);\n        // find best 3rd on T2\n        Cand best3_0{LLONG_MIN,0,0,0};\n        for(int m=0;m<M;m++){\n            for(int p=0;p+2<N;p++){\n                for(int q=0;q+2<N;q++){\n                    long long d = compute_delta(T2,m,p,q);\n                    if(d > best3_0.d) best3_0 = {d,m,p,q};\n                }\n            }\n        }\n\n        // --- branch 1 = best2: do only a 2\u2010step lookahead ---\n        memcpy(T3,B,sizeof B);\n        apply_op(T3,best2.m,best2.p,best2.q);\n        Cand best2_1{LLONG_MIN,0,0,0};\n        for(int m=0;m<M;m++){\n            for(int p=0;p+2<N;p++){\n                for(int q=0;q+2<N;q++){\n                    long long d = compute_delta(T3,m,p,q);\n                    if(d > best2_1.d) best2_1 = {d,m,p,q};\n                }\n            }\n        }\n\n        // compute all chain\u2010sums\n        long long s1    = best1.d;\n        long long s2_0  = best1.d + best2_0.d;\n        long long s2_1  = best2.d + best2_1.d;\n        long long s3_0  = best1.d + best2_0.d + best3_0.d;\n\n        // pick best among 1/2/3\u2010step (respecting rem)\n        long long bestSum = LLONG_MIN;\n        int    bestR   = 0, bestBr = 0;\n        if(rem >= 3 && s3_0 > bestSum){\n            bestSum = s3_0; bestR = 3; bestBr = 0;\n        }\n        if(rem >= 2){\n            if(s2_0 > bestSum){\n                bestSum = s2_0; bestR = 2; bestBr = 0;\n            }\n            if(s2_1 > bestSum){\n                bestSum = s2_1; bestR = 2; bestBr = 1;\n            }\n        }\n        if(s1 > bestSum){\n            bestSum = s1; bestR = 1; bestBr = 0;\n        }\n        if(bestSum <= 0) break;  // no positive chain, stop\n\n        // commit that chain on the real B\n        if(bestR == 1){\n            apply_op(B,best1.m,best1.p,best1.q);\n            ops.push_back({best1.m,best1.p,best1.q});\n        }\n        else if(bestR == 2){\n            if(bestBr == 0){\n                // branch0 two\u2010step\n                apply_op(B,best1.m,best1.p,best1.q);\n                apply_op(B,best2_0.m,best2_0.p,best2_0.q);\n                ops.push_back({best1.m,best1.p,best1.q});\n                ops.push_back({best2_0.m,best2_0.p,best2_0.q});\n            } else {\n                // branch1 two\u2010step\n                apply_op(B,best2.m,best2.p,best2.q);\n                apply_op(B,best2_1.m,best2_1.p,best2_1.q);\n                ops.push_back({best2.m,best2.p,best2.q});\n                ops.push_back({best2_1.m,best2_1.p,best2_1.q});\n            }\n        }\n        else {\n            // bestR == 3 \u2192 only branch0\n            apply_op(B,best1.m,best1.p,best1.q);\n            apply_op(B,best2_0.m,best2_0.p,best2_0.q);\n            apply_op(B,best3_0.m,best3_0.p,best3_0.q);\n            ops.push_back({best1.m,best1.p,best1.q});\n            ops.push_back({best2_0.m,best2_0.p,best2_0.q});\n            ops.push_back({best3_0.m,best3_0.p,best3_0.q});\n        }\n    }\n\n    // final output\n    cout << ops.size() << \"\\n\";\n    for(auto &o : ops)\n        cout << o[0] << \" \" << o[1] << \" \" << o[2] << \"\\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    cin >> N;\n    vector<vector<int>> A(N, vector<int>(N));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cin >> A[i][j];\n        }\n    }\n\n    // We'll bomb cranes 1..N-1 and do everything with crane 0 (the large crane).\n    vector<int> picked(N, 0);\n    int curR = 0, curC = 0;\n    vector<char> ops0;\n\n    int total = N * N;\n    for(int done = 0; done < total; done++){\n        // 1) Find the row r whose next container ID is minimal\n        int bestR = -1;\n        int bestID = INT_MAX, bestDist = INT_MAX;\n        for(int r = 0; r < N; r++){\n            if(picked[r] < N){\n                int id = A[r][ picked[r] ];\n                int d  = abs(curR - r) + abs(curC - 0);\n                if(id < bestID || (id == bestID && d < bestDist)){\n                    bestID = id;\n                    bestDist = d;\n                    bestR = r;\n                }\n            }\n        }\n        // 2) Move crane0 from (curR,curC) to (bestR, 0)\n        int dr = bestR - curR;\n        if(dr > 0) while(dr--) ops0.push_back('D');\n        else      while(dr++) ops0.push_back('U');\n        int dc = 0 - curC;\n        if(dc > 0) while(dc--) ops0.push_back('R');\n        else       while(dc++) ops0.push_back('L');\n\n        // 3) Pick up\n        ops0.push_back('P');\n        picked[bestR]++;\n\n        // 4) Deliver to its correct dispatch gate at (destR, N-1)\n        int destR = bestID / N;\n        // horizontal to column N-1\n        for(int k = 0; k < N-1; k++) ops0.push_back('R');\n        // vertical to destR\n        int dr2 = destR - bestR;\n        if(dr2 > 0) while(dr2--) ops0.push_back('D');\n        else        while(dr2++) ops0.push_back('U');\n        // drop\n        ops0.push_back('Q');\n\n        // update position\n        curR = destR;\n        curC = N-1;\n    }\n\n    int M = (int)ops0.size();\n    vector<string> S(N);\n    // crane 0\n    S[0].reserve(M);\n    for(char c : ops0) S[0].push_back(c);\n    // cranes 1..N-1: bomb at turn0, then idle\n    for(int i = 1; i < N; i++){\n        S[i].push_back('B');\n        S[i].append(M-1, '.');\n    }\n\n    // output\n    for(int i = 0; i < N; i++){\n        cout << S[i] << \"\\n\";\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Task {\n    int sx, sy;\n    int tx, ty;\n    int d;\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<vector<int>> h(N, vector<int>(N));\n    for(int i = 0; i < N; i++)\n        for(int j = 0; j < N; j++)\n            cin >> h[i][j];\n\n    // 1) collect sources and sinks\n    vector<pair<int,int>> src, dst;\n    vector<int> supply, demand;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(h[i][j] > 0){\n                src.emplace_back(i,j);\n                supply.push_back(h[i][j]);\n            } else if(h[i][j] < 0){\n                dst.emplace_back(i,j);\n                demand.push_back(-h[i][j]);\n            }\n        }\n    }\n    int S = src.size(), T = dst.size();\n    if(S == 0){\n        // already flat?\n        return 0;\n    }\n\n    // 2) build all pairs with distance\n    struct Edge { int dist, i, j; };\n    vector<Edge> E;\n    E.reserve(S*T);\n    for(int i = 0; i < S; i++){\n        for(int j = 0; j < T; j++){\n            int d = abs(src[i].first - dst[j].first)\n                  + abs(src[i].second - dst[j].second);\n            E.push_back({d, i, j});\n        }\n    }\n    sort(E.begin(), E.end(),\n         [&](auto &a, auto &b){ return a.dist < b.dist; });\n\n    // 3) greedy matching\n    vector<int> remS = supply, remT = demand;\n    vector<vector<int>> flow(S, vector<int>(T,0));\n    for(auto &e : E){\n        int i = e.i, j = e.j;\n        if(remS[i] == 0 || remT[j] == 0) continue;\n        int d = min(remS[i], remT[j]);\n        flow[i][j] = d;\n        remS[i] -= d;\n        remT[j] -= d;\n    }\n\n    // 4) collect tasks\n    vector<Task> tasks;\n    tasks.reserve(S+T);\n    for(int i = 0; i < S; i++){\n        for(int j = 0; j < T; j++){\n            if(flow[i][j] > 0){\n                tasks.push_back({\n                    src[i].first, src[i].second,\n                    dst[j].first, dst[j].second,\n                    flow[i][j]\n                });\n            }\n        }\n    }\n\n    // 5) execute tasks in nearest\u2010neighbor order\n    int cx = 0, cy = 0;\n    vector<string> ops;\n    ops.reserve(40000);\n\n    auto go = [&](int nx, int ny){\n        while(cx < nx){ ops.push_back(\"D\"); cx++; }\n        while(cx > nx){ ops.push_back(\"U\"); cx--; }\n        while(cy < ny){ ops.push_back(\"R\"); cy++; }\n        while(cy > ny){ ops.push_back(\"L\"); cy--; }\n    };\n\n    while(!tasks.empty()){\n        // pick the task whose source is closest (empty travel)\n        int best = 0, bestd = INT_MAX;\n        for(int i = 0; i < (int)tasks.size(); i++){\n            int d = abs(tasks[i].sx - cx)\n                  + abs(tasks[i].sy - cy);\n            if(d < bestd){\n                bestd = d;\n                best = i;\n            }\n        }\n        Task t = tasks[best];\n        // remove it\n        tasks[best] = tasks.back();\n        tasks.pop_back();\n\n        // move to source\n        go(t.sx, t.sy);\n        // load\n        ops.push_back(\"+\" + to_string(t.d));\n        // move to sink\n        go(t.tx, t.ty);\n        // unload\n        ops.push_back(\"-\" + to_string(t.d));\n    }\n\n    // output\n    for(auto &s : ops) {\n        cout << s << \"\\n\";\n    }\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    cin >> N >> M >> T;\n    const int S = 2 * N * (N - 1);    // 60 when N=6\n\n    // read initial seeds\n    vector<vector<int>> X(S, vector<int>(M));\n    for(int i = 0; i < S; i++)\n      for(int j = 0; j < M; j++)\n        cin >> X[i][j];\n\n    // precompute the four 2\u00d72 central cells\n    vector<pair<int,int>> core;\n    int a = N/2 - 1, b = N/2;\n    core.push_back({a, a});\n    core.push_back({a, b});\n    core.push_back({b, a});\n    core.push_back({b, b});\n\n    // precompute the other interior (deg=4), edge (deg=3), corner (deg=2) cells\n    auto dist2 = [&](int i, int j){\n        // manhattan to true center (N-1)/2, scaled by 2 to avoid fractions\n        return abs(2*i - (N-1)) + abs(2*j - (N-1));\n    };\n    vector<pair<int,int>> interior, edges, corners;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            int deg = (i>0) + (i<N-1) + (j>0) + (j<N-1);\n            bool inCore = (i==a||i==b) && (j==a||j==b);\n            if(deg==4 && !inCore){\n                interior.emplace_back(i,j);\n            } else if(deg==3){\n                edges.emplace_back(i,j);\n            } else if(deg==2){\n                corners.emplace_back(i,j);\n            }\n        }\n    }\n    // sort interior & edges by centrality\n    sort(interior.begin(), interior.end(), [&](auto &A, auto &B){\n        int d1 = dist2(A.first,A.second), d2 = dist2(B.first,B.second);\n        if(d1!=d2) return d1<d2;\n        return A < B;\n    });\n    sort(edges.begin(), edges.end(), [&](auto &A, auto &B){\n        int d1 = dist2(A.first,A.second), d2 = dist2(B.first,B.second);\n        if(d1!=d2) return d1<d2;\n        return A < B;\n    });\n    sort(corners.begin(), corners.end());\n\n    // main T turns\n    for(int turn = 0; turn < T; turn++){\n        // 1) compute per\u2010seed total sums\n        vector<int> sumVal(S);\n        vector<pair<int,int>> V(S);\n        for(int i = 0; i < S; i++){\n            int s = 0;\n            for(int x : X[i]) s += x;\n            sumVal[i] = s;\n            V[i] = {s, i};\n        }\n        sort(V.begin(), V.end(), greater<>());  // by sum desc\n\n        // 2) pick the champion\u2010of\u2010each\u2010dimension\n        vector<int> best_dim(M), champSeeds;\n        {\n            vector<char> used(S,0);\n            for(int d = 0; d < M; d++){\n                int who = 0, bv = -1;\n                for(int i = 0; i < S; i++){\n                    if(X[i][d] > bv){\n                        bv = X[i][d];\n                        who = i;\n                    }\n                }\n                if(!used[who]){\n                    used[who] = 1;\n                    champSeeds.push_back(who);\n                }\n            }\n        }\n        // 3) fill up to N*N = 36 by top\u2010sum\n        vector<char> usedSel(S,0);\n        vector<int> picks = champSeeds;\n        for(int id : champSeeds) usedSel[id] = 1;\n        for(auto &pr : V){\n            if((int)picks.size() >= N*N) break;\n            int id = pr.second;\n            if(!usedSel[id]){\n                usedSel[id] = 1;\n                picks.push_back(id);\n            }\n        }\n        // 4) sort our picks by their total\u2010sum descending\n        sort(picks.begin(), picks.end(), [&](int a, int b){\n            return sumVal[a] > sumVal[b];\n        });\n\n        // 5) carve off the top\u20104 for the core\n        vector<int> top4(picks.begin(), picks.begin()+4);\n        //    and rebuild the champion\u2010only list EXcluding any of those top4\n        vector<int> ch2;\n        for(int c: champSeeds){\n            if(find(top4.begin(), top4.end(), c) == top4.end())\n                ch2.push_back(c);\n        }\n        //    sort those by sum desc so best champions get closest to center\n        sort(ch2.begin(), ch2.end(), [&](int a, int b){\n            return sumVal[a] > sumVal[b];\n        });\n\n        // 6) assign into the grid\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        vector<char> usedA(S,0);\n        // 6a) core\n        for(int i = 0; i < 4; i++){\n            auto [r,c] = core[i];\n            A[r][c] = top4[i];\n            usedA[top4[i]] = 1;\n        }\n        // 6b) interior\u2010exclusive\n        int idx = 0;\n        for(int i = 0; i < (int)interior.size() && i < (int)ch2.size(); i++){\n            auto [r,c] = interior[i];\n            A[r][c] = ch2[i];\n            usedA[ch2[i]] = 1;\n            idx = i+1;\n        }\n        // 6c) fill the rest of interior with the highest\u2010sum picks\n        int ptr = 0;\n        for(int i = idx; i < (int)interior.size(); i++){\n            while(usedA[picks[ptr]]) ptr++;\n            auto [r,c] = interior[i];\n            A[r][c] = picks[ptr++];\n            usedA[A[r][c]] = 1;\n        }\n        // 6d) fill edges\n        for(auto &cell : edges){\n            while(usedA[picks[ptr]]) ptr++;\n            A[cell.first][cell.second] = picks[ptr++];\n            usedA[A[cell.first][cell.second]] = 1;\n        }\n        // 6e) fill corners\n        for(auto &cell : corners){\n            while(usedA[picks[ptr]]) ptr++;\n            A[cell.first][cell.second] = picks[ptr++];\n            usedA[A[cell.first][cell.second]] = 1;\n        }\n\n        // 7) output & flush\n        for(int i = 0; i < N; i++){\n            for(int j = 0; j < N; j++){\n                cout << A[i][j] << (j+1<N? ' ':'\\n');\n            }\n        }\n        cout << flush;\n\n        // 8) read the next generation\n        for(int i = 0; i < S; i++){\n            for(int j = 0; j < M; j++){\n                cin >> X[i][j];\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Directions: 0=right,1=down,2=left,3=up\nconst int DX[4] = {0, 1, 0, -1};\nconst int DY[4] = {1, 0, -1, 0};\nconst char DIRC[4] = {'R','D','L','U'};\n\n// Move the fingertip so it lands on (tx,ty), then do exactly one 'P' (pickup/drop).\n// Updates rx,ry,dir,holding, ops[], and cur[][].\nvoid move_fingertip(int tx, int ty, int N,\n                    int &rx, int &ry, int &dir, bool &holding,\n                    vector<string> &ops, vector<vector<char>> &cur) {\n    // 1) Find best orientation d and new root (brx,bry), & minimal turns T\n    int bestT = INT_MAX, bestD=0, brx=0, bry=0, brot=0, bcw=0;\n    for(int d=0; d<4; d++){\n        int nrx = tx - DX[d], nry = ty - DY[d];\n        if(nrx<0||nrx>=N||nry<0||nry>=N) continue;\n        int dist = abs(nrx - rx) + abs(nry - ry);\n        int cw  = (d - dir + 4) % 4;\n        int ccw = (dir - d + 4) % 4;\n        int rot = min(cw, ccw);\n        int T = max(dist, rot);\n        if(T < bestT){\n            bestT = T;\n            bestD = d;\n            brx = nrx; bry = nry;\n            brot = rot;\n            bcw = (cw <= ccw);\n        }\n    }\n    if(bestT==INT_MAX){\n        // Shouldn't happen if root never sits on a source/target.\n        // Emit a dummy turn\n        ops.push_back(string(4, '.'));\n        return;\n    }\n    // We need at least 1 turn to do the 'P'\n    int T = max(1, bestT);\n    int dist   = abs(brx - rx) + abs(bry - ry);\n    int rotCnt = brot;\n    int rem_dx = brx - rx, rem_dy = bry - ry;\n    char rotCh = (bcw ? 'R' : 'L');\n\n    for(int step=0; step<T; step++){\n        char m='.', r='.', a1='.';\n        // Move root if needed\n        if(step < dist){\n            if(rem_dx>0){ m='D'; rem_dx--; rx++; }\n            else if(rem_dx<0){ m='U'; rem_dx++; rx--; }\n            else if(rem_dy>0){ m='R'; rem_dy--; ry++; }\n            else if(rem_dy<0){ m='L'; rem_dy--; ry--; }\n        }\n        // Rotate fingertip if needed\n        if(step < rotCnt){\n            r = rotCh;\n            if(rotCh=='R') dir = (dir+1)&3;\n            else           dir = (dir+3)&3;\n        }\n        // On final step, do the P\n        if(step == T-1){\n            int fx = rx + DX[dir], fy = ry + DY[dir];\n            if(fx>=0 && fx<N && fy>=0 && fy<N){\n                if(!holding && cur[fx][fy]){\n                    // pickup\n                    cur[fx][fy]=0;\n                    holding=true;\n                    a1='P';\n                } else if(holding && !cur[fx][fy]){\n                    // drop\n                    cur[fx][fy]=1;\n                    holding=false;\n                    a1='P';\n                }\n            }\n        }\n        // Build command of length 4: [move][rotate of v=1][.][action v=1]\n        string S(4,'.');\n        S[0]=m; S[1]=r; /*S[2]='.'*/ S[3]=a1;\n        ops.push_back(S);\n    }\n    dir = bestD;  // ensure final orientation is recorded\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Vmax;\n    cin >> N >> M >> Vmax;\n    vector<string> S(N), T(N);\n    for(int i=0;i<N;i++) cin>>S[i];\n    for(int i=0;i<N;i++) cin>>T[i];\n\n    vector<pair<int,int>> src, dst;\n    vector<vector<char>> cur(N, vector<char>(N, 0)), occ(N, vector<char>(N,0));\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            if(S[i][j]=='1'){\n                src.emplace_back(i,j);\n                cur[i][j]=1;\n                occ[i][j]=1;\n            }\n            if(T[i][j]=='1'){\n                dst.emplace_back(i,j);\n                occ[i][j]=1;\n            }\n        }\n    }\n    // We will do on\u2010the\u2010fly matching, so no need to sort src or dst.\n\n    // Design a 2\u2010node arm\n    cout << 2 << \"\\n\";\n    cout << 0 << \" \" << 1 << \"\\n\";\n\n    // Choose initial root near grid\u2010center on an empty square\n    int cx = (N-1)/2, cy = (N-1)/2;\n    int bestDist = INT_MAX, rx=0, ry=0;\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            if(occ[i][j]) continue;\n            int d = abs(i-cx) + abs(j-cy);\n            if(d < bestDist){\n                bestDist = d;\n                rx = i; ry = j;\n            }\n        }\n    }\n    // If no empty cell (rare), we just pick (0,0)\n    cout << rx << \" \" << ry << \"\\n\";\n\n    int dir = 0;           // fingertip initially points right\n    bool holding = false;\n    vector<string> ops;\n    vector<char> used_src(M,0), used_dst(M,0);\n    int tasks = M;\n\n    for(int iter=0; iter<tasks; iter++){\n        // 1) choose next source by minimal pickup\u2010turns from (rx,ry,dir)\n        int best_i=-1, bestT=INT_MAX;\n        for(int i=0;i<M;i++){\n            if(used_src[i]) continue;\n            auto [sx,sy] = src[i];\n            // compute minimal turns to pick up at (sx,sy)\n            int localBest = INT_MAX;\n            for(int d=0;d<4;d++){\n                int nrx = sx - DX[d], nry = sy - DY[d];\n                if(nrx<0||nrx>=N||nry<0||nry>=N) continue;\n                int dist = abs(nrx - rx) + abs(nry - ry);\n                int cw  = (d - dir + 4) % 4;\n                int ccw = (dir - d + 4) % 4;\n                int rot = min(cw, ccw);\n                localBest = min(localBest, max(dist, rot));\n            }\n            if(localBest < bestT){\n                bestT = localBest;\n                best_i = i;\n            }\n        }\n        used_src[best_i] = 1;\n        auto [sx,sy] = src[best_i];\n\n        // 2) match this source to the nearest remaining target by Manhattan\n        int best_j=-1, bestD2=INT_MAX;\n        for(int j=0;j<M;j++){\n            if(used_dst[j]) continue;\n            auto [tx,ty] = dst[j];\n            int d = abs(tx - sx) + abs(ty - sy);\n            if(d < bestD2){\n                bestD2 = d;\n                best_j = j;\n            }\n        }\n        used_dst[best_j] = 1;\n        auto [tx,ty] = dst[best_j];\n\n        // 3) service: move to pickup, then move to drop\n        move_fingertip(sx, sy, N, rx, ry, dir, holding, ops, cur);\n        move_fingertip(tx, ty, N, rx, ry, dir, holding, ops, cur);\n    }\n\n    // Output all turns\n    for(auto &s: ops){\n        cout << s << \"\\n\";\n    }\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pt { int x, y, w; };\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int HMAX = 100000;\n    const int CG   = 200;\n    const int KREF = 30;\n\n    // (Kx, Ni) for global X-sliding windows\n    vector<pair<int,int>> XSETS = {\n        {200, 20},\n        {350, 40},\n        {600, 10}\n    };\n    // one horizontal pass\n    const int HY   = 300;\n    const int NIY  = 6;\n\n    int N;\n    cin >> N;\n    vector<Pt> pts(2*N);\n    for(int i = 0; i < 2*N; i++){\n        cin >> pts[i].x >> pts[i].y;\n        pts[i].w = (i < N ? +1 : -1);\n    }\n\n    // 1) Coordinate compression\n    vector<int> xs, ys;\n    xs.reserve(2*N);\n    ys.reserve(2*N);\n    for(auto &p: pts){\n        xs.push_back(p.x);\n        ys.push_back(p.y);\n    }\n    sort(xs.begin(), xs.end());\n    xs.erase(unique(xs.begin(), xs.end()), xs.end());\n    sort(ys.begin(), ys.end());\n    ys.erase(unique(ys.begin(), ys.end()), ys.end());\n    int MX = xs.size(), MY = ys.size();\n\n    vector<int> cX(2*N), cY(2*N);\n    for(int i = 0; i < 2*N; i++){\n        cX[i] = int(lower_bound(xs.begin(), xs.end(), pts[i].x) - xs.begin());\n        cY[i] = int(lower_bound(ys.begin(), ys.end(), pts[i].y) - ys.begin());\n    }\n\n    // 2) Build per-column & per-row bins + prefix sums\n    vector<vector<pair<int,int>>> binsX(MX), binsY(MY);\n    for(int i = 0; i < 2*N; i++){\n        binsX[cX[i]].emplace_back(cY[i], pts[i].w);\n        binsY[cY[i]].emplace_back(cX[i], pts[i].w);\n    }\n    vector<vector<int>> bX_y(MX), bX_ps(MX), bY_x(MY), bY_ps(MY);\n    for(int x = 0; x < MX; x++){\n        auto &v = binsX[x];\n        sort(v.begin(), v.end());\n        int m = v.size();\n        bX_y[x].resize(m);\n        bX_ps[x].resize(m);\n        for(int i = 0; i < m; i++){\n            bX_y[x][i]  = v[i].first;\n            bX_ps[x][i] = v[i].second + (i ? bX_ps[x][i-1] : 0);\n        }\n    }\n    for(int y = 0; y < MY; y++){\n        auto &v = binsY[y];\n        sort(v.begin(), v.end());\n        int m = v.size();\n        bY_x[y].resize(m);\n        bY_ps[y].resize(m);\n        for(int i = 0; i < m; i++){\n            bY_x[y][i]  = v[i].first;\n            bY_ps[y][i] = v[i].second + (i ? bY_ps[y][i-1] : 0);\n        }\n    }\n\n    auto colSum = [&](int cx, int y1, int y2){\n        auto &vy = bX_y[cx], &ps = bX_ps[cx];\n        int lo = int(lower_bound(vy.begin(), vy.end(), y1) - vy.begin());\n        int hi = int(upper_bound(vy.begin(), vy.end(), y2) - vy.begin()) - 1;\n        if(lo > hi) return 0;\n        return ps[hi] - (lo ? ps[lo-1] : 0);\n    };\n    auto rowSum = [&](int cy, int x1, int x2){\n        auto &vx = bY_x[cy], &ps = bY_ps[cy];\n        int lo = int(lower_bound(vx.begin(), vx.end(), x1) - vx.begin());\n        int hi = int(upper_bound(vx.begin(), vx.end(), x2) - vx.begin()) - 1;\n        if(lo > hi) return 0;\n        return ps[hi] - (lo ? ps[lo-1] : 0);\n    };\n\n    // 3) Multi-step local refine on a single rectangle\n    auto refineRect = [&](int &x1, int &x2, int &y1, int &y2, int &A){\n        bool improved = true;\n        while(improved){\n            improved = false;\n            // expansions\n            // left\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && x1-k>=0; k++){\n                    s += colSum(x1-k, y1, y2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ x1-=bk; A+=best; improved=true; continue;}\n            }\n            // right\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && x2+k<MX; k++){\n                    s += colSum(x2+k, y1, y2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ x2+=bk; A+=best; improved=true; continue;}\n            }\n            // bottom\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && y1-k>=0; k++){\n                    s += rowSum(y1-k, x1, x2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ y1-=bk; A+=best; improved=true; continue;}\n            }\n            // top\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && y2+k<MY; k++){\n                    s += rowSum(y2+k, x1, x2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ y2+=bk; A+=best; improved=true; continue;}\n            }\n            // contractions\n            // left\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && x1+k-1<=x2; k++){\n                    s += colSum(x1+k-1, y1, y2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ x1+=bk; A-=worst; improved=true; continue;}\n            }\n            // right\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && x2-k+1>=x1; k++){\n                    s += colSum(x2-k+1, y1, y2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ x2-=bk; A-=worst; improved=true; continue;}\n            }\n            // bottom\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && y1+k-1<=y2; k++){\n                    s += rowSum(y1+k-1, x1, x2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ y1+=bk; A-=worst; improved=true; continue;}\n            }\n            // top\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && y2-k+1>=y1; k++){\n                    s += rowSum(y2-k+1, x1, x2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ y2-=bk; A-=worst; improved=true; continue;}\n            }\n        }\n    };\n\n    struct Rect { int x1,x2,y1,y2,A; };\n    vector<Rect> cands;\n\n    mt19937_64 rng(1234567);\n\n    // 4) Global X-sliding windows at several widths\n    for(auto &ws : XSETS){\n        int K = ws.first, NI = ws.second;\n        int bestA = INT_MIN, bx1=0,bx2=0,by1=0,by2=0;\n        uniform_int_distribution<int> distL(0, max(0, MX - K));\n        vector<int> W(MY);\n        for(int it=0; it<NI; it++){\n            int L = (MX>K ? distL(rng):0);\n            fill(W.begin(), W.end(), 0);\n            int Rlim = min(MX, L+K);\n            for(int R=L; R<Rlim; R++){\n                for(auto &pr: binsX[R])\n                    W[pr.first] += pr.second;\n                // Kadane on W\n                int cur=W[0], t0=0, best=cur, sy=0, ey=0;\n                for(int y=1; y<MY; y++){\n                    if(cur>0) cur+=W[y];\n                    else { cur=W[y]; t0=y; }\n                    if(cur>best){ best=cur; sy=t0; ey=y; }\n                }\n                if(best>bestA){\n                    bestA=best;\n                    bx1=L; bx2=R;\n                    by1=sy; by2=ey;\n                }\n            }\n        }\n        if(bestA>INT_MIN/2){\n            cands.push_back({bx1,bx2,by1,by2,bestA});\n        }\n    }\n\n    // 5) One horizontal sliding window (height=HY)\n    {\n        int bestA = INT_MIN, hy1=0,hy2=0,hx1=0,hx2=0;\n        uniform_int_distribution<int> distY(0, max(0, MY-HY));\n        vector<int> W2(MX);\n        for(int it=0; it<NIY; it++){\n            int L = (MY>HY ? distY(rng):0);\n            fill(W2.begin(), W2.end(), 0);\n            int Rlim = min(MY, L+HY);\n            for(int R=L; R<Rlim; R++){\n                for(auto &pr: binsY[R])\n                    W2[pr.first] += pr.second;\n                // Kadane on W2\n                int cur=W2[0], t0=0, best=cur, sx=0, ex=0;\n                for(int x=1; x<MX; x++){\n                    if(cur>0) cur+=W2[x];\n                    else { cur=W2[x]; t0=x; }\n                    if(cur>best){ best=cur; sx=t0; ex=x; }\n                }\n                if(best>bestA){\n                    bestA=best;\n                    hy1=L; hy2=R;\n                    hx1=sx; hx2=ex;\n                }\n            }\n        }\n        if(bestA>INT_MIN/2){\n            cands.push_back({hx1,hx2,hy1,hy2,bestA});\n        }\n    }\n\n    // 6) Full-width & full-height stripes\n    // vertical stripe\n    {\n        vector<int> Wcol(MX);\n        for(int x=0; x<MX; x++)\n            Wcol[x] = bX_ps[x].empty() ? 0 : bX_ps[x].back();\n        int cur=Wcol[0], t0=0, best=cur, sx=0, ex=0;\n        for(int x=1; x<MX; x++){\n            if(cur>0) cur+=Wcol[x];\n            else { cur=Wcol[x]; t0=x; }\n            if(cur>best){ best=cur; sx=t0; ex=x; }\n        }\n        cands.push_back({sx,ex,0,MY-1,best});\n    }\n    // horizontal stripe\n    {\n        vector<int> Wrow(MY);\n        for(int y=0; y<MY; y++)\n            Wrow[y] = bY_ps[y].empty() ? 0 : bY_ps[y].back();\n        int cur=Wrow[0], t0=0, best=cur, sy=0, ey=0;\n        for(int y=1; y<MY; y++){\n            if(cur>0) cur+=Wrow[y];\n            else { cur=Wrow[y]; t0=y; }\n            if(cur>best){ best=cur; sy=t0; ey=y; }\n        }\n        cands.push_back({0,MX-1,sy,ey,best});\n    }\n\n    // 7) Coarse\u2192fine rectangle\n    static int cgrid[CG][CG];\n    int CW = (HMAX + CG) / CG;\n    for(int i=0;i<CG;i++) for(int j=0;j<CG;j++) cgrid[i][j]=0;\n    for(auto &p: pts){\n        int xi = min(CG-1, p.x / CW);\n        int yi = min(CG-1, p.y / CW);\n        cgrid[xi][yi] += p.w;\n    }\n    vector<int> tmpCG(CG);\n    int bestA2=INT_MIN, cx1=0,cx2=0,cy1=0,cy2=0;\n    for(int L=0; L<CG; L++){\n        fill(tmpCG.begin(), tmpCG.end(), 0);\n        for(int R=L; R<CG; R++){\n            for(int y=0; y<CG; y++)\n                tmpCG[y] += cgrid[R][y];\n            // Kadane\n            int cur=tmpCG[0], t0=0, best=cur, sy=0, ey=0;\n            for(int y=1; y<CG; y++){\n                if(cur>0) cur+=tmpCG[y];\n                else { cur=tmpCG[y]; t0=y; }\n                if(cur>best){ best=cur; sy=t0; ey=y; }\n            }\n            if(best>bestA2){\n                bestA2=best;\n                cx1=L; cx2=R;\n                cy1=sy; cy2=ey;\n            }\n        }\n    }\n    // refine inside that band\n    {\n        int X0 = cx1*CW, X1 = min(HMAX,(cx2+1)*CW-1);\n        int Y0 = cy1*CW, Y1 = min(HMAX,(cy2+1)*CW-1);\n        vector<Pt> sub; sub.reserve(2000);\n        for(auto &p: pts)\n            if(p.x>=X0 && p.x<=X1 && p.y>=Y0 && p.y<=Y1)\n                sub.push_back(p);\n        if(!sub.empty()){\n            vector<int> xs3, ys3;\n            xs3.reserve(sub.size()); ys3.reserve(sub.size());\n            for(auto &q: sub){\n                xs3.push_back(q.x);\n                ys3.push_back(q.y);\n            }\n            sort(xs3.begin(), xs3.end());\n            xs3.erase(unique(xs3.begin(), xs3.end()), xs3.end());\n            sort(ys3.begin(), ys3.end());\n            ys3.erase(unique(ys3.begin(), ys3.end()), ys3.end());\n            int RX = xs3.size(), RY = ys3.size();\n            vector<int> cqx(sub.size()), cqy(sub.size());\n            for(int i=0;i<(int)sub.size();i++){\n                cqx[i] = int(lower_bound(xs3.begin(), xs3.end(), sub[i].x)-xs3.begin());\n                cqy[i] = int(lower_bound(ys3.begin(), ys3.end(), sub[i].y)-ys3.begin());\n            }\n            vector<vector<pair<int,int>>> bX2(RX);\n            for(int i=0;i<(int)sub.size();i++){\n                bX2[cqx[i]].emplace_back(cqy[i], sub[i].w);\n            }\n            int bestA3=INT_MIN, rx1=0,rx2=0,ry1=0,ry2=0;\n            if(RX<=500){\n                vector<int> tmp(RY,0);\n                for(int L=0; L<RX; L++){\n                    fill(tmp.begin(), tmp.end(), 0);\n                    for(int R=L; R<RX; R++){\n                        for(auto &pr: bX2[R]) tmp[pr.first]+=pr.second;\n                        // Kadane\n                        int cur=tmp[0], t0=0, best=cur, sy=0, ey=0;\n                        for(int y=1; y<RY; y++){\n                            if(cur>0) cur+=tmp[y];\n                            else { cur=tmp[y]; t0=y; }\n                            if(cur>best){ best=cur; sy=t0; ey=y; }\n                        }\n                        if(best>bestA3){\n                            bestA3=best; rx1=L; rx2=R; ry1=sy; ry2=ey;\n                        }\n                    }\n                }\n            } else {\n                uniform_int_distribution<int> dist2(0, max(0, RX-HY));\n                vector<int> starts(NIY), tmp(RY);\n                for(int i=0;i<NIY;i++)\n                    starts[i] = (RX>HY ? dist2(rng) : 0);\n                for(int L: starts){\n                    fill(tmp.begin(), tmp.end(), 0);\n                    int Rlim = min(RX, L+HY);\n                    for(int R=L; R<Rlim; R++){\n                        for(auto &pr: bX2[R]) tmp[pr.first]+=pr.second;\n                        int cur=tmp[0], t0=0, best=cur, sy=0, ey=0;\n                        for(int y=1; y<RY; y++){\n                            if(cur>0) cur+=tmp[y];\n                            else { cur=tmp[y]; t0=y; }\n                            if(cur>best){ best=cur; sy=t0; ey=y; }\n                        }\n                        if(best>bestA3){\n                            bestA3=best; rx1=L; rx2=R; ry1=sy; ry2=ey;\n                        }\n                    }\n                }\n            }\n            if(bestA3>INT_MIN/2){\n                int gx1 = int(lower_bound(xs.begin(), xs.end(), xs3[rx1]) - xs.begin());\n                int gx2 = int(lower_bound(xs.begin(), xs.end(), xs3[rx2]) - xs.begin());\n                int gy1 = int(lower_bound(ys.begin(), ys.end(), ys3[ry1]) - ys.begin());\n                int gy2 = int(lower_bound(ys.begin(), ys.end(), ys3[ry2]) - ys.begin());\n                if(gx1<=gx2 && gy1<=gy2){\n                    int A3=0;\n                    for(int xx=gx1; xx<=gx2; xx++)\n                        A3 += colSum(xx, gy1, gy2);\n                    cands.push_back({gx1,gx2,gy1,gy2,A3});\n                }\n            }\n        }\n    }\n\n    // 8) Locally refine all candidates\n    for(auto &r : cands){\n        if(r.x1<=r.x2 && r.y1<=r.y2)\n            refineRect(r.x1, r.x2, r.y1, r.y2, r.A);\n    }\n\n    // 9) Pick best\n    int bestA=INT_MIN, bx1=0,bx2=0,by1=0,by2=0;\n    for(auto &r : cands){\n        if(r.A>bestA){\n            bestA=r.A;\n            bx1=r.x1; bx2=r.x2;\n            by1=r.y1; by2=r.y2;\n        }\n    }\n    // fallback\n    if(bestA<=0 || bx2<=bx1 || by2<=by1){\n        bx1=by1=0;\n        bx2=by2=1;\n    }\n\n    // 10) Output as 4-vertex rectangle\n    cout << 4 << \"\\n\";\n    cout << xs[bx1] << \" \" << ys[by1] << \"\\n\";\n    cout << xs[bx1] << \" \" << ys[by2] << \"\\n\";\n    cout << xs[bx2] << \" \" << ys[by2] << \"\\n\";\n    cout << xs[bx2] << \" \" << ys[by1] << \"\\n\";\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    ll sigma;\n    cin >> N >> T >> sigma;\n    vector<ll> w0(N), h0(N);\n    for(int i = 0; i < N; i++){\n        cin >> w0[i] >> h0[i];\n    }\n\n    // Treat the measured sizes as exact:\n    // orient each rectangle so that its \"width\" = min(w0,h0), \"height\" = max(w0,h0).\n    vector<ll> wi(N), hi(N);\n    ll totalW = 0;\n    for(int i = 0; i < N; i++){\n        wi[i] = min(w0[i], h0[i]);\n        hi[i] = max(w0[i], h0[i]);\n        totalW += wi[i];\n    }\n\n    // We'll try R = 1..N rows.  For each R, do a greedy fill of contiguous indices\n    // so each of the first R-1 rows accumulates at least one rect and tries not to\n    // exceed totalW/R, and the last row takes all remaining.  Compute\n    //   score(R) = max_row_width + sum_row_heights,\n    // pick the best R and remember its start/size arrays.\n    ll bestScore = LLONG_MAX;\n    int bestR = 1;\n    vector<int> bestStart, bestSize;\n\n    for(int R = 1; R <= N; R++){\n        ll target = totalW / R;\n        vector<int> start(R), sz(R);\n        int idx = 0;\n        for(int r = 0; r < R; r++){\n            start[r] = idx;\n            if(r == R - 1){\n                // last row: take all remaining\n                sz[r] = N - idx;\n                idx = N;\n            } else {\n                // ensure at least one\n                sz[r] = 1;\n                ll sum = wi[idx];\n                idx++;\n                // fill until target\n                while(idx < N && sum + wi[idx] <= target){\n                    sum += wi[idx];\n                    sz[r]++;\n                    idx++;\n                }\n            }\n        }\n        // compute score:\n        ll maxRowW = 0, sumRowH = 0;\n        for(int r = 0; r < R; r++){\n            ll wsum = 0, hmx = 0;\n            for(int i = start[r]; i < start[r] + sz[r]; i++){\n                wsum += wi[i];\n                hmx = max(hmx, hi[i]);\n            }\n            maxRowW = max(maxRowW, wsum);\n            sumRowH += hmx;\n        }\n        ll sc = maxRowW + sumRowH;\n        if(sc < bestScore){\n            bestScore = sc;\n            bestR = R;\n            bestStart = start;\n            bestSize  = sz;\n        }\n    }\n\n    // Build row[i] = which shelf the i-th rect belongs to,\n    // and rep[r] = the index of the tallest rect in row r (for alignment).\n    int R = bestR;\n    auto &start = bestStart;\n    auto &sz    = bestSize;\n    vector<int> row(N), rep(R);\n    for(int r = 0; r < R; r++){\n        int s = start[r], e = start[r] + sz[r];\n        int tallest = s;\n        for(int i = s; i < e; i++){\n            row[i] = r;\n            if(hi[i] > hi[tallest]) tallest = i;\n        }\n        rep[r] = tallest;\n    }\n\n    // Now output the SAME packing every turn:\n    //  - in row 0 we push 'U' from left to right\n    //  - in rows 1..R-1 we push 'L' aligned under rep[r-1]\n    for(int t = 0; t < T; t++){\n        cout << N << \"\\n\";\n        for(int i = 0; i < N; i++){\n            int rbit = (w0[i] > h0[i] ? 1 : 0);\n            int r = row[i];\n            char d; \n            int b;\n            if(r == 0){\n                // top shelf: push Up\n                d = 'U';\n                b = (i == 0 ? -1 : i - 1);\n            } else {\n                // lower shelf r: push Left under the tallest of shelf r-1\n                d = 'L';\n                b = rep[r - 1];\n            }\n            cout << i << \" \" << rbit << \" \" << d << \" \" << b << \"\\n\";\n        }\n        cout << flush;\n\n        // read back the noisy (W',H') to stay in sync\n        ll Wp, Hp;\n        if(!(cin >> Wp >> Hp)) break;\n    }\n\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, H;\n    cin >> N >> M >> H;\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    // skip coordinates\n    for(int i = 0; i < N; i++){\n        int x,y; \n        cin >> x >> y;\n    }\n\n    // ----------------------------------------------------------------\n    // 1) Precompute for each r the list of (v,dist) within H and\n    //    staticScore[r] = sum (dist+1)*A[v].\n    // ----------------------------------------------------------------\n    vector<vector<pair<int,uint8_t>>> reach(N);\n    vector<ll> staticScore(N,0);\n    vector<int> q(N), dist(N,-1);\n\n    for(int r = 0; r < N; r++){\n        int ql=0, qr=0;\n        dist[r]=0; q[qr++]=r;\n        while(ql<qr){\n            int u=q[ql++];\n            if(dist[u]==H) continue;\n            for(int w: adj[u]){\n                if(dist[w]==-1){\n                    dist[w]=dist[u]+1;\n                    q[qr++]=w;\n                }\n            }\n        }\n        ll sc=0;\n        reach[r].reserve(qr);\n        for(int i=0;i<qr;i++){\n            int v=q[i];\n            int d=dist[v];\n            reach[r].emplace_back(v,(uint8_t)d);\n            sc += ll(d+1)*A[v];\n            dist[v]=-1;\n        }\n        staticScore[r]=sc;\n    }\n    // sort vertices by staticScore descending\n    vector<int> staticCand(N);\n    iota(staticCand.begin(), staticCand.end(), 0);\n    sort(staticCand.begin(), staticCand.end(),\n         [&](int i, int j){ return staticScore[i]>staticScore[j]; });\n\n    // ----------------------------------------------------------------\n    // Multi\u2010start greedy parameters\n    // ----------------------------------------------------------------\n    const int RUNS = 10;    // number of independent greedy tries\n    const int S     = 20;   // how many top static\u2010roots to consider per step\n    const int K     = 3;    // pick among top\u2010K dynamic scores\n\n    mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());\n\n    vector<int> bestParent(N), bestDepth(N);\n    ll bestGlobalScore = -1;\n\n    // temp arrays for one run\n    vector<char> covered(N);\n    vector<int> parent(N), depth(N), dist2(N), q2(N);\n\n    for(int run=0; run<RUNS; run++){\n        // reset\n        fill(covered.begin(), covered.end(), 0);\n        fill(parent.begin(), parent.end(), -1);\n        fill(depth.begin(), depth.end(), 0);\n        int remaining = N;\n\n        // greedy cover\n        while(remaining>0){\n            // collect top\u2010S uncovered static candidates\n            static int candListArr[50];\n            int csz=0;\n            for(int r: staticCand){\n                if(!covered[r]){\n                    candListArr[csz++] = r;\n                    if(csz==S) break;\n                }\n            }\n            // evaluate dynamicScore for these\n            static ll dynScoreArr[50];\n            for(int i=0;i<csz;i++){\n                int r = candListArr[i];\n                ll sc=0;\n                for(auto &pr: reach[r]){\n                    int v=pr.first, d=pr.second;\n                    if(!covered[v]) sc += ll(d+1)*A[v];\n                }\n                dynScoreArr[i]=sc;\n            }\n            // sort candListArr[0..csz) by dynScoreArr descending (partial sort)\n            array<int,50> idx;\n            for(int i=0;i<csz;i++) idx[i]=i;\n            sort(idx.begin(), idx.begin()+csz,\n                 [&](int i,int j){ return dynScoreArr[i]>dynScoreArr[j]; });\n\n            // pick one\n            int pickIdx;\n            if(run==0){\n                // pure greedy on first run\n                pickIdx = idx[0];\n            } else {\n                // random among top\u2010K\n                int limit = min(K, csz);\n                uniform_int_distribution<int> dist(0, limit-1);\n                pickIdx = idx[ dist(rng) ];\n            }\n            int root = candListArr[pickIdx];\n\n            // BFS from root on uncovered to carve out a tree of height \u2264H\n            fill(dist2.begin(), dist2.end(), -1);\n            int ql=0, qr=0;\n            dist2[root]=0;\n            parent[root] = -1;\n            depth[root]  = 0;\n            covered[root]=1;\n            q2[qr++]=root;\n            --remaining;\n            while(ql<qr){\n                int u=q2[ql++];\n                if(dist2[u]==H) continue;\n                for(int w: adj[u]){\n                    if(!covered[w] && dist2[w]==-1){\n                        dist2[w]=dist2[u]+1;\n                        parent[w]=u;\n                        depth[w]=dist2[w];\n                        covered[w]=1;\n                        q2[qr++]=w;\n                        --remaining;\n                    }\n                }\n            }\n        }\n\n        // score this run\n        ll runScore=0;\n        for(int v=0;v<N;v++){\n            runScore += ll(depth[v]+1)*A[v];\n        }\n        if(runScore > bestGlobalScore){\n            bestGlobalScore = runScore;\n            bestParent = parent;\n            bestDepth  = depth;\n        }\n    }\n\n    // ----------------------------------------------------------------\n    // Build child counts & roots for best solution\n    // ----------------------------------------------------------------\n    vector<int> childrenCount(N,0), rootOf(N,-1);\n    vector<vector<int>> children(N);\n    for(int v=0;v<N;v++){\n        int p = bestParent[v];\n        if(p>=0){\n            childrenCount[p]++;\n            children[p].push_back(v);\n        }\n    }\n    // assign root labels by BFS from each root\n    for(int v=0;v<N;v++){\n        if(bestParent[v]==-1){\n            deque<int> dq;\n            dq.push_back(v);\n            rootOf[v]=v;\n            while(!dq.empty()){\n                int u=dq.front(); dq.pop_front();\n                for(int c: children[u]){\n                    rootOf[c]=v;\n                    dq.push_back(c);\n                }\n            }\n        }\n    }\n\n    // ----------------------------------------------------------------\n    // Leaf\u2010shifting local search on best solution\n    // ----------------------------------------------------------------\n    bool improved=true;\n    while(improved){\n        improved=false;\n        ll bestGain=0;\n        int  bestV=-1, bestU=-1, oldP=-1;\n        for(int v=0;v<N;v++){\n            if(bestParent[v]>=0 && childrenCount[v]==0){\n                int dv = bestDepth[v];\n                for(int u: adj[v]){\n                    // must be different tree and within depth\u2010limit\n                    if(rootOf[u]==rootOf[v]) continue;\n                    if(bestDepth[u]+1 > H) continue;\n                    ll gain = ll(bestDepth[u] - dv + 1) * A[v];\n                    if(gain > bestGain){\n                        bestGain = gain;\n                        bestV = v;\n                        bestU = u;\n                        oldP  = bestParent[v];\n                    }\n                }\n            }\n        }\n        if(bestGain>0){\n            // apply the best leaf\u2010shift\n            improved = true;\n            childrenCount[oldP]--;\n            childrenCount[bestU]++;\n            bestParent[bestV] = bestU;\n            bestDepth [bestV] = bestDepth[bestU] + 1;\n            rootOf   [bestV] = rootOf[bestU];\n        }\n    }\n\n    // ----------------------------------------------------------------\n    // Output final parent pointers\n    // ----------------------------------------------------------------\n    for(int i=0;i<N;i++){\n        cout << bestParent[i] << (i+1==N?'\\n':' ');\n    }\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\nusing ull = unsigned long long;\n\nstruct Segment {\n    char dir;            // 'L','R','U','D'\n    int idx, k, cost;    // cost = 2*k\n    vector<int> cover;   // list of Oni IDs\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<string> B(N);\n    for(int i = 0; i < N; i++){\n        cin >> B[i];\n    }\n\n    // 1) Gather Oni positions and assign them IDs 0..M-1\n    vector<pair<int,int>> oni_pos;\n    oni_pos.reserve(2*N);\n    vector<vector<int>> pos2id(N, vector<int>(N,-1));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(B[i][j]=='x'){\n                int id = oni_pos.size();\n                oni_pos.emplace_back(i,j);\n                pos2id[i][j] = id;\n            }\n        }\n    }\n    int M = oni_pos.size();  // should be 2N = 40\n\n    // 2) For each row/col, find nearest 'o'\n    const int INF = 1<<20;\n    vector<int> row_min_o(N,INF), row_max_o(N,-INF);\n    vector<int> col_min_o(N,INF), col_max_o(N,-INF);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(B[i][j]=='o'){\n                row_min_o[i] = min(row_min_o[i], j);\n                row_max_o[i] = max(row_max_o[i], j);\n                col_min_o[j] = min(col_min_o[j], i);\n                col_max_o[j] = max(col_max_o[j], i);\n            }\n        }\n    }\n\n    // 3) Build exactly one *minimal* segment per Oni per clear direction\n    //    and dedupe via a small hash\u2010key.\n    auto dir_code = [&](char d){\n        return (d=='L'?0:(d=='R'?1:(d=='U'?2:3)));\n    };\n    unordered_map<int,int> seg_map;\n    seg_map.reserve(M*4);\n    vector<Segment> segs;\n    segs.reserve(M*4);\n\n    auto add_seg = [&](char d, int idx, int k){\n        int dc = dir_code(d);\n        int key = ((dc*N + idx)*(N+1)) + k;\n        if(!seg_map.count(key)){\n            seg_map[key] = (int)segs.size();\n            segs.push_back({d, idx, k, 2*k, {}});\n        }\n    };\n\n    for(int id = 0; id < M; id++){\n        auto [i,j] = oni_pos[id];\n        if(row_min_o[i] > j) add_seg('L', i, j+1);\n        if(row_max_o[i] < j) add_seg('R', i, N-j);\n        if(col_min_o[j] > i) add_seg('U', j, i+1);\n        if(col_max_o[j] < i) add_seg('D', j, N-i);\n    }\n\n    // 4) Build each segment's cover\u2010list *and* a 64\u2010bit mask\n    int S = segs.size();\n    vector<ull> segMask(S, 0);\n    for(int s = 0; s < S; s++){\n        auto &sg = segs[s];\n        if(sg.dir=='L'){\n            for(int c=0;c<sg.k;c++){\n                int id = pos2id[sg.idx][c];\n                if(id>=0){\n                    sg.cover.push_back(id);\n                    segMask[s] |= (1ULL<<id);\n                }\n            }\n        } else if(sg.dir=='R'){\n            for(int c=N-sg.k;c<N;c++){\n                int id = pos2id[sg.idx][c];\n                if(id>=0){\n                    sg.cover.push_back(id);\n                    segMask[s] |= (1ULL<<id);\n                }\n            }\n        } else if(sg.dir=='U'){\n            for(int r=0;r<sg.k;r++){\n                int id = pos2id[r][sg.idx];\n                if(id>=0){\n                    sg.cover.push_back(id);\n                    segMask[s] |= (1ULL<<id);\n                }\n            }\n        } else { // 'D'\n            for(int r=N-sg.k;r<N;r++){\n                int id = pos2id[r][sg.idx];\n                if(id>=0){\n                    sg.cover.push_back(id);\n                    segMask[s] |= (1ULL<<id);\n                }\n            }\n        }\n    }\n\n    // 5) Randomized\u2010greedy + prune + MERGE\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    vector<char> used(S);\n    vector<int>  cov_cnt(M);\n    vector<double> randf(S);\n\n    int best_cost = INT_MAX;\n    vector<tuple<char,int,int>> best_sol;\n\n    const int REPS = 2000;    // we can afford a few thousand reps at N=20\n\n    for(int rep=0; rep<REPS; rep++){\n        // set up randomized weights (or 1.0 in the first pass)\n        if(rep==0){\n            fill(randf.begin(), randf.end(), 1.0);\n        } else {\n            for(int s=0;s<S;s++){\n                int r = int(rng()%1001);    // [0..1000]\n                randf[s] = 1.0 + (r - 500)/5000.0;  // in [0.9,1.1]\n            }\n        }\n\n        // greedy cover in O(S) per pick via popcount\n        fill(used.begin(), used.end(), 0);\n        ull coveredMask = 0;\n        vector<int> choice; \n        choice.reserve(M);\n\n        while(__builtin_popcountll(coveredMask) < M){\n            double bestR = -1;\n            int bestS = -1;\n            ull inv = ~coveredMask;\n            for(int s=0;s<S;s++){\n                if(used[s]) continue;\n                ull nb = segMask[s] & inv;\n                int newc = __builtin_popcountll(nb);\n                if(newc==0) continue;\n                double r = newc * randf[s] / segs[s].cost;\n                if(r > bestR){\n                    bestR = r;\n                    bestS = s;\n                }\n            }\n            if(bestS<0) break;   // cannot cover more (shouldn\u2019t happen)\n            used[bestS]=1;\n            coveredMask |= segMask[bestS];\n            choice.push_back(bestS);\n        }\n        if(__builtin_popcountll(coveredMask) < M) \n            continue;  // failed this rep\n\n        // 5a) prune *fully* redundant segments\n        fill(cov_cnt.begin(), cov_cnt.end(), 0);\n        for(int s: choice)\n            for(int id: segs[s].cover)\n                cov_cnt[id]++;\n\n        vector<int> pruned;\n        pruned.reserve(choice.size());\n        for(int s: choice){\n            bool red = true;\n            for(int id: segs[s].cover){\n                if(cov_cnt[id] <= 1){ \n                    red = false; \n                    break;\n                }\n            }\n            if(red){\n                for(int id: segs[s].cover)\n                    cov_cnt[id]--;\n            } else {\n                pruned.push_back(s);\n            }\n        }\n\n        // 5b) MERGE any segments with the same (dir,idx)\n        //     keep only one of length = max k\n        vector<int> best_k(4*N, 0);\n        for(int s: pruned){\n            int dc = dir_code(segs[s].dir);\n            int key = dc*N + segs[s].idx;\n            best_k[key] = max(best_k[key], segs[s].k);\n        }\n\n        // 5c) assemble the merged solution & cost\n        int cost = 0;\n        vector<tuple<char,int,int>> sol;\n        sol.reserve(pruned.size());\n        for(int key=0; key<4*N; key++){\n            int k = best_k[key];\n            if(k>0){\n                cost += 2*k;\n                int dc = key / N, idx = key % N;\n                char d = (dc==0?'L': dc==1?'R': dc==2?'U':'D');\n                sol.emplace_back(d, idx, k);\n            }\n        }\n\n        if(cost < best_cost){\n            best_cost = cost;\n            best_sol = move(sol);\n        }\n    }\n\n    // 6) Emit the final best\n    auto opposite = [&](char d){\n        if(d=='L') return 'R';\n        if(d=='R') return 'L';\n        if(d=='U') return 'D';\n        return 'U';\n    };\n    vector<pair<char,int>> ops;\n    ops.reserve(best_sol.size()*N);\n    for(auto &t: best_sol){\n        char d; int idx,k;\n        tie(d,idx,k) = t;\n        for(int i=0;i<k;i++) ops.emplace_back(d, idx);\n        char od = opposite(d);\n        for(int i=0;i<k;i++) ops.emplace_back(od, idx);\n    }\n    for(auto &p: ops){\n        cout << p.first << \" \" << p.second << \"\\n\";\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    long long L;\n    cin >> N >> L;\n    vector<long long> T(N);\n    for(int i = 0; i < N; i++){\n        cin >> T[i];\n    }\n\n    // Baseline: one big cycle of length N.\n    // We set a[i] = b[i] = (i+1)%N so that the walker cycles\n    // around 0\u21921\u21922\u2192...\u2192N-1\u21920\u2192...\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;\nusing ll = long long;\n\n// Hilbert\u2010curve mapping of (x,y) in [0,2^bits)\n// into a 2*bits\u2010bit key.  Improves spatial locality.\nstatic inline uint64_t hilbertOrder(int x, int y, int bits = 14) {\n    uint64_t d = 0;\n    for(int s = bits - 1; s >= 0; s--) {\n        uint64_t rx = (x >> s) & 1;\n        uint64_t ry = (y >> s) & 1;\n        d = (d << 2) | ((rx << 1) | (rx ^ ry));\n        if(ry == 0) {\n            if(rx == 1) {\n                x = ((1<<bits) - 1) ^ x;\n                y = ((1<<bits) - 1) ^ y;\n            }\n            std::swap(x, y);\n        }\n    }\n    return d;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for(int i = 0; i < M; i++) cin >> G[i];\n    vector<int> lx(N), rx(N), ly(N), ry(N);\n    for(int i = 0; i < N; i++){\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n\n    // 1) Compute centers (integers in [0..10000]) for ordering\n    vector<int> cx(N), cy(N);\n    for(int i = 0; i < N; i++){\n        cx[i] = (lx[i] + rx[i]) >> 1;\n        cy[i] = (ly[i] + ry[i]) >> 1;\n    }\n\n    // 2) Sort all cities by their Hilbert\u2010curve key\n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    vector<uint64_t> key(N);\n    for(int i = 0; i < N; i++){\n        key[i] = hilbertOrder(cx[i], cy[i], 14);\n    }\n    sort(idx.begin(), idx.end(), [&](int a, int b){\n        return key[a] < key[b];\n    });\n\n    // 3) Slice into the prescribed group\u2010sizes G[0],G[1],...\n    vector<vector<int>> groups(M);\n    {\n        int p = 0;\n        for(int k = 0; k < M; k++){\n            groups[k].reserve(G[k]);\n            for(int t = 0; t < G[k]; t++){\n                groups[k].push_back(idx[p++]);\n            }\n        }\n    }\n\n    // Collect the final edges here:\n    vector<vector<pair<int,int>>> answer_edges(M);\n    int remQ = Q;\n\n    // A simple Prim fallback in case we ever run out of queries.\n    auto prim_on_centers = [&](int k){\n        auto &g = groups[k];\n        int K = (int)g.size();\n        if(K <= 1) return;\n        vector<bool> in_mst(K,false);\n        vector<double> dist(K,1e18);\n        vector<int> par(K,-1);\n        dist[0] = 0;\n        for(int it=0; it<K; it++){\n            int u=-1; double best=1e18;\n            for(int i=0;i<K;i++){\n                if(!in_mst[i] && dist[i]<best){\n                    best=dist[i]; u=i;\n                }\n            }\n            in_mst[u]=true;\n            if(par[u]!=-1){\n                answer_edges[k].emplace_back(g[u], g[par[u]]);\n            }\n            for(int v=0;v<K;v++){\n                if(in_mst[v]) continue;\n                double dx = cx[g[u]] - cx[g[v]];\n                double dy = cy[g[u]] - cy[g[v]];\n                double d = floor(sqrt(dx*dx + dy*dy));\n                if(d < dist[v]){\n                    dist[v]=d;\n                    par[v]=u;\n                }\n            }\n        }\n    };\n\n    // 4) For each group, either query windows or fallback\n    for(int k = 0; k < M; k++){\n        auto &g = groups[k];\n        int K = (int)g.size();\n        if(K <= 1) continue;\n\n        // how many queries we need\n        int need = (K <= L\n                    ? 1\n                    : ( (K + L - 3) / (L - 1) )  // ceil((K-1)/(L-1)) = (K+L-3)/(L-1)\n                   );\n        if(remQ >= need){\n            int step = L - 1;\n            // issue exactly 'need' windows\n            for(int j = 0; j < need; j++){\n                int start = j * step;\n                int end = min(start + L, K);\n                int sz = end - start;  // guaranteed >= 2\n                cout << \"? \" << sz;\n                for(int t = start; t < end; t++){\n                    cout << ' ' << g[t];\n                }\n                cout << \"\\n\" << flush;\n                remQ--;\n\n                // read sz-1 edges\n                for(int e = 0; e < sz - 1; e++){\n                    int a, b;\n                    cin >> a >> b;\n                    answer_edges[k].emplace_back(a, b);\n                }\n            }\n        } else {\n            // fallback to approximate MST\n            prim_on_centers(k);\n        }\n    }\n\n    // 5) Output the final solution\n    cout << \"!\\n\";\n    for(int k = 0; k < M; k++){\n        // cities in group k\n        for(int i = 0; i < (int)groups[k].size(); i++){\n            if(i) cout << ' ';\n            cout << groups[k][i];\n        }\n        cout << \"\\n\";\n        // the (G[k] - 1) edges\n        for(auto &e : answer_edges[k]){\n            cout << e.first << \" \" << e.second << \"\\n\";\n        }\n    }\n    cout << flush;\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    cin >> N >> M;\n    vector<pair<int,int>> pts(M);\n    for(int i = 0; i < M; i++){\n        cin >> pts[i].first >> pts[i].second;\n    }\n    int ci = pts[0].first, cj = pts[0].second;\n    vector<pair<char,char>> ans;\n    const int INF = 1e9;\n\n    for(int k = 1; k < M; k++){\n        int ti = pts[k].first;\n        int tj = pts[k].second;\n        int di = ti - ci;\n        int dj = tj - cj;\n        int costVM = abs(di);\n        int costHM = abs(dj);\n        int costVS = INF, costHS = INF;\n\n        // cost of sliding vertically via boundary then back\n        if(di > 0){\n            // slide down to row N-1, then move up to ti\n            costVS = 1 + ((N-1) - ti);\n        } else if(di < 0){\n            // slide up to row 0, then move down to ti\n            costVS = 1 + ti;\n        }\n        // cost of sliding horizontally via boundary then back\n        if(dj > 0){\n            // slide right to col N-1, then move left to tj\n            costHS = 1 + ((N-1) - tj);\n        } else if(dj < 0){\n            // slide left to col 0, then move right to tj\n            costHS = 1 + tj;\n        }\n\n        bool useV = costVS < costVM;\n        bool useH = costHS < costHM;\n\n        // First do horizontal phase\n        if(useH){\n            if(dj > 0){\n                ans.emplace_back('S','R');\n                int moves = (N-1) - tj;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','L');\n                }\n            } else {\n                // dj<0\n                ans.emplace_back('S','L');\n                int moves = tj;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','R');\n                }\n            }\n            cj = tj;\n        } else {\n            // simple moves\n            if(dj > 0){\n                for(int t = 0; t < dj; t++){\n                    ans.emplace_back('M','R');\n                }\n            } else if(dj < 0){\n                for(int t = 0; t < -dj; t++){\n                    ans.emplace_back('M','L');\n                }\n            }\n            cj = tj;\n        }\n\n        // Then do vertical phase\n        if(useV){\n            if(di > 0){\n                ans.emplace_back('S','D');\n                int moves = (N-1) - ti;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','U');\n                }\n            } else {\n                // di<0\n                ans.emplace_back('S','U');\n                int moves = ti;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','D');\n                }\n            }\n            ci = ti;\n        } else {\n            // simple moves\n            if(di > 0){\n                for(int t = 0; t < di; t++){\n                    ans.emplace_back('M','D');\n                }\n            } else if(di < 0){\n                for(int t = 0; t < -di; t++){\n                    ans.emplace_back('M','U');\n                }\n            }\n            ci = ti;\n        }\n    }\n\n    // Output all actions\n    for(auto &ac : ans){\n        cout << ac.first << \" \" << ac.second << \"\\n\";\n    }\n    return 0;\n}"},"8":{"ahc001":"#include <bits/stdc++.h>\n#include <chrono>\nusing namespace std;\n\n// A half\u2010open free rectangle [x1,x2)\u00d7[y1,y2)\nstruct Rect { int x1,y1,x2,y2; };\n\n// If a and b share a full edge, merge them into o and return true.\ninline bool canMerge(const Rect &a, const Rect &b, Rect &o) {\n    // vertical\n    if(a.x1==b.x1 && a.x2==b.x2) {\n        if(a.y2==b.y1){ o={a.x1,a.y1,a.x2,b.y2}; return true; }\n        if(b.y2==a.y1){ o={a.x1,b.y1,a.x2,a.y2}; return true; }\n    }\n    // horizontal\n    if(a.y1==b.y1 && a.y2==b.y2) {\n        if(a.x2==b.x1){ o={a.x1,a.y1,b.x2,a.y2}; return true; }\n        if(b.x2==a.x1){ o={b.x1,a.y1,a.x2,a.y2}; return true; }\n    }\n    return false;\n}\n\n// Morton\u2010(Z\u2010)order key for (x,y) with up to 14 bits each (0..9999)\nstatic inline uint32_t mortonKey(int x, int y) {\n    uint32_t m=0;\n    for(int i=0;i<14;i++){\n        m |= ((x>>i)&1u) << (2*i+1);\n        m |= ((y>>i)&1u) << (2*i);\n    }\n    return m;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n; \n    cin>>n;\n    vector<int> x(n), y(n);\n    vector<long long> r(n);\n    for(int i=0;i<n;i++){\n        cin>>x[i]>>y[i]>>r[i];\n    }\n\n    // 1) Build a richer list of (w,h) \u2248 sqrt(r_i) with \u00b11,\u00b12 perturbations:\n    vector<vector<pair<int,int>>> dims0(n);\n    for(int i=0;i<n;i++){\n        long long ri=r[i];\n        int w0=int(floor(sqrt((long double)ri)));\n        while(1LL*w0*w0>ri) --w0;\n        while(1LL*(w0+1)*(w0+1)<=ri) ++w0;\n        w0 = max(1, min(w0,10000));\n        int h0 = int((ri + w0 - 1)/w0);\n        if(h0>10000){\n            h0=10000;\n            w0=int((ri+h0-1)/h0);\n        }\n        auto &D=dims0[i];\n        // core\n        D.emplace_back(w0,h0);\n        if(h0!=w0) D.emplace_back(h0,w0);\n        // square\n        D.emplace_back(w0,w0);\n        // \u00b11,\u00b12 in w\n        for(int d=-2;d<=2;d++){\n            if(d==0) continue;\n            int w=w0+d;\n            if(w<1||w>10000) continue;\n            int h=int((ri+w-1)/w);\n            if(h>10000) continue;\n            D.emplace_back(w,h);\n        }\n        // \u00b11,\u00b12 in h\n        for(int d=-2;d<=2;d++){\n            if(d==0) continue;\n            int h=h0+d;\n            if(h<1||h>10000) continue;\n            int w=int((ri+h-1)/h);\n            if(w>10000) continue;\n            D.emplace_back(w,h);\n        }\n        sort(D.begin(), D.end());\n        D.erase(unique(D.begin(), D.end()), D.end());\n    }\n\n    // 2) Prepare base list and 10 static order\u2010variants (8 old + 2 Morton)\n    vector<int> base(n);\n    iota(base.begin(), base.end(), 0);\n    vector<vector<int>> orderVars;\n    orderVars.reserve(10);\n\n    // (a) r desc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){ return r[a]>r[b]; });\n        orderVars.push_back(o);\n    }\n    // (b) r desc, x asc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]>r[b];\n                 return x[a]<x[b];\n             });\n        orderVars.push_back(o);\n    }\n    // (c) r desc, y asc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]>r[b];\n                 return y[a]<y[b];\n             });\n        orderVars.push_back(o);\n    }\n    // (d) r desc, dist\u2192center asc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]>r[b];\n                 long long da=(x[a]-5000LL)*(x[a]-5000LL)\n                             +(y[a]-5000LL)*(y[a]-5000LL);\n                 long long db=(x[b]-5000LL)*(x[b]-5000LL)\n                             +(y[b]-5000LL)*(y[b]-5000LL);\n                 return da<db;\n             });\n        orderVars.push_back(o);\n    }\n    // (e) one random shuffle\n    {\n        auto o=base;\n        mt19937_64 tmp(7126871263ULL);\n        shuffle(o.begin(), o.end(), tmp);\n        orderVars.push_back(o);\n    }\n    // (f) r asc (small\u2010first)\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){ return r[a]<r[b]; });\n        orderVars.push_back(o);\n    }\n    // (g) r asc, x asc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]<r[b];\n                 return x[a]<x[b];\n             });\n        orderVars.push_back(o);\n    }\n    // (h) r asc, y asc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]<r[b];\n                 return y[a]<y[b];\n             });\n        orderVars.push_back(o);\n    }\n    // (i) Morton\u2010asc\n    {\n        vector<pair<uint32_t,int>> tmp;\n        tmp.reserve(n);\n        for(int i=0;i<n;i++) tmp.emplace_back(mortonKey(x[i],y[i]),i);\n        sort(tmp.begin(), tmp.end());\n        vector<int> o(n);\n        for(int i=0;i<n;i++) o[i]=tmp[i].second;\n        orderVars.push_back(o);\n    }\n    // (j) Morton\u2010desc\n    {\n        vector<pair<uint32_t,int>> tmp;\n        tmp.reserve(n);\n        for(int i=0;i<n;i++) tmp.emplace_back(mortonKey(x[i],y[i]),i);\n        sort(tmp.begin(), tmp.end(), greater<>());\n        vector<int> o(n);\n        for(int i=0;i<n;i++) o[i]=tmp[i].second;\n        orderVars.push_back(o);\n    }\n\n    int V = int(orderVars.size());\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_real_distribution<double> P2(0.0,0.30);\n    vector<double> pick2(V);\n    for(int i=0;i<V;i++) pick2[i]=P2(rng);\n\n    // workspace\n    vector<array<int,4>> bestAns(n), ans(n);\n    double bestScore=-1;\n    vector<Rect> freeRects;\n    freeRects.reserve(2000);\n\n    auto removeRect=[&](int i){\n        freeRects[i]=freeRects.back();\n        freeRects.pop_back();\n    };\n    auto addFree=[&](Rect R){\n        if(R.x1>=R.x2||R.y1>=R.y2) return;\n        bool again=true;\n        while(again){\n            again=false;\n            for(int i=0;i<(int)freeRects.size();i++){\n                Rect M;\n                if(canMerge(R, freeRects[i], M)){\n                    removeRect(i);\n                    R=M;\n                    again=true;\n                    break;\n                }\n            }\n        }\n        freeRects.push_back(R);\n    };\n\n    struct Cand{int ridx,w,h,L,Rg,D,U,waste,area;};\n    struct Fb {int j,w,h,L,Rg,D,U;};\n\n    // Single greedy+fallback pass\n    auto doRun = [&](const vector<int> &order, double p2){\n        freeRects.clear();\n        freeRects.push_back({0,0,10000,10000});\n        for(int idx: order){\n            long long ri=r[idx];\n            int xi=x[idx], yi=y[idx];\n            // collect guillotine fits\n            vector<Cand> cands;\n            cands.reserve(dims0[idx].size()*freeRects.size());\n            for(auto &wh: dims0[idx]){\n                int w=wh.first, h=wh.second;\n                for(int j=0;j<(int)freeRects.size();j++){\n                    auto &F=freeRects[j];\n                    int Rw=F.x2-F.x1, Rh=F.y2-F.y1;\n                    if(Rw<w||Rh<h) continue;\n                    int L=max(F.x1, xi-w+1), Rg=min(xi, F.x2-w);\n                    if(L>Rg) continue;\n                    int D=max(F.y1, yi-h+1), U=min(yi, F.y2-h);\n                    if(D>U) continue;\n                    int A=Rw*Rh;\n                    cands.push_back({j,w,h,L,Rg,D,U,A - w*h, A});\n                }\n            }\n            if(!cands.empty()){\n                // pick best & 2nd-best by (waste,area)\n                int b0=0, b1=-1;\n                int w0=cands[0].waste, A0=cands[0].area;\n                for(int i=1;i<(int)cands.size();i++){\n                    int wi=cands[i].waste, Ai=cands[i].area;\n                    if(wi<w0 || (wi==w0 && Ai<A0)){\n                        b1=b0; b0=i; w0=wi; A0=Ai;\n                    } else if(b1<0){\n                        b1=i;\n                    } else {\n                        int w1=cands[b1].waste, A1=cands[b1].area;\n                        if(wi<w1 || (wi==w1 && Ai<A1)){\n                            b1=i;\n                        }\n                    }\n                }\n                int pick=b0;\n                if(b1>=0 && (rng()%10000)<int(p2*10000.0)) pick=b1;\n                auto &c=cands[pick];\n                int a0=xi - c.w/2; a0=min(max(a0,c.L),c.Rg);\n                int b0y=yi - c.h/2; b0y=min(max(b0y,c.D),c.U);\n                ans[idx]={a0,b0y,a0+c.w,b0y+c.h};\n                // carve it out\n                Rect F=freeRects[c.ridx];\n                removeRect(c.ridx);\n                addFree({F.x1,      F.y1,    a0,       F.y2});\n                addFree({a0+c.w,    F.y1,    F.x2,     F.y2});\n                addFree({a0,        F.y1,    a0+c.w,   b0y});\n                addFree({a0,        b0y+c.h, a0+c.w,   F.y2});\n            } else {\n                // improved 1D fallback\n                double bestR=-1;\n                Fb bestFb{};\n                for(int j=0;j<(int)freeRects.size();j++){\n                    auto &F=freeRects[j];\n                    if(!(F.x1<=xi&&xi<F.x2&&F.y1<=yi&&yi<F.y2))\n                        continue;\n                    int Rw=F.x2-F.x1, Rh=F.y2-F.y1;\n                    // vary width\n                    if(Rh>0){\n                        for(int t=-1;t<=1;t+=2){\n                            long long w = (t<0? ri/Rh : (ri+Rh-1)/Rh);\n                            if(w<1||w>Rw) continue;\n                            int W=int(w), H=Rh;\n                            int L0=max(F.x1, xi-W+1), Rg0=min(xi, F.x2-W);\n                            int D0=max(F.y1, yi-H+1), U0=min(yi, F.y2-H);\n                            if(L0>Rg0||D0>U0) continue;\n                            double rat = (t<0? double(W*1LL*H)/ri : double(ri)/double(W*1LL*H));\n                            if(rat>bestR){\n                                bestR=rat;\n                                bestFb={j,W,H,L0,Rg0,D0,U0};\n                            }\n                        }\n                    }\n                    // vary height\n                    if(Rw>0){\n                        for(int t=-1;t<=1;t+=2){\n                            long long h = (t<0? ri/Rw : (ri+Rw-1)/Rw);\n                            if(h<1||h>Rh) continue;\n                            int W=Rw, H=int(h);\n                            int L0=max(F.x1, xi-W+1), Rg0=min(xi, F.x2-W);\n                            int D0=max(F.y1, yi-H+1), U0=min(yi, F.y2-H);\n                            if(L0>Rg0||D0>U0) continue;\n                            double rat = (t<0? double(W*1LL*H)/ri : double(ri)/double(W*1LL*H));\n                            if(rat>bestR){\n                                bestR=rat;\n                                bestFb={j,W,H,L0,Rg0,D0,U0};\n                            }\n                        }\n                    }\n                }\n                if(bestR>0){\n                    int j=bestFb.j, W=bestFb.w, H=bestFb.h;\n                    int a0=xi-W/2;  a0=min(max(a0,bestFb.L),bestFb.Rg);\n                    int b0y=yi-H/2; b0y=min(max(b0y,bestFb.D),bestFb.U);\n                    ans[idx]={a0,b0y,a0+W,b0y+H};\n                    Rect F=freeRects[j];\n                    removeRect(j);\n                    addFree({F.x1,      F.y1,    a0,       F.y2});\n                    addFree({a0+W,      F.y1,    F.x2,     F.y2});\n                    addFree({a0,        F.y1,    a0+W,     b0y});\n                    addFree({a0,        b0y+H,   a0+W,     F.y2});\n                } else {\n                    // final 1\u00d71\n                    Rect F=freeRects.back();\n                    removeRect((int)freeRects.size()-1);\n                    int a0=F.x1, b0y=F.y1;\n                    ans[idx]={a0,b0y,a0+1,b0y+1};\n                    addFree({F.x1,      F.y1,    a0,       F.y2});\n                    addFree({a0+1,      F.y1,    F.x2,     F.y2});\n                    addFree({a0,        F.y1,    a0+1,     b0y});\n                    addFree({a0,        b0y+1,   a0+1,     F.y2});\n                }\n            }\n        }\n        // evaluate\n        double S=0;\n        for(int i=0;i<n;i++){\n            auto &rc=ans[i];\n            if(rc[0]<=x[i]&&x[i]<rc[2]&&rc[1]<=y[i]&&y[i]<rc[3]){\n                long long si=1LL*(rc[2]-rc[0])*(rc[3]-rc[1]);\n                double rt=double(min(r[i],si))/double(max(r[i],si));\n                S += 1.0 - (1.0-rt)*(1.0-rt);\n            }\n        }\n        if(S>bestScore){\n            bestScore=S;\n            bestAns=ans;\n        }\n    };\n\n    // 3) static runs\n    for(int i=0;i<V;i++){\n        doRun(orderVars[i], pick2[i]);\n    }\n    // 4) random\u2010shuffle restarts up to ~4.8\u2009s\n    auto t0=chrono::steady_clock::now();\n    auto TL=chrono::milliseconds(4800);\n    while(chrono::steady_clock::now() - t0 < TL){\n        auto ord=base;\n        shuffle(ord.begin(), ord.end(), rng);\n        doRun(ord, P2(rng));\n    }\n    // 5) output best\n    for(int i=0;i<n;i++){\n        auto &a=bestAns[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\nstatic constexpr int H = 50, W = 50;\nstatic constexpr int DX[4] = {-1,1,0,0};\nstatic constexpr int DY[4] = {0,0,-1,1};\nstatic constexpr char DC[4] = {'U','D','L','R'};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    cin >> si >> sj;\n\n    static int tile[H][W], pval[H][W];\n    int maxT = 0;\n    for(int i=0;i<H;i++){\n      for(int j=0;j<W;j++){\n        cin >> tile[i][j];\n        maxT = max(maxT, tile[i][j]);\n      }\n    }\n    for(int i=0;i<H;i++){\n      for(int j=0;j<W;j++){\n        cin >> pval[i][j];\n      }\n    }\n    int M = maxT + 1;       // number of tiles\n\n    // stamping trick to avoid clearing a big 'visited' array\n    vector<int> visited(M, 0);\n    int stamp = 1;\n\n    // rng\n    uint64_t seed = chrono::high_resolution_clock::now()\n                       .time_since_epoch().count();\n    mt19937_64 rng(seed ^ (seed<<13));\n\n    // best path so far\n    vector<char> bestPath;\n    long long  bestScore = -1;\n\n    vector<char> curPath;\n    curPath.reserve(H*W);\n\n    // time\u2010boxing\n    auto T0 = chrono::steady_clock::now();\n    constexpr double TL = 1.85;  // leave a little margin\n\n    for(int iter=0; ; iter++){\n      // every 32 iters check the clock\n      if((iter & 31) == 0){\n        auto now = chrono::steady_clock::now();\n        double sec = double((now - T0).count()) * 1e-9;\n        if(sec > TL) break;\n      }\n\n      // pick our (WD,WP) according to 4 \u201cextreme\u201d modes + random\n      int mode = iter % 204;\n      int WD, WP;\n      if(mode == 0){\n        // pure degree\u2010only\n        WD = 20000; WP = 0;\n      } else if(mode == 1){\n        // pure value\u2010only\n        WD = 0; WP = 200;\n      } else if(mode == 2){\n        // fixed balanced\n        WD = 10000; WP = 100;\n      } else {\n        // random static mix\n        WD = int(rng() % 20001);  // [0..20000]\n        WP = int(rng() % 201);    // [0..200]\n      }\n\n      // clear for this run\n      curPath.clear();\n      int ci = si, cj = sj;\n      long long curScore = pval[ci][cj];\n      visited[ tile[ci][cj] ] = stamp;\n\n      // greedy until no more moves\n      while(true){\n        int bestW = INT_MIN, bestD = -1, ni = -1, nj = -1;\n        for(int d=0; d<4; d++){\n          int ti = ci + DX[d], tj = cj + DY[d];\n          if(ti<0||ti>=H||tj<0||tj>=W) continue;\n          int tid = tile[ti][tj];\n          if(visited[tid] == stamp) continue;\n\n          // count unvisited\u2010tile neighbors = deg\n          int deg = 0;\n          for(int d2=0; d2<4; d2++){\n            int xi = ti + DX[d2], xj = tj + DY[d2];\n            if(xi<0||xi>=H||xj<0||xj>=W) continue;\n            if(visited[ tile[xi][xj] ] != stamp)\n              deg++;\n          }\n\n          // static weight = deg*WD + p*WP + tiny noise\n          int w = deg * WD + pval[ti][tj] * WP + int(rng() & 15);\n          if(w > bestW){\n            bestW = w;\n            bestD = d;\n            ni = ti; nj = tj;\n          }\n        }\n        if(bestD < 0) break;  // no legal move\n\n        // take it\n        ci = ni; cj = nj;\n        visited[ tile[ci][cj] ] = stamp;\n        curScore += pval[ci][cj];\n        curPath.push_back( DC[bestD] );\n      }\n\n      // record if best\n      if(curScore > bestScore){\n        bestScore = curScore;\n        bestPath = curPath;\n      }\n      stamp++;\n    }\n\n    // output\n    for(char c : bestPath) cout << c;\n    cout << \"\\n\";\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nstatic constexpr int N      = 30;\nstatic constexpr int V      = N*N;\n\n// initial guess\nstatic constexpr double INITW = 5000.0;\n\n// schedules (tweak these to taste)\nstatic constexpr double ALPHA0    = 0.25;   // initial learning rate\nstatic constexpr double ALPHA_MIN = 0.005;  // final learning rate\nstatic constexpr double EXPL0     = 350.0;  // initial exploration bonus\nstatic constexpr double SM0       = 0.12;   // initial row/col smoothing\nstatic constexpr double SM1       = 0.005;  // final row/col smoothing\n\nint dr[4] = {-1, +1, 0, 0};\nint dc[4] = { 0,  0,-1,+1};\nchar dch[4] = {'U','D','L','R'};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // estimators and visit\u2010counts\n    static double w_h[N][N-1], w_v[N-1][N];\n    static int    cnt_h[N][N-1], cnt_v[N-1][N];\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N-1;j++){\n            w_h[i][j] = INITW;\n            cnt_h[i][j] = 0;\n        }\n    }\n    for(int i=0;i<N-1;i++){\n        for(int j=0;j<N;j++){\n            w_v[i][j] = INITW;\n            cnt_v[i][j] = 0;\n        }\n    }\n\n    // Dijkstra buffers\n    static double distArr[V];\n    static bool   done[V];\n    static int    prevNode[V];\n    static char   prevDir[V];\n\n    auto idx = [&](int r,int c){ return r*N + c; };\n    mt19937 rng(712687126);\n\n    for(int k=0;k<1000;k++){\n        int si,sj,ti,tj;\n        if(!(cin>>si>>sj>>ti>>tj)) break;\n\n        // fraction [0..1]\n        double f = double(k)/999.0;\n        // schedules\n        double alpha  = ALPHA0*(1-f) + ALPHA_MIN*f;\n        double expl   = EXPL0*(1-f);\n        double smooth = SM0*(1-f) + SM1*f;\n        double logk   = log(double(k+2));\n\n        // randomize neighbor order\n        array<int,4> dirs = {0,1,2,3};\n        shuffle(dirs.begin(), dirs.end(), rng);\n\n        // init Dijkstra\n        const double INF = 1e18;\n        for(int i=0;i<V;i++){\n            distArr[i] = INF;\n            done[i]    = false;\n        }\n        int S = idx(si,sj), T = idx(ti,tj);\n        distArr[S]=0;\n        priority_queue<pair<double,int>,\n                       vector<pair<double,int>>,\n                       greater<pair<double,int>>> pq;\n        pq.push({0.0,S});\n\n        // Dijkstra + UCB\u2010bonus\n        while(!pq.empty()){\n            auto [cd,u] = pq.top(); pq.pop();\n            if(done[u]) continue;\n            done[u]=true;\n            if(u==T) break;\n            int ur=u/N, uc=u%N;\n            for(int d:dirs){\n                int vr=ur+dr[d], vc=uc+dc[d];\n                if(vr<0||vr>=N||vc<0||vc>=N) continue;\n                double we, bonus;\n                if(d==0){        // U\n                    we    = w_v[vr][vc];\n                    bonus = expl * sqrt(logk/(cnt_v[vr][vc]+1.0));\n                } else if(d==1){ // D\n                    we    = w_v[ur][uc];\n                    bonus = expl * sqrt(logk/(cnt_v[ur][uc]+1.0));\n                } else if(d==2){ // L\n                    we    = w_h[vr][vc];\n                    bonus = expl * sqrt(logk/(cnt_h[vr][vc]+1.0));\n                } else {         // R\n                    we    = w_h[ur][uc];\n                    bonus = expl * sqrt(logk/(cnt_h[ur][uc]+1.0));\n                }\n                double cost = we - bonus;\n                if(cost < 1.0) cost = 1.0;\n                int v = idx(vr,vc);\n                double nd = cd + cost;\n                if(nd < distArr[v]){\n                    distArr[v]=nd;\n                    prevNode[v]=u;\n                    prevDir[v]=dch[d];\n                    pq.push({nd,v});\n                }\n            }\n        }\n\n        // reconstruct\n        vector<char> rev;\n        rev.reserve(1000);\n        for(int cur=T; cur!=S; cur=prevNode[cur])\n            rev.push_back(prevDir[cur]);\n        string path;\n        path.reserve(rev.size());\n        for(int i=int(rev.size())-1;i>=0;i--) path.push_back(rev[i]);\n\n        // output & flush\n        cout<<path<<\"\\n\"<<flush;\n\n        // read noisy length\n        int b_obs; \n        cin>>b_obs;\n\n        // collect edges & predicted sum\n        struct E{ bool h; int r,c; };\n        vector<E> edges; \n        edges.reserve(path.size());\n        double s_est=0;\n        int cr=si, cc=sj;\n        for(char mv:path){\n            if(mv=='U'){\n                edges.push_back({false,cr-1,cc});\n                s_est += w_v[cr-1][cc];\n                cr--;\n            } else if(mv=='D'){\n                edges.push_back({false,cr,cc});\n                s_est += w_v[cr][cc];\n                cr++;\n            } else if(mv=='L'){\n                edges.push_back({true,cr,cc-1});\n                s_est += w_h[cr][cc-1];\n                cc--;\n            } else { // R\n                edges.push_back({true,cr,cc});\n                s_est += w_h[cr][cc];\n                cc++;\n            }\n        }\n\n        // weighted\u2010residual update\n        double err = double(b_obs) - s_est;\n        if(!edges.empty() && fabs(err)>1e-9){\n            vector<bool> touch_row(N,false), touch_col(N,false);\n            for(auto &e: edges){\n                if(e.h){\n                    touch_row[e.r]=true;\n                    double &w = w_h[e.r][e.c];\n                    int    &ct=cnt_h[e.r][e.c];\n                    ct++;\n                    double lr = alpha / sqrt(double(ct));\n                    w += w * (err/s_est) * lr;\n                    if(w<1.0) w=1.0;\n                } else {\n                    touch_col[e.c]=true;\n                    double &w = w_v[e.r][e.c];\n                    int    &ct=cnt_v[e.r][e.c];\n                    ct++;\n                    double lr = alpha / sqrt(double(ct));\n                    w += w * (err/s_est) * lr;\n                    if(w<1.0) w=1.0;\n                }\n            }\n            // row/col smoothing\n            for(int i=0;i<N;i++){\n                if(touch_row[i]){\n                    double mu=0;\n                    for(int j=0;j<N-1;j++) mu += w_h[i][j];\n                    mu /= (N-1);\n                    for(int j=0;j<N-1;j++)\n                        w_h[i][j] = w_h[i][j]*(1 - smooth) + mu*smooth;\n                }\n                if(touch_col[i]){\n                    double mu=0;\n                    for(int r=0;r<N-1;r++) mu += w_v[r][i];\n                    mu /= (N-1);\n                    for(int r=0;r<N-1;r++)\n                        w_v[r][i] = w_v[r][i]*(1 - smooth) + mu*smooth;\n                }\n            }\n        }\n    }\n    return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// fast xorshift RNG\nstatic uint64_t rng_state = chrono::steady_clock::now().time_since_epoch().count();\ninline uint32_t xorshift32() {\n    rng_state ^= rng_state << 13;\n    rng_state ^= rng_state >> 7;\n    rng_state ^= rng_state << 17;\n    return (uint32_t)rng_state;\n}\ninline int randInt(int l, int r) {\n    return l + (xorshift32() % (r - l + 1));\n}\ninline double randDouble() {\n    // 24\u2010bit uniform\n    return (xorshift32() & 0xFFFFFF) / double(1<<24);\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const double TL = 2.95;     // leave a small margin\n    const int N = 20;\n    int M;\n    cin >> M;\n    vector<string> s(M);\n    for(int i = 0; i < M; i++){\n        cin >> s[i];\n    }\n    // convert strings to 0..7\n    vector<vector<int>> sChars(M);\n    for(int i = 0; i < M; i++){\n        int L = s[i].size();\n        sChars[i].resize(L);\n        for(int j = 0; j < L; j++){\n            sChars[i][j] = s[i][j] - 'A';\n        }\n    }\n\n    // Build all placements\n    struct Placement {\n        int si;\n        int len;\n        vector<int> coord; // (i,j) pairs flattened: coord[2*p],coord[2*p+1]\n    };\n    vector<Placement> placements;\n    placements.reserve(M * 2 * N);\n    const int CELL = N * N;\n    vector<vector<int>> byCell(CELL);\n    for(int c = 0; c < CELL; c++){\n        byCell[c].reserve(600);\n    }\n\n    for(int si = 0; si < M; si++){\n        int L = sChars[si].size();\n        for(int dir = 0; dir < 2; dir++){ // 0=H,1=V\n            for(int x = 0; x < N; x++){\n                for(int st = 0; st < N; st++){\n                    Placement P;\n                    P.si = si;\n                    P.len = L;\n                    P.coord.resize(2 * L);\n                    for(int p = 0; p < L; p++){\n                        int i,j;\n                        if(dir == 0){\n                            i = x;\n                            j = (st + p) % N;\n                        } else {\n                            i = (st + p) % N;\n                            j = x;\n                        }\n                        P.coord[2*p] = i;\n                        P.coord[2*p+1] = j;\n                    }\n                    int pid = placements.size();\n                    placements.push_back(move(P));\n                    // index into byCell\n                    auto &C = placements.back().coord;\n                    for(int p = 0; p < placements.back().len; p++){\n                        int i = C[2*p], j = C[2*p+1];\n                        byCell[i*N + j].push_back(pid);\n                    }\n                }\n            }\n        }\n    }\n\n    int Pn = placements.size();\n\n    // current grid as ints 0..7\n    vector<int> grid(CELL);\n    vector<int> bestGrid(CELL);\n\n    // valid flags for placements\n    vector<char> valid(Pn, 0);\n    // match count per string\n    vector<int> matchCount(M, 0);\n\n    // initialize grid randomly\n    for(int i = 0; i < CELL; i++){\n        grid[i] = randInt(0,7);\n    }\n    // compute initial valid[] and matchCount[]\n    for(int pid = 0; pid < Pn; pid++){\n        auto &P = placements[pid];\n        bool ok = true;\n        for(int p = 0; p < P.len; p++){\n            int i = P.coord[2*p], j = P.coord[2*p+1];\n            if(grid[i*N+j] != sChars[P.si][p]){\n                ok = false;\n                break;\n            }\n        }\n        if(ok){\n            valid[pid] = 1;\n            matchCount[P.si]++;\n        }\n    }\n    int curC = 0;\n    for(int i = 0; i < M; i++) if(matchCount[i] > 0) curC++;\n    int bestC = curC;\n    bestGrid = grid;\n\n    // buffers for delta computations\n    vector<pair<int,char>> changed; changed.reserve(1000);\n    vector<int> sis; sis.reserve(1000);\n    vector<int> oldMatch(M);\n    vector<char> seen(M,0);\n\n    auto start = chrono::steady_clock::now();\n    int iter = 0;\n    const double T0 = 5.0, T1 = 0.1;\n\n    while(true){\n        iter++;\n        if((iter & 511) == 0){\n            auto now = chrono::steady_clock::now();\n            double t = chrono::duration<double>(now - start).count();\n            if(t > TL) break;\n        }\n        // temperature\n        auto now = chrono::steady_clock::now();\n        double t = chrono::duration<double>(now - start).count() / TL;\n        if(t > 1.0) t = 1.0;\n        double T = T0 + (T1 - T0) * t;\n\n        // pick a random cell\n        int c = randInt(0, CELL-1);\n        int oldL = grid[c];\n        int newL = randInt(0,7);\n        if(newL == oldL) continue;\n\n        changed.clear();\n        sis.clear();\n        int newC = curC;\n\n        int ci = c / N, cj = c % N;\n\n        // try the change\n        for(int pid : byCell[c]){\n            auto &P = placements[pid];\n            int si = P.si;\n            bool prev = valid[pid];\n            bool nowv = true;\n            // check validity if we change this cell to newL\n            for(int p = 0; p < P.len; p++){\n                int ii = P.coord[2*p], jj = P.coord[2*p+1];\n                int gv = (ii==ci && jj==cj ? newL : grid[ii*N+jj]);\n                if(gv != sChars[si][p]){\n                    nowv = false;\n                    break;\n                }\n            }\n            if(prev != nowv){\n                changed.emplace_back(pid, prev);\n                if(!seen[si]){\n                    seen[si] = 1;\n                    sis.push_back(si);\n                    oldMatch[si] = matchCount[si];\n                }\n                if(prev){\n                    matchCount[si]--;\n                    if(oldMatch[si] > 0 && matchCount[si] == 0) newC--;\n                } else {\n                    matchCount[si]++;\n                    if(oldMatch[si] == 0 && matchCount[si] == 1) newC++;\n                }\n                valid[pid] = nowv;\n            }\n        }\n\n        int delta = newC - curC;\n        bool accept = false;\n        if(delta >= 0) accept = true;\n        else {\n            double p = exp(delta / T);\n            if(randDouble() < p) accept = true;\n        }\n\n        if(accept){\n            grid[c] = newL;\n            curC = newC;\n            if(curC > bestC){\n                bestC = curC;\n                bestGrid = grid;\n            }\n        } else {\n            // revert\n            for(auto &pc : changed){\n                valid[pc.first] = pc.second;\n            }\n            for(int si : sis){\n                matchCount[si] = oldMatch[si];\n            }\n        }\n        for(int si : sis) seen[si] = 0;\n    }\n\n    // output bestGrid\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            char ch = char('A' + bestGrid[i*N+j]);\n            cout << ch;\n        }\n        cout << \"\\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    cin >> N >> si >> sj;\n    vector<string> C(N);\n    for(int i = 0; i < N; i++){\n        cin >> C[i];\n    }\n\n    // 1) Flatten grid into road\u2010cell IDs\n    vector<int> id_map(N*N, -1);\n    vector<pair<int,int>> id2pos;\n    vector<int> id2cost;\n    id2pos.reserve(N*N);\n    id2cost.reserve(N*N);\n    int R = 0;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(C[i][j] == '#') continue;\n            id_map[i*N + j] = R++;\n            id2pos.emplace_back(i, j);\n            id2cost.push_back(C[i][j] - '0');\n        }\n    }\n    if(R == 0){\n        cout << \"\\n\";\n        return 0;\n    }\n    int start = id_map[si*N + sj];\n\n    // 2) Build 4\u2010neighbor graph with symmetric weights w = cost[u]+cost[v]\n    vector<vector<pair<int,int>>> graph(R);\n    const int di[4] = {-1,1,0,0}, dj[4] = {0,0,-1,1};\n    for(int u = 0; u < R; u++){\n        auto [ui,uj] = id2pos[u];\n        int cu = id2cost[u];\n        for(int d = 0; d < 4; d++){\n            int vi = ui + di[d], vj = uj + dj[d];\n            if(vi<0||vi>=N||vj<0||vj>=N) continue;\n            int v = id_map[vi*N + vj];\n            if(v<0) continue;\n            int w = cu + id2cost[v];\n            graph[u].emplace_back(v,w);\n        }\n    }\n\n    // 3) Prim\u2019s MST from `start`\n    const int INF = 1e9;\n    vector<int> key(R, INF), parent(R, -1), wMST(R,0);\n    vector<char> inM(R,0);\n    struct Node{int d,u;};\n    struct Cmp{ bool operator()(Node const &a, Node const &b) const {\n        return a.d > b.d;\n    }};\n    priority_queue<Node,vector<Node>,Cmp> pq;\n    key[start] = 0;\n    pq.push({0, start});\n    while(!pq.empty()){\n        auto [cd,u] = pq.top(); pq.pop();\n        if(inM[u]) continue;\n        inM[u] = 1;\n        wMST[u] = cd;  // equals key[u]\n        for(auto &e: graph[u]){\n            int v=e.first, w=e.second;\n            if(!inM[v] && w < key[v]){\n                key[v] = w;\n                parent[v] = u;\n                pq.push({w, v});\n            }\n        }\n    }\n\n    // 4) Build undirected MST adjacency\n    vector<vector<pair<int,int>>> tree(R);\n    for(int v = 0; v < R; v++){\n        int u = parent[v];\n        if(u < 0) continue;\n        int w = wMST[v];\n        tree[u].emplace_back(v,w);\n        tree[v].emplace_back(u,w);\n    }\n\n    // 5) Compute degree and mark \u201cturn\u201d nodes\n    vector<int> deg(R);\n    for(int u = 0; u < R; u++){\n        deg[u] = tree[u].size();\n    }\n    vector<char> is_turn(R,0);\n    for(int u = 0; u < R; u++){\n        if(deg[u] == 2){\n            int a = tree[u][0].first, b = tree[u][1].first;\n            auto [ui,uj] = id2pos[u];\n            auto [ai,aj] = id2pos[a];\n            auto [bi,bj] = id2pos[b];\n            // collinear?\n            if( !((ai==ui&&bi==ui) || (aj==uj&&bj==uj)) ){\n                is_turn[u] = 1;\n            }\n        }\n    }\n\n    // keep = start OR junction (deg>=3) OR a \u201cturn\u201d\n    vector<char> keep(R,0);\n    for(int u = 0; u < R; u++){\n        if(u==start || deg[u]>=3 || is_turn[u]) keep[u] = 1;\n    }\n\n    // 6) Root the MST at `start`, build children[]\n    vector<int> parT(R,-1);\n    vector<vector<int>> children(R);\n    {\n        vector<int> stk;\n        stk.reserve(R);\n        stk.push_back(start);\n        parT[start] = -1;\n        while(!stk.empty()){\n            int u = stk.back(); stk.pop_back();\n            for(auto &e: tree[u]){\n                int v = e.first;\n                if(v == parT[u]) continue;\n                parT[v] = u;\n                children[u].push_back(v);\n                stk.push_back(v);\n            }\n        }\n    }\n\n    // 7) Mark hasImp[u] = true if subtree at u contains any keep-node\n    vector<char> hasImp(R,0);\n    function<void(int)> dfsImp = [&](int u){\n        char h = keep[u];\n        for(int v: children[u]){\n            dfsImp(v);\n            if(hasImp[v]) h = 1;\n        }\n        hasImp[u] = h;\n    };\n    dfsImp(start);\n\n    // 8) Euler\u2010tour DFS on pruned tree: only traverse into v if hasImp[v]\n    string ans;\n    ans.reserve(R*2);\n\n    auto rev = [&](char c){\n        if(c=='U') return 'D';\n        if(c=='D') return 'U';\n        if(c=='L') return 'R';\n        return 'L';\n    };\n\n    function<void(int)> dfsTour = [&](int u){\n        auto [ui,uj] = id2pos[u];\n        for(int v: children[u]){\n            if(!hasImp[v]) continue;\n            auto [vi,vj] = id2pos[v];\n            char mv;\n            if(vi==ui-1&&vj==uj) mv='U';\n            else if(vi==ui+1&&vj==uj) mv='D';\n            else if(vi==ui&&vj==uj-1) mv='L';\n            else mv='R';\n            ans.push_back(mv);\n            dfsTour(v);\n            ans.push_back(rev(mv));\n        }\n    };\n\n    dfsTour(start);\n\n    // 9) Output the move string\n    cout << ans << \"\\n\";\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// Weights for our greedy cost = TIME_W * t_ij - RANK_W * rank[i]\nstatic const ll TIME_W = 10000;\nstatic const ll RANK_W = 2000;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, K, R;\n    cin >> N >> M >> K >> R;\n\n    // Read task difficulties\n    vector<vector<int>> d(N, vector<int>(K));\n    for(int i = 0; i < N; i++)\n        for(int j = 0; j < K; j++)\n            cin >> d[i][j];\n\n    // Read dependencies, build graph\n    vector<vector<int>> adj(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        adj[u].push_back(v);\n        indeg[v]++;\n    }\n\n    // Precompute sumd[i] = sum_k d[i][k]\n    vector<int> sumd(N, 0);\n    for(int i = 0; i < N; i++)\n        for(int x: d[i])\n            sumd[i] += x;\n\n    // 1) Compute static \u201crank\u201d = sumd[i] + max rank of children\n    // Since u<v always, we can do i=N-1..0\n    vector<ll> rankv(N,0);\n    for(int i = N-1; i >= 0; i--){\n        ll best = 0;\n        for(int v: adj[i])\n            best = max(best, rankv[v]);\n        rankv[i] = sumd[i] + best;\n    }\n\n    // Track which tasks are ready\n    vector<int> ready;\n    ready.reserve(N);\n    for(int i = 0; i < N; i++){\n        if(indeg[i] == 0)\n            ready.push_back(i);\n    }\n\n    // State\n    vector<char> started(N, 0), done(N, 0);\n    vector<int> assigned(M, -1), start_day(M, 0);\n    vector<char> is_free(M, 1);\n    vector<int> free_list(M);\n    iota(free_list.begin(), free_list.end(), 0);\n\n    // Skill lower\u2010bounds s_est[j][k]\n    vector<vector<int>> s_est(M, vector<int>(K,0));\n\n    int day = 1;\n    while(true){\n        // --- MORNING: build candidate task list & greedy match ---\n        vector<int> cand;\n        cand.reserve(ready.size());\n        for(int t: ready){\n            if(!started[t] && !done[t])\n                cand.push_back(t);\n        }\n\n        vector<pair<int,int>> out;\n        out.reserve(M);\n\n        // Greedy min\u2010cost matching\n        while(!free_list.empty() && !cand.empty()){\n            ll best_cost = LLONG_MAX;\n            int best_wi=-1, best_ti=-1;\n            // search all pairs\n            for(int wi = 0; wi < (int)free_list.size(); wi++){\n                int w = free_list[wi];\n                auto &se = s_est[w];\n                for(int tj = 0; tj < (int)cand.size(); tj++){\n                    int t = cand[tj];\n                    // predict deficit\n                    int def = 0;\n                    for(int k2 = 0; k2 < K; k2++){\n                        int delta = d[t][k2] - se[k2];\n                        if(delta>0) def += delta;\n                    }\n                    int tij = def>0 ? def+1 : 1;\n                    ll cost = (ll)tij * TIME_W - rankv[t] * RANK_W;\n                    if(cost < best_cost){\n                        best_cost = cost;\n                        best_wi = wi;\n                        best_ti = tj;\n                    }\n                }\n            }\n            if(best_wi<0) break;\n            // assign them\n            int w = free_list[best_wi];\n            int t = cand[best_ti];\n            started[t]     = 1;\n            is_free[w]     = 0;\n            assigned[w]    = t;\n            start_day[w]   = day;\n            out.emplace_back(w+1, t+1);\n\n            // remove w and t from lists\n            free_list.erase(free_list.begin() + best_wi);\n            cand       .erase(cand.begin()       + best_ti);\n        }\n\n        // Output assignments\n        cout << out.size();\n        for(auto &pr: out)\n            cout << ' ' << pr.first << ' ' << pr.second;\n        cout << \"\\n\" << flush;\n\n        // --- EVENING: read completions ---\n        int cnt;\n        if(!(cin >> cnt) || cnt < 0) break;\n        for(int i = 0; i < cnt; i++){\n            int f; \n            cin >> f;\n            int w = f-1;\n            int t = assigned[w];\n            int took = day - start_day[w] + 1;\n            int w_est = max(0, took - 1);\n            // update skill\u2010bounds\n            if(t >= 0){\n                for(int k2 = 0; k2 < K; k2++){\n                    int lb = d[t][k2] - w_est;\n                    if(lb > s_est[w][k2])\n                        s_est[w][k2] = lb;\n                }\n            }\n            // free worker\n            is_free[w]   = 1;\n            assigned[w]  = -1;\n            free_list.push_back(w);\n            // mark task done & unlock children\n            if(t >= 0 && !done[t]){\n                done[t] = 1;\n                for(int nx: adj[t]){\n                    if(--indeg[nx] == 0)\n                        ready.push_back(nx);\n                }\n            }\n        }\n\n        day++;\n    }\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\n#include <chrono>\nusing namespace std;\nusing ll = long long;\n\n// Manhattan distance\nstatic inline int manh(int x1,int y1,int x2,int y2){\n    return abs(x1-x2)+abs(y1-y2);\n}\n\nstruct Order {\n    int a,b,c,d,dist;\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    //--- 1) Read 1000 orders\n    vector<Order> ord(1000);\n    for(int i=0;i<1000;i++){\n        cin>>ord[i].a>>ord[i].b>>ord[i].c>>ord[i].d;\n        ord[i].dist = manh(ord[i].a,ord[i].b, ord[i].c,ord[i].d);\n    }\n\n    // Global timer\n    auto T0 = chrono::steady_clock::now();\n    auto elapsed = [&](){\n        return chrono::duration<double>(\n          chrono::steady_clock::now() - T0).count();\n    };\n    const double TL_TOTAL = 1.97;\n\n    //--- 2) Pick the 50 orders with smallest internal distance\n    vector<int> initial_sel(1000);\n    iota(initial_sel.begin(), initial_sel.end(), 0);\n    nth_element(initial_sel.begin(),\n                initial_sel.begin()+50,\n                initial_sel.end(),\n                [&](int i,int j){ return ord[i].dist < ord[j].dist; });\n    initial_sel.resize(50);\n    const int M = 50;\n\n    //--- 3) Build the condensed graph for these M=50\n    // start_cost[i] = dist(office\u2192pickup_i)\n    // end_cost[i]   = dist(delivery_i\u2192office)\n    // trans0[i][j]  = dist(delivery_i\u2192pickup_j)\n    vector<int> px(M), py(M), dx(M), dy(M);\n    vector<int> start_cost(M), end_cost(M);\n    for(int i=0;i<M;i++){\n        auto &o = ord[ initial_sel[i] ];\n        px[i]=o.a;  py[i]=o.b;\n        dx[i]=o.c;  dy[i]=o.d;\n        start_cost[i] = manh(400,400, px[i],py[i]);\n        end_cost[i]   = manh(dx[i],dy[i], 400,400);\n    }\n    static int trans0[50][50];\n    for(int i=0;i<M;i++){\n        for(int j=0;j<M;j++){\n            trans0[i][j] = manh(dx[i],dy[i], px[j],py[j]);\n        }\n    }\n\n    //--- 4) Multi\u2010start greedy NN: 10 pure + (K-10) semi\u2010random\n    vector<int> order_by_start(M);\n    iota(order_by_start.begin(), order_by_start.end(), 0);\n    sort(order_by_start.begin(), order_by_start.end(),\n         [&](int i,int j){ return start_cost[i] < start_cost[j]; });\n\n    const int K = min(M, 32), K_PURE = 10, RAND_K = 5;\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    vector<pair<ll,vector<int>>> seeds;\n    seeds.reserve(K);\n\n    for(int ss=0; ss<K && elapsed()<0.5; ss++){\n        int s = order_by_start[ss];\n        vector<char> used(M,false);\n        vector<int> path;\n        path.reserve(M);\n        path.push_back(s);\n        used[s]=true;\n        int cur=s;\n        for(int step=1; step<M; step++){\n            int nxt=-1;\n            if(ss < K_PURE){\n                // pure nearest\n                int bestc=INT_MAX;\n                for(int j=0;j<M;j++) if(!used[j]){\n                    int c = trans0[cur][j];\n                    if(c<bestc){ bestc=c; nxt=j; }\n                }\n            } else {\n                // randomized among top-RAND_K\n                vector<pair<int,int>> cand;\n                cand.reserve(M);\n                for(int j=0;j<M;j++) if(!used[j]){\n                    cand.emplace_back(trans0[cur][j], j);\n                }\n                int k = min(RAND_K, (int)cand.size());\n                nth_element(cand.begin(), cand.begin()+k, cand.end());\n                uniform_int_distribution<int> pick(0,k-1);\n                nxt = cand[pick(rng)].second;\n            }\n            path.push_back(nxt);\n            used[nxt]=true;\n            cur=nxt;\n        }\n        // cost it\n        ll csum = start_cost[path[0]];\n        for(int i=0;i+1<M;i++) csum += trans0[path[i]][path[i+1]];\n        csum += end_cost[path[M-1]];\n        seeds.emplace_back(csum, move(path));\n    }\n    if(seeds.empty()){\n        // fallback: single trivial\n        vector<int> p(M);\n        iota(p.begin(),p.end(),0);\n        ll c= start_cost[0]+end_cost[0]; \n        for(int i=0;i+1<M;i++) c+=trans0[i][i+1];\n        seeds.emplace_back(c,p);\n    }\n    sort(seeds.begin(), seeds.end(),\n         [&](auto &A, auto &B){ return A.first < B.first; });\n\n    //--- 5) Phase 1: directed\u20102opt on top 2 seeds (until ~1.2s)\n    const double TL1 = 1.20;\n    ll best_cost = seeds[0].first;\n    vector<int> best_path = seeds[0].second;\n    const int T_OPT = min((int)seeds.size(), 2);\n\n    for(int ti=0; ti<T_OPT && elapsed()<TL1; ti++){\n        ll cur_cost = seeds[ti].first;\n        auto P = seeds[ti].second;\n        static ll prefix[50];\n\n        while(elapsed()<TL1){\n            bool improved=false;\n            // build prefix of interior\u2010reversal deltas\n            prefix[0] = (ll)trans0[P[1]][P[0]] - trans0[P[0]][P[1]];\n            for(int k=1;k<M-1;k++){\n                prefix[k] = prefix[k-1]\n                           + ((ll)trans0[P[k+1]][P[k]] - trans0[P[k]][P[k+1]]);\n            }\n            for(int i=1;i<M-1 && !improved;i++){\n                int A=P[i-1], B=P[i];\n                ll o1 = trans0[A][B], bef = prefix[i-1];\n                for(int j=i+1;j<M && !improved;j++){\n                    int C=P[j];\n                    bool endseg = (j==M-1);\n                    ll o2 = endseg\n                              ? end_cost[C]\n                              : trans0[C][P[j+1]];\n                    ll n1 = trans0[A][C];\n                    ll n2 = endseg\n                              ? end_cost[B]\n                              : trans0[B][P[j+1]];\n                    ll interior = prefix[j-1] - bef;\n                    ll delta = (n1+n2) - (o1+o2) + interior;\n                    if(delta<0){\n                        reverse(P.begin()+i, P.begin()+j+1);\n                        cur_cost += delta;\n                        improved = true;\n                    }\n                }\n            }\n            if(!improved) break;\n        }\n        if(cur_cost < best_cost){\n            best_cost = cur_cost;\n            best_path = move(P);\n        }\n    }\n\n    //--- 6) Phase 2: build explicit route & swap\u2010out/in (until ~1.5s)\n    // cur_sel_ids[k] = original order\u2010index of the k\u2019th block in best_path\n    vector<int> cur_sel_ids(M);\n    for(int i=0;i<M;i++){\n        cur_sel_ids[i] = initial_sel[ best_path[i] ];\n    }\n    // explicit 2*M+2 route: (400,400)\u2192p\u2192d\u2192\u2026\u2192p\u2192d\u2192(400,400)\n    vector<pair<int,int>> route;\n    route.reserve(2*M+2);\n    route.emplace_back(400,400);\n    for(int k=0;k<M;k++){\n        auto &o = ord[cur_sel_ids[k]];\n        route.emplace_back(o.a,o.b);\n        route.emplace_back(o.c,o.d);\n    }\n    route.emplace_back(400,400);\n\n    // build outside pool = top 150 unused by internal\u2010dist\n    static bool in_sel[1000];\n    memset(in_sel,0,sizeof(in_sel));\n    for(int x: cur_sel_ids) in_sel[x]=1;\n    vector<pair<int,int>> outv;\n    outv.reserve(1000);\n    for(int i=0;i<1000;i++){\n        if(!in_sel[i]) outv.emplace_back(ord[i].dist, i);\n    }\n    sort(outv.begin(), outv.end());\n    const int K_OUT = 150;\n    if((int)outv.size()>K_OUT) outv.resize(K_OUT);\n    vector<int> outside;\n    outside.reserve(K_OUT);\n    for(auto &p: outv) outside.push_back(p.second);\n\n    // swap\u2010out/in\n    while(elapsed()<1.50){\n        // 1) find best removal\n        ll best_rem = LLONG_MIN;\n        int rem_i=-1;\n        for(int k=0;k<M;k++){\n            int rp = 2*k+1;\n            auto &L = route[rp-1];\n            auto &P = route[rp];\n            auto &D = route[rp+1];\n            auto &R = route[rp+2];\n            ll bef = manh(L.first,L.second,P.first,P.second)\n                   + manh(P.first,P.second,D.first,D.second)\n                   + manh(D.first,D.second,R.first,R.second);\n            ll aft = manh(L.first,L.second,R.first,R.second);\n            ll delta = bef - aft;\n            if(delta>best_rem){\n                best_rem=delta;\n                rem_i = k;\n            }\n        }\n        if(best_rem<=0) break;\n\n        // 2) find best insertion\n        ll best_ins = LLONG_MAX;\n        int ins_j=-1, ins_pos=0;\n        for(int j=0;j<(int)outside.size();j++){\n            auto &o = ord[ outside[j] ];\n            ll bestj = LLONG_MAX;\n            int bestp=0;\n            for(int ip=0; ip<=M; ip++){\n                int rp = 2*ip;\n                auto &A = route[rp];\n                auto &B = route[rp+1];\n                ll cb = manh(A.first,A.second,B.first,B.second);\n                ll ca = manh(A.first,A.second,o.a,o.b)\n                      + manh(o.a,o.b,o.c,o.d)\n                      + manh(o.c,o.d,B.first,B.second);\n                ll d = ca - cb;\n                if(d<bestj){\n                    bestj=d;\n                    bestp=ip;\n                }\n            }\n            if(bestj<best_ins){\n                best_ins=bestj;\n                ins_j=j;\n                ins_pos=bestp;\n            }\n        }\n        if(ins_j<0 || best_ins>=best_rem) break;\n\n        // Apply the swap\n        int old_id   = cur_sel_ids[rem_i];\n        int out_id   = outside[ins_j];\n        int rp       = 2*rem_i+1;\n        route.erase(route.begin()+rp, route.begin()+rp+2);\n        cur_sel_ids.erase(cur_sel_ids.begin()+rem_i);\n\n        int new_pos = ins_pos;\n        if(ins_pos>rem_i) new_pos = ins_pos-1;\n        cur_sel_ids.insert(cur_sel_ids.begin()+new_pos, out_id);\n        int ip = 2*new_pos+1;\n        route.insert(route.begin()+ip,   {ord[out_id].a, ord[out_id].b});\n        route.insert(route.begin()+ip+1, {ord[out_id].c, ord[out_id].d});\n\n        outside[ins_j] = old_id;\n    }\n\n    //--- 7) Phase 3: final block-level 2-opt + block-relocation (until TL_TOTAL)\n    // rebuild the M\u00d7M graph on the *current* cur_sel_ids\n    vector<int> px2(M),py2(M),dx2(M),dy2(M);\n    vector<int> st2(M), en2(M);\n    for(int i=0;i<M;i++){\n        auto &o = ord[ cur_sel_ids[i] ];\n        px2[i]=o.a;  py2[i]=o.b;\n        dx2[i]=o.c;  dy2[i]=o.d;\n        st2[i] = manh(400,400,px2[i],py2[i]);\n        en2[i] = manh(dx2[i],dy2[i],400,400);\n    }\n    static int trans2[50][50];\n    for(int i=0;i<M;i++){\n        for(int j=0;j<M;j++){\n            trans2[i][j] = manh(dx2[i],dy2[i], px2[j],py2[j]);\n        }\n    }\n    // initial block order\n    vector<int> P2(M);\n    iota(P2.begin(),P2.end(),0);\n    // compute cost2\n    ll cost2 = st2[P2[0]];\n    for(int i=0;i+1<M;i++) cost2 += trans2[P2[i]][P2[i+1]];\n    cost2 += en2[P2[M-1]];\n\n    // (a) directed 2-opt over the remaining budget\n    static ll prefix2[50];\n    while(elapsed()<TL_TOTAL){\n        bool improved=false;\n        prefix2[0] = (ll)trans2[P2[1]][P2[0]] - trans2[P2[0]][P2[1]];\n        for(int k=1;k<M-1;k++){\n            prefix2[k] = prefix2[k-1]\n                       + ((ll)trans2[P2[k+1]][P2[k]] \n                          - trans2[P2[k]][P2[k+1]]);\n        }\n        for(int i=1;i<M-1 && !improved;i++){\n            int A=P2[i-1], B=P2[i];\n            ll o1 = trans2[A][B], bef = prefix2[i-1];\n            for(int j=i+1;j<M && !improved;j++){\n                int C=P2[j];\n                bool endsg = (j==M-1);\n                ll o2 = endsg ? en2[C] \n                              : trans2[C][P2[j+1]];\n                ll n1 = trans2[A][C];\n                ll n2 = endsg ? en2[B]\n                              : trans2[B][P2[j+1]];\n                ll interior = prefix2[j-1] - bef;\n                ll delta = (n1+n2) - (o1+o2) + interior;\n                if(delta<0){\n                    reverse(P2.begin()+i, P2.begin()+j+1);\n                    cost2 += delta;\n                    improved = true;\n                }\n            }\n        }\n        if(!improved) break;\n    }\n\n    // (b) block-relocation (Or-opt on blocks) in the last ~0.1 s\n    while(elapsed() < TL_TOTAL - 0.05){\n        ll best_delta = 0;\n        int bi=-1, bj=-1;\n        for(int i=0;i<M;i++){\n            int u = P2[i];\n            ll remd;\n            if(i==0){\n                // remove first block\n                ll c1 = st2[P2[0]] + trans2[P2[0]][P2[1]];\n                ll c3 = st2[P2[1]];\n                remd = c3 - c1;\n            } else if(i==M-1){\n                // remove last block\n                ll c1 = trans2[P2[M-2]][P2[M-1]] + en2[P2[M-1]];\n                ll c3 = en2[P2[M-2]];\n                remd = c3 - c1;\n            } else {\n                // middle\n                ll c1 = trans2[P2[i-1]][u];\n                ll c2 = trans2[u][P2[i+1]];\n                ll c3 = trans2[P2[i-1]][P2[i+1]];\n                remd = c3 - (c1 + c2);\n            }\n            // try inserting u before position j in [0..M]\n            for(int j=0;j<=M;j++){\n                if(j==i || j==i+1) continue;\n                ll insd;\n                if(j==0){\n                    // before the very first\n                    ll oldc = st2[P2[0]];\n                    insd = st2[u] + trans2[u][P2[0]] - oldc;\n                } else if(j==M){\n                    // after the last\n                    ll oldc = en2[P2[M-1]];\n                    insd = trans2[P2[M-1]][u] + en2[u] - oldc;\n                } else {\n                    ll oldc = trans2[P2[j-1]][P2[j]];\n                    insd = trans2[P2[j-1]][u] + trans2[u][P2[j]] - oldc;\n                }\n                ll delta = remd + insd;\n                if(delta < best_delta){\n                    best_delta = delta;\n                    bi = i; bj = j;\n                }\n            }\n        }\n        if(best_delta >= 0) break;\n        // apply the relocation\n        int u = P2[bi];\n        P2.erase(P2.begin()+bi);\n        int pos = bj;\n        if(bj > bi) pos = bj-1;\n        P2.insert(P2.begin()+pos, u);\n        cost2 += best_delta;\n    }\n\n    //--- 8) Rebuild final selection & route\n    vector<int> final_sel(M);\n    for(int i=0;i<M;i++){\n        final_sel[i] = cur_sel_ids[ P2[i] ];\n    }\n    vector<pair<int,int>> final_route;\n    final_route.reserve(2*M+2);\n    final_route.emplace_back(400,400);\n    for(int i=0;i<M;i++){\n        auto &o = ord[ final_sel[i] ];\n        final_route.emplace_back(o.a,o.b);\n        final_route.emplace_back(o.c,o.d);\n    }\n    final_route.emplace_back(400,400);\n\n    //--- 9) Output\n    // first line: 50 r_1 \u2026 r_50 (1-based)\n    cout<<M;\n    for(int id: final_sel) cout<<' '<<(id+1);\n    cout<<\"\\n\";\n    // second line: n and the coordinates\n    cout<<final_route.size();\n    for(auto &p: final_route){\n        cout<<\" \"<<p.first<<\" \"<<p.second;\n    }\n    cout<<\"\\n\";\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Disjoint\u2010set union (union by rank + path compression)\nstruct DSU {\n    int n;\n    vector<int> p, r;\n    DSU(int _n): n(_n), p(n,-1), r(n,0) {\n        iota(p.begin(), p.end(), 0);\n    }\n    int find(int x) {\n        return p[x]==x ? x : 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    vector<pair<int,int>> coord(N);\n    for(int i = 0; i < N; i++){\n        cin >> coord[i].first >> coord[i].second;\n    }\n    struct Edge { int u,v,id; int d; };\n    vector<Edge> edges;\n    edges.reserve(M);\n    for(int i = 0; i < M; i++){\n        int u,v;\n        cin >> u >> v;\n        int dx = coord[u].first  - coord[v].first;\n        int dy = coord[u].second - coord[v].second;\n        // rounded Euclidean distance\n        int di = int( round( sqrt(double(dx*dx + dy*dy)) ) );\n        edges.push_back({u,v,i,di});\n    }\n\n    // Kruskal on weights = d_i\n    vector<bool> choose(M,false);\n    DSU dsu(N);\n    sort(edges.begin(), edges.end(),\n         [&](auto &A, auto &B){\n             return A.d < B.d;\n         });\n    int taken = 0;\n    for(auto &e: edges){\n        if(taken == N-1) break;\n        if(dsu.unite(e.u, e.v)){\n            choose[e.id] = true;\n            taken++;\n        }\n    }\n    // Now process the stream\n    for(int i = 0; i < M; i++){\n        int l;\n        if(!(cin >> l)) return 0;  // safety\n        if(choose[i]){\n            cout << 1 << '\\n';\n        } else {\n            cout << 0 << '\\n';\n        }\n        cout.flush();  // must flush after each decision\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Global maps\nstatic bool petAt[30][30], humanAt[30][30], impWall[30][30], builtThis[30][30];\n\n// Directions\nint dx4[4] = {-1,0,1,0}, dy4[4] = {0,1,0,-1};\nchar buildC[4] = {'u','r','d','l'};\n\nint buildDirIdx(char c){\n  if(c=='u') return 0;\n  if(c=='r') return 1;\n  if(c=='d') return 2;\n  if(c=='l') return 3;\n  return -1;\n}\n\nvoid moveDelta(char c,int &dx,int &dy){\n  if(c=='U'){ dx=-1; dy=0; }\n  else if(c=='D'){ dx= 1; dy=0; }\n  else if(c=='L'){ dx= 0; dy=-1;}\n  else if(c=='R'){ dx= 0; dy= 1;}\n  else { dx=dy=0; }\n}\n\n// Can we legally build at (bx,by) this turn?\nbool canBuildAt(int bx,int by){\n  if(bx<0||bx>=30||by<0||by>=30) return false;\n  if(petAt[bx][by] || humanAt[bx][by]) return false;\n  for(int d=0;d<4;d++){\n    int ax=bx+dx4[d], ay=by+dy4[d];\n    if(ax>=0&&ax<30&&ay>=0&&ay<30 && petAt[ax][ay]) \n      return false;\n  }\n  return true;\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<int> ppx(N), ppy(N), pt(N);\n  for(int i=0;i<N;i++){\n    cin>>ppx[i]>>ppy[i]>>pt[i];\n    --ppx[i]; --ppy[i];\n  }\n  int M; cin>>M;\n  vector<int> hx(M), hy(M);\n  for(int i=0;i<M;i++){\n    cin>>hx[i]>>hy[i];\n    --hx[i]; --hy[i];\n  }\n\n  // Initialize petAt\n  memset(petAt,0,sizeof(petAt));\n  for(int i=0;i<N;i++){\n    petAt[ppx[i]][ppy[i]] = true;\n  }\n  // Initialize humanAt\n  memset(humanAt,0,sizeof(humanAt));\n  for(int i=0;i<M;i++){\n    humanAt[hx[i]][hy[i]] = true;\n  }\n  // Initialize impassable walls (none yet)\n  memset(impWall,0,sizeof(impWall));\n\n  // Current human coords\n  vector<int> cx = hx, cy = hy;\n\n  // 1) Assign stripes by sorting humans by hy\n  vector<pair<int,int>> order;\n  order.reserve(M);\n  for(int i=0;i<M;i++) order.emplace_back(hy[i], i);\n  sort(order.begin(), order.end());\n  \n  // 2) Split columns 0..29 into M stripes of widths floor(30/M) or +1\n  vector<int> width(M), L(M), R(M);\n  int baseW = 30 / M, rem = 30 % M;\n  for(int k=0;k<M;k++){\n    width[k] = baseW + (k < rem);\n  }\n  {\n    int cur = 0;\n    for(int k=0;k<M;k++){\n      L[k] = cur;\n      R[k] = cur + width[k] - 1;\n      cur += width[k];\n    }\n  }\n\n  // 3) Prepare the 300\u2010turn plan for each human\n  const int TURNS = 300;\n  vector< array<char,TURNS> > plan(M);\n  for(int i=0;i<M;i++){\n    plan[i].fill('.');\n  }\n\n  // We will build fence only for stripes 0..M-2:\n  // stripe k's \"builder\" is human idx = order[k].second\n  // that builder must end up at (0, R[k]) at time REL, then at times REL + 2*r issue \"r\" then \"D\"\n  // stripe M-1 has no interior fence to build.\n\n  // First compute each builder's relocation cost to (0,R[k])\n  vector<int> relocCost(M,0);\n  int REL = 0;\n  for(int k=0;k<M;k++){\n    int i = order[k].second;\n    int cost = hx[i] + abs(hy[i] - R[k]);\n    relocCost[i] = cost;\n    REL = max(REL, cost);\n  }\n  // REL = #turns we MUST spend moving, so that all i finish relocation **exactly** at turn REL\n  // We'll pad each human's plan with dots so that barrier\u2010building begins at turn REL.\n\n  // Build each plan:\n  for(int k=0;k<M;k++){\n    int i = order[k].second;\n    int p = 0;\n    //  a) move up from (hx[i],hy[i]) to (0, hy[i])\n    for(int z=0; z<hx[i]; z++){\n      plan[i][p++] = 'U';\n    }\n    //  b) move horizontally to col=R[k]\n    if(hy[i] <= R[k]){\n      for(int z=0; z< R[k]-hy[i]; z++){\n        plan[i][p++] = 'R';\n      }\n    } else {\n      for(int z=0; z< hy[i]-R[k]; z++){\n        plan[i][p++] = 'L';\n      }\n    }\n    //  c) pad with dots so that p == REL\n    int pad = REL - relocCost[i];\n    for(int z=0; z<pad; z++){\n      if(p<TURNS) plan[i][p++] = '.';\n    }\n    //  d) barrier building for stripes 0..M-2\n    if(k < M-1){\n      // we assume builder i is now at (0, R[k])\n      for(int r=0; r<29 && p<TURNS; r++){\n        plan[i][p++] = 'r';   // build the right wall at row=r, col=R[k]+1\n        plan[i][p++] = 'D';   // move down\n      }\n      // last row =29, only 'r'\n      if(p<TURNS){\n        plan[i][p++] = 'r';\n      }\n    }\n    // rest remain '.'\n  }\n\n  // 4) Interactive loop with pointer\u2010advance on success or dot:\n  vector<int> ptr(M,0);\n  string out(M, '.');\n\n  for(int turn=0; turn<TURNS; turn++){\n    // a) clear builtThis\n    memset(builtThis,0,sizeof(builtThis));\n    // b) pre\u2010scan builds that would be legal\n    vector<bool> isBuild(M,false), isMove(M,false);\n\n    for(int i=0;i<M;i++){\n      if(ptr[i] >= TURNS) continue;\n      char c = plan[i][ptr[i]];\n      int d = buildDirIdx(c);\n      if(d >= 0){\n        // a lowercase build\n        int bx = cx[i] + dx4[d], by = cy[i] + dy4[d];\n        if(canBuildAt(bx,by)){\n          isBuild[i] = true;\n          builtThis[bx][by] = true;\n        }\n      }\n    }\n    // c) decide moves\n    for(int i=0;i<M;i++){\n      if(ptr[i] >= TURNS) continue;\n      char c = plan[i][ptr[i]];\n      if(c=='U'||c=='D'||c=='L'||c=='R'){\n        int dx,dy;\n        moveDelta(c,dx,dy);\n        int tx = cx[i]+dx, ty = cy[i]+dy;\n        if(tx>=0&&tx<30&&ty>=0&&ty<30\n           && !impWall[tx][ty]\n           && !builtThis[tx][ty]){\n          isMove[i] = true;\n        }\n      }\n    }\n    // d) finalize out[]\n    for(int i=0;i<M;i++){\n      if(isBuild[i] || isMove[i]){\n        out[i] = plan[i][ptr[i]];\n      } else {\n        out[i] = '.';\n      }\n    }\n\n    // e) advance ptr on success or dot\n    for(int i=0;i<M;i++){\n      if(ptr[i]>=TURNS) continue;\n      char c = plan[i][ptr[i]];\n      int d = buildDirIdx(c);\n      if(d>=0){\n        // build\n        if(isBuild[i]) ptr[i]++;\n      }\n      else if(c=='U'||c=='D'||c=='L'||c=='R'){\n        if(isMove[i]) ptr[i]++;\n      }\n      else {\n        // dot in plan\n        ptr[i]++;\n      }\n    }\n\n    // f) apply builds \u2192 impWall\n    for(int i=0;i<M;i++){\n      if(isBuild[i]){\n        int d = buildDirIdx(out[i]);\n        int bx = cx[i] + dx4[d], by = cy[i] + dy4[d];\n        if(bx>=0&&bx<30&&by>=0&&by<30){\n          impWall[bx][by] = true;\n        }\n      }\n    }\n    // g) apply moves \u2192 humanAt, cx,cy\n    for(int i=0;i<M;i++){\n      humanAt[cx[i]][cy[i]] = false;\n    }\n    for(int i=0;i<M;i++){\n      if(isMove[i]){\n        int dx,dy;\n        moveDelta(out[i],dx,dy);\n        cx[i] += dx;\n        cy[i] += dy;\n      }\n    }\n    for(int i=0;i<M;i++){\n      humanAt[cx[i]][cy[i]] = true;\n    }\n\n    // h) output & flush\n    cout << out << \"\\n\" << flush;\n\n    // i) read pet\u2010moves, rebuild petAt\n    vector<string> mv(N);\n    for(int i=0;i<N;i++){\n      cin >> mv[i];\n    }\n    memset(petAt,0,sizeof(petAt));\n    for(int i=0;i<N;i++){\n      if(mv[i]!=\".\"){\n        for(char c: mv[i]){\n          int dx,dy;\n          moveDelta(c,dx,dy);\n          ppx[i] += dx;\n          ppy[i] += dy;\n        }\n      }\n      int x=ppx[i], y=ppy[i];\n      if(x>=0&&x<30&&y>=0&&y<30){\n        petAt[x][y] = true;\n      }\n    }\n  }\n\n  return 0;\n}","ahc009":"#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,ti,tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n\n    // read walls\n    vector<string> h(20), v(19);\n    for(int i=0;i<20;i++) cin >> h[i];\n    for(int i=0;i<19;i++) cin >> v[i];\n\n    // Precompute for each cell (i,j) the list of valid neighbor\u2010directions,\n    // sorted by manhattan distance to target ascending.\n    static vector<int> nbr[20][20];\n    int dx[4]={-1,1,0,0}, dy[4]={0,0,-1,1};\n    char dc[4]={'U','D','L','R'};\n    for(int i=0;i<20;i++){\n        for(int j=0;j<20;j++){\n            nbr[i][j].clear();\n            for(int d=0;d<4;d++){\n                int ni=i+dx[d], nj=j+dy[d];\n                bool ok=false;\n                if(d==0){ if(i>=1   && v[i-1][j]=='0') ok=true; }\n                if(d==1){ if(i<=18  && v[i][j]=='0')   ok=true; }\n                if(d==2){ if(j>=1   && h[i][j-1]=='0') ok=true; }\n                if(d==3){ if(j<=18  && h[i][j]=='0')   ok=true; }\n                if(ok){\n                    nbr[i][j].push_back(d);\n                }\n            }\n            // sort by manhattan distance of the neighbor to (ti,tj)\n            sort(nbr[i][j].begin(), nbr[i][j].end(),\n                 [&](int d1,int d2){\n                     int ni1=i+dx[d1], nj1=j+dy[d1];\n                     int ni2=i+dx[d2], nj2=j+dy[d2];\n                     int md1=abs(ni1-ti)+abs(nj1-tj);\n                     int md2=abs(ni2-ti)+abs(nj2-tj);\n                     return md1<md2;\n                 });\n        }\n    }\n\n    // BFS to find the shortest path in the union\u2010of\u2010trees graph\n    static int dist[20][20], pi_[20][20], pj_[20][20];\n    static char pm_[20][20];\n    const int INF = 1e9;\n    for(int i=0;i<20;i++)\n      for(int j=0;j<20;j++)\n        dist[i][j]=INF;\n\n    queue<pair<int,int>> q;\n    dist[si][sj]=0;\n    q.push({si,sj});\n    while(!q.empty()){\n        auto [i,j]=q.front(); q.pop();\n        if(i==ti && j==tj) break;\n        for(int d: nbr[i][j]){\n            int ni=i+dx[d], nj=j+dy[d];\n            if(dist[ni][nj] > dist[i][j]+1){\n                dist[ni][nj]=dist[i][j]+1;\n                pi_[ni][nj]=i; pj_[ni][nj]=j;\n                pm_[ni][nj]=dc[d];\n                q.push({ni,nj});\n            }\n        }\n    }\n\n    // Reconstruct the move sequence\n    vector<char> path;\n    if(dist[ti][tj]<INF){\n        int ci=ti, cj=tj;\n        while(!(ci==si && cj==sj)){\n            char c = pm_[ci][cj];\n            path.push_back(c);\n            int pi=pi_[ci][cj], pj=pj_[ci][cj];\n            ci=pi; cj=pj;\n        }\n        reverse(path.begin(), path.end());\n    }\n    int D = (int)path.size();\n    if(D==0){\n        // either already at office (rare) or no path\n        cout<<\"\\n\";\n        return 0;\n    }\n\n    // We will pick a uniform block\u2010size k, B = floor(200/k) full blocks,\n    // then distribute any rem = 200 - B*k extra instructions across\n    // the last rem blocks (1 each).\n    int k_cap = 200 / D;\n    if(k_cap < 1) k_cap = 1;\n    // precompute p^k\n    vector<double> ppow(k_cap+2, 1.0);\n    for(int i=1;i<=k_cap;i++) ppow[i] = ppow[i-1] * p;\n\n    // Negative\u2010Binomial enumeration to choose best k\n    double bestE = -1.0;\n    int best_k = 1, best_B = D;\n    for(int k=1;k<=k_cap;k++){\n        double pk = ppow[k];\n        double q  = 1.0 - pk;\n        int B = 200 / k;\n        if(B < D) continue;\n        // failures allowed in full\u2010block NB until the Dth success\n        int rmax = B - D;\n        // P_j = Prob exactly j failures before the Dth success (i.e. finish in block D+j)\n        // P_0 = q^D\n        double Pj = pow(q, D);\n        double E = Pj * (401.0 - k*(D+0));\n        for(int j=1;j<=rmax;j++){\n            // NB recurrence\n            Pj = Pj * ((D + j - 1.0)/ j) * (1.0 - q);\n            E += Pj * (401.0 - k*(D + j));\n        }\n        if(E > bestE){\n            bestE = E;\n            best_k = k;\n            best_B = B;\n        }\n    }\n\n    // Now build the actual instruction string of length exactly 200:\n    // give best_B blocks, each block = best_k or best_k+1 reps\n    // (we distribute rem = 200 - best_B*best_k across the last rem blocks)\n    int rem = 200 - best_B * best_k;\n    string out;\n    out.reserve(200);\n    for(int b=0;b<best_B;b++){\n        int blk = best_k + (b >= best_B - rem ? 1 : 0);\n        char c = path[b % D];\n        for(int t=0;t<blk;t++){\n            out.push_back(c);\n        }\n    }\n    // safety check (should be exactly 200)\n    if((int)out.size() > 200) out.resize(200);\n\n    cout << out << \"\\n\";\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Grid size\nstatic constexpr int H = 30, W = 30;\n// Directions: 0=left,1=up,2=right,3=down\nint di[4]={0,-1,0,1}, dj[4]={-1,0,1,0};\ninline int opp(int d){ return (d+2)&3; }\n\n// to_dir[s][d]: exit side if entering tile-state s from side d, or -1 if none.\nstatic const int to_dir[8][4] = {\n  { 1, 0,-1,-1},\n  { 3,-1,-1, 0},\n  {-1,-1, 3, 2},\n  {-1, 2, 1,-1},\n  { 1, 0, 3, 2},\n  { 3, 2, 1, 0},\n  { 2,-1, 0,-1},\n  {-1, 3,-1, 1}\n};\n\n// splitmix64 RNG\nstatic uint64_t rnd_state;\ninline uint64_t splitmix64(){\n  uint64_t z = (rnd_state += 0x9e3779b97f4a7c15ULL);\n  z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;\n  z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;\n  return z ^ (z >> 31);\n}\n// uniform in [0,1)\ninline double rnd01(){\n  return (splitmix64() >> 11) * (1.0/9007199254740992.0);\n}\n\n// rotate original tile-state s by r\u00d790\u00b0 CCW\ninline int rotateState(int s, int r){\n  if(s < 4)          return (s + r) & 3; // single-curve\n  else if(r & 1)     return s ^ 1;       // double-curve or straight flip\n  else               return s;\n}\n\nint main(){\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n\n  // seed RNG\n  rnd_state = chrono::steady_clock::now().time_since_epoch().count();\n\n  // read input\n  static int orig[H][W];\n  for(int i=0;i<H;i++){\n    string s; cin >> s;\n    for(int j=0;j<W;j++){\n      orig[i][j] = s[j] - '0';\n    }\n  }\n\n  // precompute open-side bitmasks\n  int openMask[8];\n  for(int s=0;s<8;s++){\n    int m=0;\n    for(int d=0;d<4;d++){\n      if(to_dir[s][d] != -1) m |= 1<<d;\n    }\n    openMask[s] = m;\n  }\n\n  // timers\n  auto now = chrono::steady_clock::now;\n  auto t0  = now();\n  const double TOTAL_TIME  = 1.90;\n  const double GREEDY_TIME = 0.18;\n\n  // rotation arrays\n  static int rot[H][W], bestRot[H][W], curMask[H][W];\n\n  // ---- Proxy score: sum of matched edges (counted +2) minus boundary penalties (-1) ----\n  auto computeLocalSum = [&](){\n    int S=0;\n    for(int i=0;i<H;i++)for(int j=0;j<W;j++){\n      int st = rotateState(orig[i][j], rot[i][j]);\n      int m  = openMask[st];\n      for(int d=0;d<4;d++) if(m & (1<<d)){\n        int ni=i+di[d], nj=j+dj[d];\n        if(ni>=0&&ni<H&&nj>=0&&nj<W){\n          int st2 = rotateState(orig[ni][nj], rot[ni][nj]);\n          if(openMask[st2] & (1<<opp(d))) S += 2;\n        } else {\n          S -= 1;\n        }\n      }\n    }\n    return S;\n  };\n\n  // ---- True cycle score: product of two longest loops ----\n  auto computeTrueScore = [&](){\n    static bool used[H][W][4];\n    memset(used, 0, sizeof(used));\n    static int st[H][W];\n    for(int i=0;i<H;i++)for(int j=0;j<W;j++)\n      st[i][j] = rotateState(orig[i][j], rot[i][j]);\n\n    vector<int> loops;\n    loops.reserve(H*W);\n    for(int i=0;i<H;i++)for(int j=0;j<W;j++){\n      for(int d=0; d<4; d++){\n        if(used[i][j][d]) continue;\n        int ex = to_dir[st[i][j]][d];\n        if(ex<0) continue;\n        int ni = i+di[ex], nj = j+dj[ex];\n        if(ni<0||ni>=H||nj<0||nj>=W) continue;\n        if(to_dir[st[ni][nj]][opp(ex)]<0) continue;\n        // walk the cycle\n        int si=i, sj=j, sd=d;\n        int ci=i, cj=j, cd=d, len=0;\n        while(true){\n          used[ci][cj][cd] = true;\n          int ed = to_dir[st[ci][cj]][cd];\n          if(ed<0) break;\n          int nci=ci+di[ed], ncj=cj+dj[ed];\n          if(nci<0||nci>=H||ncj<0||ncj>=W) break;\n          ci = nci; cj = ncj; cd = opp(ed); len++;\n          if(ci==si && cj==sj && cd==sd){\n            loops.push_back(len);\n            break;\n          }\n        }\n      }\n    }\n    if(loops.size()<2) return 0;\n    nth_element(loops.begin(), loops.begin()+1, loops.end(), greater<int>());\n    return loops[0] * loops[1];\n  };\n\n  // ---- Greedy one-sweep (choose each tile's best local orientation) ----\n  auto greedySweep = [&](){\n    for(int i=0;i<H;i++)for(int j=0;j<W;j++){\n      int curR = rot[i][j], bestR = curR, bestSc = INT_MIN;\n      for(int r=0;r<4;r++){\n        int st = rotateState(orig[i][j], r);\n        int m  = openMask[st], sc = 0;\n        for(int d=0;d<4;d++) if(m & (1<<d)){\n          int ni=i+di[d], nj=j+dj[d];\n          if(ni>=0&&ni<H&&nj>=0&&nj<W){\n            int st2 = rotateState(orig[ni][nj], rot[ni][nj]);\n            if(openMask[st2] & (1<<opp(d))) sc += 2;\n          } else {\n            sc -= 1;\n          }\n        }\n        if(sc > bestSc){\n          bestSc = sc;\n          bestR  = r;\n        }\n      }\n      rot[i][j] = bestR;\n    }\n  };\n\n  // ---- 1) MULTI-START GREEDY to seed bestRot ----\n  int bestTrue = 0, bestLocal = INT_MIN;\n  int starts = 0;\n  while(true){\n    if(starts>0 && chrono::duration<double>(now()-t0).count() > GREEDY_TIME)\n      break;\n    // random init\n    for(int i=0;i<H;i++)for(int j=0;j<W;j++)\n      rot[i][j] = int(splitmix64() & 3);\n    // a couple of sweeps\n    greedySweep();\n    greedySweep();\n\n    int ls = computeLocalSum();\n    int ts = computeTrueScore();\n    if(ls > bestLocal || (ls==bestLocal && ts>bestTrue)){\n      bestLocal = ls;\n      bestTrue  = ts;\n      for(int i=0;i<H;i++)for(int j=0;j<W;j++)\n        bestRot[i][j] = rot[i][j];\n    }\n\n    if(++starts >= 8) break;\n  }\n\n  // ---- initialize SA state from bestRot ----\n  for(int i=0;i<H;i++)for(int j=0;j<W;j++){\n    rot[i][j]    = bestRot[i][j];\n    int s        = rotateState(orig[i][j], rot[i][j]);\n    curMask[i][j]= openMask[s];\n  }\n  int curSum = bestLocal;\n\n  // ---- SA parameters ----\n  const double T0 = 4.0, T1 = 0.1;\n  double timeSoFar = chrono::duration<double>(now()-t0).count();\n  const double TIME_LEFT = TOTAL_TIME - timeSoFar - 0.02;\n  uint64_t iter = 0;\n  const int PROBE = 1<<12;  // every ~4k iters probe true-score\n\n  // ---- Main SA loop ----\n  while(true){\n    double elapsed = chrono::duration<double>(now()-t0).count() - timeSoFar;\n    if(elapsed > TIME_LEFT) break;\n    double frac = elapsed / TIME_LEFT;\n    double T = T0*(1-frac) + T1*frac;\n\n    // random neighbor move: choose tile & random new rotation\n    int i = int(splitmix64() % H);\n    int j = int(splitmix64() % W);\n    int oldR = rot[i][j];\n    int newR = int(splitmix64() & 3);\n    if(newR == oldR) continue;\n\n    int oldM = curMask[i][j];\n    int newM = openMask[ rotateState(orig[i][j], newR) ];\n    int delta = 0;\n\n    // compute global proxy delta\n    for(int d=0; d<4; d++){\n      int oH = (oldM>>d)&1;\n      int nH = (newM>>d)&1;\n      int ni = i+di[d], nj = j+dj[d];\n      if(ni>=0&&ni<H&&nj>=0&&nj<W){\n        int nh = (curMask[ni][nj]>>opp(d))&1;\n        if(nh) delta += 2*(nH - oH);\n      } else {\n        delta += (oH - nH);\n      }\n    }\n\n    // accept\n    if(delta >= 0 || rnd01() < exp(-double(-delta)/T)){\n      rot[i][j]    = newR;\n      curMask[i][j]= newM;\n      curSum      += delta;\n    }\n\n    // periodic true-score probe\n    if((++iter & (PROBE-1)) == 0){\n      int ts = computeTrueScore();\n      if(ts > bestTrue){\n        bestTrue = ts;\n        for(int x=0;x<H;x++)for(int y=0;y<W;y++)\n          bestRot[x][y] = rot[x][y];\n      }\n    }\n  }\n\n  // ---- output bestRot ----\n  string out;\n  out.reserve(H*W);\n  for(int i=0;i<H;i++){\n    for(int j=0;j<W;j++){\n      out.push_back(char('0' + bestRot[i][j]));\n    }\n  }\n  cout << out << \"\\n\";\n  return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\n//\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Fixed\u2010size UF (N\u00b2 \u2264 100), global arrays to avoid any vector allocations.\n//\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nstatic int  uf_p[100], uf_sz[100];\nstatic bool uf_cyc[100];\nstatic int  comp_sz[100];\nstatic bool comp_cyc[100];\n\ninline int uf_find(int x){\n    return uf_p[x]==x ? x : (uf_p[x] = uf_find(uf_p[x]));\n}\ninline void uf_unite(int a,int b){\n    int ra = uf_find(a), rb = uf_find(b);\n    if(ra==rb){\n        uf_cyc[ra] = true;\n    } else {\n        if(uf_sz[ra] < uf_sz[rb]) swap(ra,rb);\n        uf_p[rb]    = ra;\n        uf_sz[ra]  += uf_sz[rb];\n        uf_cyc[ra] |= uf_cyc[rb];\n    }\n}\n\n//\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// compute_best_tree: O(N\u00b2) DSU + scan, no allocations.\n//\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nint compute_best_tree(int N, const vector<int>& G){\n    int NN = N*N;\n    // reset DSU\n    for(int i=0;i<NN;i++){\n        uf_p[i]   = i;\n        uf_sz[i]  = 1;\n        uf_cyc[i] = false;\n    }\n    // build edges\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            int idx = i*N + j;\n            int v   = G[idx];\n            if(v==0) continue;\n            // down\u2013up\n            if(i+1<N){\n                int v2 = G[(i+1)*N + j];\n                if((v&8) && (v2&2)) uf_unite(idx, (i+1)*N + j);\n            }\n            // right\u2013left\n            if(j+1<N){\n                int v2 = G[i*N + (j+1)];\n                if((v&4) && (v2&1)) uf_unite(idx, i*N + (j+1));\n            }\n        }\n    }\n    // gather comp sizes & cycle\u2010flags\n    for(int i=0;i<NN;i++){\n        comp_sz[i]  = 0;\n        comp_cyc[i] = false;\n    }\n    for(int i=0;i<NN;i++){\n        int r = uf_find(i);\n        comp_sz[r]  = uf_sz[r];\n        comp_cyc[r] = uf_cyc[r];\n    }\n    // find the empty\u2010cell index\n    int empty_idx = -1;\n    for(int i=0;i<NN;i++){\n        if(G[i]==0){ empty_idx=i; break; }\n    }\n    // pick the largest acyclic component \u2260 empty\n    int best = 0;\n    for(int r=0;r<NN;r++){\n        if(r==empty_idx) continue;\n        if(uf_p[r]==r && !comp_cyc[r]){\n            best = max(best, comp_sz[r]);\n        }\n    }\n    return best;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    cin >> N >> T;\n    vector<int> G0(N*N);\n    int ex0=-1, ey0=-1;\n    for(int i=0;i<N;i++){\n        string s; cin>>s;\n        for(int j=0;j<N;j++){\n            char c=s[j];\n            int v = (c<='9'? c-'0' : c-'a'+10);\n            G0[i*N+j]=v;\n            if(v==0){ ex0=i; ey0=j; }\n        }\n    }\n\n    // U, D, L, R deltas\n    static const int dx[4]={-1,+1, 0,  0};\n    static const int dy[4]={ 0, 0,-1, +1};\n    static const char dc[4]={'U','D','L','R'};\n    static const int rev[4]={1,0,3,2};\n\n    // Timer\n    auto T0 = chrono::steady_clock::now();\n    auto elapsed = [&](){\n        return chrono::duration<double,milli>(\n            chrono::steady_clock::now() - T0\n        ).count();\n    };\n    const double TIME_LIMIT = 2950.0;  // ms\n\n    // Precompute the original board\u2019s tree\u2010size once\n    int origS = compute_best_tree(N, G0);\n\n    // Globals for the best\u2010ever board across all restarts\n    vector<int> bestG = G0;\n    int bestEx=ex0, bestEy=ey0;\n    int bestS = origS;\n    string bestMoves = \"\";\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    const double NEG_START = 0.30, NEG_END = 0.01;\n\n    // Multi\u2010restart loop\n    while(elapsed() < TIME_LIMIT){\n        // reset to original\n        vector<int> G = G0;\n        int ex = ex0, ey = ey0;\n        string curMoves; \n        curMoves.reserve(T);\n        int curS = origS;           // <\u2014 FIXED: start from original score NOT bestS\n\n        // PHASE 1: greedy single\u2010step hill\u2010climb\n        auto one_step = [&](){\n            if((int)curMoves.size() >= T || elapsed() > TIME_LIMIT) return false;\n            int bS=curS, bd=-1;\n            for(int d=0;d<4;d++){\n                int nx=ex+dx[d], ny=ey+dy[d];\n                if(nx<0||nx>=N||ny<0||ny>=N) continue;\n                int epos=ex*N+ey, tpos=nx*N+ny;\n                swap(G[epos], G[tpos]);\n                int s2 = compute_best_tree(N,G);\n                swap(G[epos], G[tpos]);\n                if(s2 > bS){\n                    bS=s2; bd=d;\n                }\n            }\n            if(bd<0) return false;\n            int nx=ex+dx[bd], ny=ey+dy[bd];\n            swap(G[ex*N+ey], G[nx*N+ny]);\n            ex=nx; ey=ny;\n            curMoves.push_back(dc[bd]);\n            curS = bS;\n            if(curS > bestS){\n                bestS=curS;\n                bestG=G; bestEx=ex; bestEy=ey;\n                bestMoves=curMoves;\n            }\n            return true;\n        };\n        while(one_step());\n\n        // PHASE 2: greedy two\u2010step hill\u2010climb\n        auto two_step = [&](){\n            if((int)curMoves.size()+2 > T || elapsed() > TIME_LIMIT) return false;\n            int bS=curS, bd1=-1, bd2=-1;\n            for(int d1=0;d1<4;d1++){\n                int x1=ex+dx[d1], y1=ey+dy[d1];\n                if(x1<0||x1>=N||y1<0||y1>=N) continue;\n                int e1=ex*N+ey, t1=x1*N+y1;\n                swap(G[e1], G[t1]);\n                for(int d2=0;d2<4;d2++){\n                    if(d2==rev[d1]) continue;\n                    int x2=x1+dx[d2], y2=y1+dy[d2];\n                    if(x2<0||x2>=N||y2<0||y2>=N) continue;\n                    int e2=x1*N+y1, t2=x2*N+y2;\n                    swap(G[e2], G[t2]);\n                    int s3 = compute_best_tree(N,G);\n                    swap(G[e2], G[t2]);\n                    if(s3 > bS){\n                        bS=s3; bd1=d1; bd2=d2;\n                    }\n                }\n                swap(G[e1], G[t1]);\n            }\n            if(bd1<0) return false;\n            // commit both moves\n            int nx1=ex+dx[bd1], ny1=ey+dy[bd1];\n            swap(G[ex*N+ey], G[nx1*N+ny1]);\n            ex=nx1; ey=ny1;\n            curMoves.push_back(dc[bd1]);\n\n            int nx2=ex+dx[bd2], ny2=ey+dy[bd2];\n            swap(G[ex*N+ey], G[nx2*N+ny2]);\n            ex=nx2; ey=ny2;\n            curMoves.push_back(dc[bd2]);\n\n            curS = bS;\n            if(curS > bestS){\n                bestS=curS;\n                bestG=G; bestEx=ex; bestEy=ey;\n                bestMoves=curMoves;\n            }\n            return true;\n        };\n        while(two_step());\n\n        // PHASE 3: simulated annealing / random\u2010walk\n        int movesUsed = curMoves.size();\n        int remain    = T - movesUsed;\n        int accepted  = 0, last_dir=-1;\n\n        for(int iter=0; accepted<remain; iter++){\n            if((iter&127)==0 && elapsed()>TIME_LIMIT) break;\n            int cand[4], nc=0;\n            for(int d=0;d<4;d++){\n                if(last_dir>=0 && d==rev[last_dir]) continue;\n                int nx=ex+dx[d], ny=ey+dy[d];\n                if(nx<0||nx>=N||ny<0||ny>=N) continue;\n                cand[nc++]=d;\n            }\n            if(nc==0) continue;\n            int d = cand[rng()%nc];\n\n            int epos=ex*N+ey, tpos=(ex+dx[d])*N + (ey+dy[d]);\n            swap(G[epos], G[tpos]);\n            int newS = compute_best_tree(N,G);\n            int delta = newS - curS;\n            bool doAccept = false;\n            if(delta>=0){\n                doAccept = true;\n            } else {\n                // linearly cool downhill\u2010prob\n                double p = NEG_START + (NEG_END-NEG_START) * (accepted/(double)remain);\n                if((rng()%1000) < int(p*1000)) doAccept=true;\n            }\n            if(doAccept){\n                ex+=dx[d]; ey+=dy[d];\n                curS = newS;\n                curMoves.push_back(dc[d]);\n                last_dir = d;\n                accepted++;\n                if(curS>bestS){\n                    bestS=curS;\n                    bestG=G; bestEx=ex; bestEy=ey;\n                    bestMoves=curMoves;\n                    if(bestS==N*N-1) break;\n                }\n            } else {\n                swap(G[epos], G[tpos]);\n            }\n        }\n        if(bestS==N*N-1) break;\n    }\n\n    // OUTPUT best found\n    cout << bestMoves << \"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstatic const int OFF     = 10000;\nstatic const int D1_OFF  = 20000;\nstatic const int MAX_CAND= 80;\n\nstruct Straw { int x,y,d1,d2; };\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N,K;\n    cin >> N >> K;\n    vector<int> a(11);\n    for(int d=1; d<=10; d++) cin >> a[d];\n\n    // Read strawberries and build marks\n    vector<Straw> P(N);\n    vector<int> xs(N), ys(N), ds1(N), ds2(N);\n    vector<bool> xmark(2*OFF+1,false), ymark(2*OFF+1,false),\n                 d1mark(2*D1_OFF+1,false), d2mark(2*D1_OFF+1,false);\n\n    for(int i=0;i<N;i++){\n        int x,y; cin>>x>>y;\n        int d1 = x+y, d2 = x-y;\n        P[i]={x,y,d1,d2};\n        xs[i]=x; ys[i]=y; ds1[i]=d1; ds2[i]=d2;\n        if(-OFF<=x&&x<=OFF)      xmark[x+OFF]=true;\n        if(-OFF<=y&&y<=OFF)      ymark[y+OFF]=true;\n        if(-D1_OFF<=d1&&d1<=D1_OFF) d1mark[d1+D1_OFF]=true;\n        if(-D1_OFF<=d2&&d2<=D1_OFF) d2mark[d2+D1_OFF]=true;\n    }\n    sort(xs.begin(), xs.end());\n    sort(ys.begin(), ys.end());\n    sort(ds1.begin(),ds1.end());\n    sort(ds2.begin(),ds2.end());\n\n    // 1) Poisson\u2010approx over all (v,h), keep top MAX_CAND\n    struct Cand{ double sc; int v,h; };\n    vector<Cand> approx;\n    approx.reserve(K*K/2);\n    for(int v=1; v<K; v++){\n        int hmax = K-v;\n        for(int h=1; h<=hmax; h++){\n            int M = (v+1)*(h+1);\n            double lam = double(N)/double(M);\n            double p0 = exp(-lam), pd = p0, sc = 0;\n            for(int d=1; d<=10; d++){\n                pd *= lam/d;        // P(d;\u03bb)\n                double bd = pd * M; // predicted #cells\n                sc += min<double>(a[d], bd);\n            }\n            approx.push_back({sc,v,h});\n        }\n    }\n    if((int)approx.size()>MAX_CAND){\n        nth_element(\n          approx.begin(),\n          approx.begin()+MAX_CAND,\n          approx.end(),\n          [](auto&A,auto&B){ return A.sc>B.sc; }\n        );\n        approx.resize(MAX_CAND);\n    }\n    sort(approx.begin(), approx.end(),\n         [](auto&A,auto&B){ return A.sc>B.sc; }\n    );\n\n    // helper to avoid slicing through a strawberry\u2010coordinate\n    auto find_safe = [&](int tgt, const vector<bool>& mark, int off){\n        for(int d=0; d<=2*off; d++){\n            int c1 = tgt - d;\n            if(c1>=-off && c1<=off && !mark[c1+off]) return c1;\n            int c2 = tgt + d;\n            if(c2>=-off && c2<=off && !mark[c2+off]) return c2;\n        }\n        return tgt;\n    };\n\n    // 2) Precompute quantiles on x,y,d1,d2\n    vector<vector<int>> qvx(K+1), qvy(K+1), qd1(K+1), qd2(K+1);\n    for(int v=1; v<=K; v++){\n        if(v+1 > N) break;\n        auto &X = qvx[v], &D1 = qd1[v];\n        X.reserve(v); D1.reserve(v);\n        for(int j=1; j<=v; j++){\n            int idx = j*N/(v+1);\n            int lx=xs[idx-1], hx=xs[idx];\n            X.push_back(find_safe((lx+hx)/2, xmark, OFF));\n            int l1=ds1[idx-1], h1=ds1[idx];\n            D1.push_back(find_safe((l1+h1)/2, d1mark, D1_OFF));\n        }\n        sort(X.begin(),X.end());\n        sort(D1.begin(),D1.end());\n    }\n    for(int h=1; h<=K; h++){\n        if(h+1 > N) break;\n        auto &Y = qvy[h], &D2 = qd2[h];\n        Y.reserve(h); D2.reserve(h);\n        for(int j=1; j<=h; j++){\n            int idx = j*N/(h+1);\n            int ly=ys[idx-1], hy=ys[idx];\n            Y.push_back(find_safe((ly+hy)/2, ymark, OFF));\n            int l2=ds2[idx-1], h2=ds2[idx];\n            D2.push_back(find_safe((l2+h2)/2, d2mark, D1_OFF));\n        }\n        sort(Y.begin(),Y.end());\n        sort(D2.begin(),D2.end());\n    }\n\n    // 3) exact\u2010eval\n    vector<int> cnt;\n    cnt.reserve((K+1)*(K+1));\n    auto eval_cart = [&](int v,int h,const vector<int>& vx,const vector<int>& vy){\n        int C=v+1,R=h+1, M=C*R;\n        cnt.assign(M,0);\n        for(auto &s: P){\n            int c = int(lower_bound(vx.begin(),vx.end(),s.x)-vx.begin());\n            int r = int(lower_bound(vy.begin(),vy.end(),s.y)-vy.begin());\n            cnt[r*C + c]++;\n        }\n        int bd[11]={};\n        for(int i=0;i<M;i++){\n            int c=cnt[i];\n            if(1<=c&&c<=10) bd[c]++;\n        }\n        ll sum=0;\n        for(int d=1; d<=10; d++) sum += min<ll>(a[d], bd[d]);\n        return sum;\n    };\n    auto eval_diag = [&](int v,int h,const vector<int>& A,const vector<int>& B){\n        int C=v+1,R=h+1, M=C*R;\n        cnt.assign(M,0);\n        for(auto &s: P){\n            int c = int(lower_bound(A.begin(), A.end(), s.d1)-A.begin());\n            int r = int(lower_bound(B.begin(), B.end(), s.d2)-B.begin());\n            cnt[r*C + c]++;\n        }\n        int bd[11]={};\n        for(int i=0;i<M;i++){\n            int c=cnt[i];\n            if(1<=c&&c<=10) bd[c]++;\n        }\n        ll sum=0;\n        for(int d=1; d<=10; d++) sum += min<ll>(a[d], bd[d]);\n        return sum;\n    };\n    auto pick_uniform = [&](int steps,const vector<bool>& mark,int off){\n        vector<int> out;\n        out.reserve(steps-1);\n        for(int j=1; j<steps; j++){\n            double raw = -double(off) + (2.0*off*j)/double(steps);\n            out.push_back(find_safe(int(round(raw)), mark, off));\n        }\n        sort(out.begin(), out.end());\n        return out;\n    };\n\n    // 4) try top candidates under 5 layouts\n    ll best_sum = -1;\n    int best_v=1, best_h=1;\n    vector<int> best_vx, best_vy, best_d1, best_d2;\n\n    for(auto &C: approx){\n        int v=C.v, h=C.h;\n        auto ux = pick_uniform(v+1, xmark, OFF);\n        auto uy = pick_uniform(h+1, ymark, OFF);\n        bool canQ = int(qvx[v].size())==v && int(qvy[h].size())==h;\n        bool canD = int(qd1[v].size())==v && int(qd2[h].size())==h;\n\n        // (1) U\u00d7U\n        {\n            ll s = eval_cart(v,h, ux, uy);\n            if(s>best_sum){\n                best_sum=s; best_v=v; best_h=h;\n                best_vx=ux; best_vy=uy;\n                best_d1.clear(); best_d2.clear();\n            }\n        }\n        // (2) Q\u00d7Q\n        if(canQ){\n            ll s = eval_cart(v,h, qvx[v], qvy[h]);\n            if(s>best_sum){\n                best_sum=s; best_v=v; best_h=h;\n                best_vx=qvx[v]; best_vy=qvy[h];\n                best_d1.clear(); best_d2.clear();\n            }\n        }\n        // (3) Q\u00d7U\n        if(canQ){\n            ll s = eval_cart(v,h, qvx[v], uy);\n            if(s>best_sum){\n                best_sum=s; best_v=v; best_h=h;\n                best_vx=qvx[v]; best_vy=uy;\n                best_d1.clear(); best_d2.clear();\n            }\n        }\n        // (4) U\u00d7Q\n        if(canQ){\n            ll s = eval_cart(v,h, ux, qvy[h]);\n            if(s>best_sum){\n                best_sum=s; best_v=v; best_h=h;\n                best_vx=ux; best_vy=qvy[h];\n                best_d1.clear(); best_d2.clear();\n            }\n        }\n        // (5) Diagonal Q\u00d7Q\n        if(canD){\n            ll s = eval_diag(v,h, qd1[v], qd2[h]);\n            if(s>best_sum){\n                best_sum=s; best_v=v; best_h=h;\n                best_vx.clear(); best_vy.clear();\n                best_d1=qd1[v]; best_d2=qd2[h];\n            }\n        }\n    }\n\n    // 5) output\n    int printed=0;\n    if(!best_vx.empty()){\n        int total = best_vx.size() + best_vy.size();\n        int k = min(total, K);\n        cout << k << \"\\n\";\n        // vertical\n        for(int c: best_vx){\n            if(printed>=k) break;\n            cout << c << \" \" << -2*OFF << \"   \"\n                 << c << \" \" <<  2*OFF << \"\\n\";\n            printed++;\n        }\n        // horizontal\n        for(int c: best_vy){\n            if(printed>=k) break;\n            cout << -2*OFF << \" \" << c << \"   \"\n                 <<  2*OFF << \" \" << c << \"\\n\";\n            printed++;\n        }\n    } else {\n        // Diagonal\n        int total = best_d1.size() + best_d2.size();\n        int k = min(total, K);\n        cout << k << \"\\n\";\n        const ll S = 2LL*OFF;\n        // x+y = c\n        for(int c: best_d1){\n            if(printed>=k) break;\n            cout << (c+S) << \" \" << -S << \"   \"\n                 << -S      << \" \" << (c+S) << \"\\n\";\n            printed++;\n        }\n        // x\u2212y = c   <-- **Fixed endpoint here!**\n        for(int c: best_d2){\n            if(printed>=k) break;\n            // now both points lie on x\u2212y=c:\n            //    (c+S, S)  and  (c\u2212S, \u2212S)\n            cout << (c+S) << \" \" <<  S << \"   \"\n                 << (c-S) << \" \" << -S << \"\\n\";\n            printed++;\n        }\n    }\n\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// One operation record\nstruct Op {\n  int x1,y1, x2,y2, x3,y3, x4,y4;\n};\n\n// fast splitmix64\nstatic uint64_t rng_state;\ninline uint64_t rnd() {\n  uint64_t z = (rng_state += 0x9e3779b97f4a7c15ULL);\n  z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;\n  z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;\n  return z ^ (z >> 31);\n}\n\nint main(){\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n\n  int N,M;\n  cin >> N >> M;\n\n  // center\n  int C = (N-1)/2;\n  // precompute weights\n  static ll wgt[62][62];\n  for(int x=0;x<N;x++) for(int y=0;y<N;y++){\n    ll dx = x - C, dy = y - C;\n    wgt[x][y] = dx*dx + dy*dy + 1;\n  }\n  // mask_len[L] = (1<<L)-1\n  static uint64_t mask_len[62];\n  mask_len[0] = 0;\n  for(int i=1;i<=N;i++) mask_len[i] = (1ULL<<i) - 1;\n\n  // read initial seeds\n  vector<pair<int,int>> seeds(M);\n  for(int i=0;i<M;i++){\n    cin >> seeds[i].first >> seeds[i].second;\n  }\n  // sort them by descending weight\n  sort(seeds.begin(), seeds.end(),\n       [&](auto &a, auto &b){\n         return wgt[a.first][a.second] > wgt[b.first][b.second];\n       });\n\n  // occupancy & used-edge masks\n  static uint64_t dot_row[62]={}, dot_col[62]={};\n  static uint64_t used_h [62]={}, used_v [62]={};\n\n  // flatten into E_x/E_y (kept sorted by weight)\n  static int E_x[4000], E_y[4000];\n  int Esz = M;\n  for(int i=0;i<M;i++){\n    int x = seeds[i].first, y = seeds[i].second;\n    E_x[i]=x;  E_y[i]=y;\n    dot_row[y] |= (1ULL<<x);\n    dot_col[x] |= (1ULL<<y);\n  }\n\n  // RNG seed\n  rng_state = chrono::steady_clock::now().time_since_epoch().count();\n  auto t0 = chrono::steady_clock::now();\n  const double TL = 4.8;\n\n  vector<Op> ops;\n  ops.reserve(N*N);\n\n  while(true){\n    if(double(chrono::duration<double>(\n         chrono::steady_clock::now() - t0).count()) > TL) \n      break;\n    if(Esz < 2) break;\n\n    int T = min(2000, Esz*2);       // number of samples\n    int H = min(Esz,   600);       // bias corner #1 to the top\u2010H heaviest dots\n\n    ll bestW = -1;\n    Op bestOp{};\n\n    for(int t=0;t<T;t++){\n      int i = rnd() % H;\n      int j = rnd() % Esz;\n      if(i==j) continue;\n\n      int x2 = E_x[i], y2 = E_y[i];\n      int x4 = E_x[j], y4 = E_y[j];\n      if(x2==x4 || y2==y4) continue;\n\n      // axis\u2010aligned bounding box\n      int xa = min(x2,x4), xb = max(x2,x4);\n      int ya = min(y2,y4), yb = max(y2,y4);\n      int Lh = xb - xa, Lv = yb - ya;\n\n      uint64_t he = mask_len[Lh] << xa;\n      uint64_t hi = (Lh>1 ? mask_len[Lh-1] << (xa+1) : 0ULL);\n      uint64_t ve = mask_len[Lv] << ya;\n      uint64_t vi = (Lv>1 ? mask_len[Lv-1] << (ya+1) : 0ULL);\n\n      // OPTION 1: new = (x4,y2), opp=(x2,y4)\n      {\n        int x1 = x4, y1 = y2, x3 = x2, y3 = y4;\n        // p1 must be empty, p3 must exist\n        if(((dot_row[y1] >> x1)&1)==0 &&\n           ((dot_row[y3] >> x3)&1)==1)\n        {\n          // check four sides: no used edges, no other dots on interior\n          if((used_h[y2]&he)==0 && (dot_row[y2]&hi)==0\n          && (used_v[x2]&ve)==0 && (dot_col[x2]&vi)==0\n          && (used_h[y4]&he)==0 && (dot_row[y4]&hi)==0\n          && (used_v[x4]&ve)==0 && (dot_col[x4]&vi)==0)\n          {\n            ll W = wgt[x1][y1];\n            if(W > bestW){\n              bestW = W;\n              bestOp = {x1,y1, x2,y2, x3,y3, x4,y4};\n            }\n          }\n        }\n      }\n\n      // OPTION 2: new = (x2,y4), opp=(x4,y2)\n      {\n        int x1 = x2, y1 = y4, x3 = x4, y3 = y2;\n        if(((dot_row[y1] >> x1)&1)==0 &&\n           ((dot_row[y3] >> x3)&1)==1)\n        {\n          if((used_h[y4]&he)==0 && (dot_row[y4]&hi)==0\n          && (used_v[x2]&ve)==0 && (dot_col[x2]&vi)==0\n          && (used_h[y2]&he)==0 && (dot_row[y2]&hi)==0\n          && (used_v[x4]&ve)==0 && (dot_col[x4]&vi)==0)\n          {\n            ll W = wgt[x1][y1];\n            if(W > bestW){\n              bestW = W;\n              bestOp = {x1,y1, x2,y2, x3,y3, x4,y4};\n            }\n          }\n        }\n      }\n    }\n\n    // no valid move found in our samples \u2192 stop\n    if(bestW < 0) break;\n\n    // COMMIT bestOp\n    int x1 = bestOp.x1, y1 = bestOp.y1;\n    int x2 = bestOp.x2, y2 = bestOp.y2;\n    int x4 = bestOp.x4, y4 = bestOp.y4;\n\n    // 1) place the new dot\n    dot_row[y1] |= (1ULL<<x1);\n    dot_col[x1] |= (1ULL<<y1);\n\n    // 2) insert into E_x/E_y, keeping sorted by weight\n    ll Wnew = wgt[x1][y1];\n    int lo=0, hi_idx=Esz;\n    while(lo<hi_idx){\n      int mid=(lo+hi_idx)>>1;\n      ll Wmid = wgt[E_x[mid]][E_y[mid]];\n      if(Wmid < Wnew) hi_idx=mid;\n      else lo=mid+1;\n    }\n    for(int k=Esz; k>lo; k--){\n      E_x[k]=E_x[k-1];\n      E_y[k]=E_y[k-1];\n    }\n    E_x[lo]=x1;\n    E_y[lo]=y1;\n    Esz++;\n\n    // 3) mark the four sides as \u201cused\u201d\n    {\n      int xa = min(x2,x4), xb = max(x2,x4);\n      int ya = min(y2,y4), yb = max(y2,y4);\n      int Lh = xb - xa, Lv = yb - ya;\n      uint64_t mhe = mask_len[Lh]<<xa;\n      uint64_t mve = mask_len[Lv]<<ya;\n      used_h[y2] |= mhe;\n      used_h[y4] |= mhe;\n      used_v[x2] |= mve;\n      used_v[x4] |= mve;\n    }\n\n    ops.push_back(bestOp);\n  }\n\n  // output\n  cout << ops.size() << \"\\n\";\n  for(auto &o: ops){\n    cout << o.x1<<\" \"<<o.y1<<\" \"\n         << o.x2<<\" \"<<o.y2<<\" \"\n         << o.x3<<\" \"<<o.y3<<\" \"\n         << o.x4<<\" \"<<o.y4<<\"\\n\";\n  }\n  return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\n// simulate one tilt on a 10\u00d710 grid\n// dir = 'F','B','L','R'\nstatic void tilt(const int in[10][10], int out[10][10], char dir){\n    // temp buffer for one line\n    int buf[10];\n    if(dir=='F'){\n        // push everything to i=0\n        for(int j=0;j<10;j++){\n            int m=0;\n            for(int i=0;i<10;i++) if(in[i][j]) buf[m++] = in[i][j];\n            for(int i=0;i<10;i++){\n                out[i][j] = (i<m ? buf[i] : 0);\n            }\n        }\n    } else if(dir=='B'){\n        // push everything to i=9\n        for(int j=0;j<10;j++){\n            int m=0;\n            for(int i=9;i>=0;i--) if(in[i][j]) buf[m++] = in[i][j];\n            for(int i=9, k=0;i>=0;i--,k++){\n                out[i][j] = (k<m ? buf[k] : 0);\n            }\n        }\n    } else if(dir=='L'){\n        // push everything to j=0\n        for(int i=0;i<10;i++){\n            int m=0;\n            for(int j=0;j<10;j++) if(in[i][j]) buf[m++] = in[i][j];\n            for(int j=0;j<10;j++){\n                out[i][j] = (j<m ? buf[j] : 0);\n            }\n        }\n    } else { // 'R'\n        // push everything to j=9\n        for(int i=0;i<10;i++){\n            int m=0;\n            for(int j=9;j>=0;j--) if(in[i][j]) buf[m++] = in[i][j];\n            for(int j=9,k=0;j>=0;j--,k++){\n                out[i][j] = (k<m ? buf[k] : 0);\n            }\n        }\n    }\n}\n\n// compute sum of (component size)^2 on a 10\u00d710 grid\nstatic int calcScore(const int g[10][10]){\n    bool vis[10][10]={0};\n    int qx[100], qy[100];\n    int total = 0;\n    static const int di[4]={-1,1,0,0}, dj[4]={0,0,-1,1};\n    for(int i=0;i<10;i++) for(int j=0;j<10;j++){\n        if(g[i][j] && !vis[i][j]){\n            int f = g[i][j];\n            int head=0, tail=0;\n            vis[i][j]=true;\n            qx[tail]=i; qy[tail]=j; tail++;\n            while(head<tail){\n                int x=qx[head], y=qy[head]; head++;\n                for(int d=0;d<4;d++){\n                    int ni=x+di[d], nj=y+dj[d];\n                    if(ni>=0&&ni<10&&nj>=0&&nj<10\n                       && !vis[ni][nj] && g[ni][nj]==f){\n                        vis[ni][nj]=true;\n                        qx[tail]=ni; qy[tail]=nj; tail++;\n                    }\n                }\n            }\n            total += tail*tail;\n        }\n    }\n    return total;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // read in the 100 flavors\n    int F[101];\n    for(int i=1;i<=100;i++){\n        cin >> F[i];\n    }\n\n    // the board, 0=empty, 1/2/3=flavor\n    int grid[10][10]={0};\n\n    // our \u201cdefault\u201d mapping so we only break it if there's a real gain\n    char defdir[4] = {0,'L','R','F',};\n\n    for(int t=1;t<=100;t++){\n        int p; \n        if(!(cin>>p)) break;\n        // locate the p-th empty cell in row-major (front-to-back, left-to-right)\n        int cnt=0, si=0, sj=0;\n        for(int i=0;i<10;i++){\n            for(int j=0;j<10;j++){\n                if(grid[i][j]==0){\n                    cnt++;\n                    if(cnt==p){\n                        si=i; sj=j;\n                        goto FOUND;\n                    }\n                }\n            }\n        }\n    FOUND:\n        grid[si][sj] = F[t];\n\n        // build candidate list: default first, then the other 3\n        char cand[4];\n        cand[0] = defdir[F[t]];\n        int m=1;\n        for(char c: {'F','B','L','R'}){\n            if(c!=cand[0]) cand[m++]=c;\n        }\n\n        // greedy pick\n        int bestScore = -1;\n        char bestDir = cand[0];\n        int tmp[10][10];\n        for(int k=0;k<4;k++){\n            char d = cand[k];\n            tilt(grid, tmp, d);\n            int sc = calcScore(tmp);\n            if(sc > bestScore){\n                bestScore = sc;\n                bestDir = d;\n            }\n        }\n\n        // apply bestDir to our real grid\n        tilt(grid, tmp, bestDir);\n        for(int i=0;i<10;i++)\n            for(int j=0;j<10;j++)\n                grid[i][j] = tmp[i][j];\n\n        // output & flush\n        cout << bestDir << '\\n' << flush;\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    // 1) pick minimal N so that L = N*(N-1)/2 >= M-1\n    int N = 4;\n    int L = N*(N-1)/2;\n    while(L < M-1){\n        ++N;\n        L = N*(N-1)/2;\n    }\n    cout << N << \"\\n\";\n\n    // 2) precompute the lex\u2010order edge list edges[b] = (i,j)\n    vector<pair<int,int>> edges;\n    edges.reserve(L);\n    for(int i=0;i<N;i++){\n        for(int j=i+1;j<N;j++){\n            edges.emplace_back(i,j);\n        }\n    }\n\n    // 3) emit G_k as first k edges = '1', rest '0'\n    //    also build degG[k] = sorted degree\u2010vector of G_k\n    vector<vector<int>> degG(M, vector<int>(N, 0));\n    for(int k=0;k<M;k++){\n        // output bitstring\n        int ones = min(k, L);\n        cout << string(ones, '1') << string(L - ones, '0') << \"\\n\";\n        // build degree vector incrementally\n        if(k>0){\n            degG[k] = degG[k-1];\n            if(k-1 < L){\n                auto [u,v] = edges[k-1];\n                degG[k][u]++;\n                degG[k][v]++;\n            }\n        }\n        // for k=0 already zeroed\n    }\n    cout << flush;\n\n    // sort each prototype's degree\u2010vector\n    for(int k=0;k<M;k++){\n        sort(degG[k].begin(), degG[k].end());\n    }\n\n    // 4) answer 100 queries\n    const int W = 3;  // window around raw estimate\n    for(int qi=0; qi<100; qi++){\n        string H;\n        cin >> H;\n        if(!cin) break;\n        // count 1's and build H's degree\u2010vector\n        int cnt = 0;\n        vector<int> degH(N, 0);\n        for(int b=0;b<L;b++){\n            if(H[b]=='1'){\n                ++cnt;\n                auto [u,v] = edges[b];\n                degH[u]++;\n                degH[v]++;\n            }\n        }\n        // sort H's degrees\n        sort(degH.begin(), degH.end());\n\n        // 4a) raw linear inverse\n        double denom = 1.0 - 2.0*eps;\n        double kd = eps*L;\n        double x;\n        if(fabs(denom) < 1e-9){\n            x = cnt; // fallback (shouldn't happen for eps<=0.4)\n        } else {\n            x = double(cnt - kd) / denom;\n        }\n        int k0 = int(round(x));\n        k0 = max(0, min(M-1, k0));\n\n        // 4b) refine on [k0-W .. k0+W]\n        int lo = max(0, k0 - W), hi = min(M-1, k0 + W);\n        int bestK = k0;\n        long long bestCost = LLONG_MAX;\n        for(int k=lo; k<=hi; k++){\n            // L1 distance between degH and degG[k]\n            long long c = 0;\n            for(int i=0;i<N;i++){\n                c += abs(degH[i] - degG[k][i]);\n            }\n            // prefer smaller cost, tie\u2010break by closeness to k0\n            if(c < bestCost || (c==bestCost && abs(k - k0) < abs(bestK - k0))){\n                bestCost = c;\n                bestK = k;\n            }\n        }\n\n        cout << bestK << \"\\n\" << flush;\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nstatic const ll INF = (ll)4e18;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // --------------- INPUT ----------------\n    int N,M,D,K;\n    cin >> N >> M >> D >> K;\n    vector<int> U(M), V(M);\n    vector<ll> 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    // skip coords\n    for(int i=0;i<N;i++){\n        int x,y; cin >> x >> y;\n    }\n\n    // ------------- BUILD INCIDENCE & DEGREE ------------\n    vector<vector<int>> inc(N);\n    vector<int> deg(N,0);\n    for(int e=0;e<M;e++){\n        inc[U[e]].push_back(e);\n        inc[V[e]].push_back(e);\n        deg[U[e]]++;\n        deg[V[e]]++;\n    }\n\n    // --------------- BRANDES SOURCES ----------------\n    int B = min(N,150);    // a bit smaller to save time\n    vector<int> vid(N);\n    iota(vid.begin(), vid.end(), 0);\n    // pick top B/2 by degree\n    nth_element(vid.begin(), vid.begin()+B/2, vid.end(),\n                [&](int a,int b){ return deg[a]>deg[b]; });\n    vector<int> srcs;\n    srcs.reserve(B);\n    for(int i=0;i<B/2;i++) srcs.push_back(vid[i]);\n    // + B/2 random\n    mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());\n    shuffle(vid.begin(), vid.end(), rng);\n    for(int i=0; (int)srcs.size()<B; i++){\n        srcs.push_back(vid[i]);\n    }\n\n    // --------------- APPROXIMATE CENTRALITY ---------------\n    vector<double> central(M,0.0);\n    vector<ll> dist(N);\n    vector<double> sigma(N), delta(N);\n    vector<vector<pair<int,int>>> pred(N);\n    vector<int> S; \n    S.reserve(N);\n\n    auto time_start = chrono::steady_clock::now();\n\n    for(int s: srcs){\n        // init\n        fill(dist.begin(), dist.end(), INF);\n        fill(sigma.begin(), sigma.end(), 0.0);\n        for(auto &v: pred) v.clear();\n        dist[s]=0; sigma[s]=1.0;\n        S.clear();\n        // Dijkstra\n        using pli = pair<ll,int>;\n        priority_queue<pli,vector<pli>,greater<pli>> pq;\n        pq.push({0,s});\n        while(!pq.empty()){\n            auto [d,u] = pq.top(); pq.pop();\n            if(d!=dist[u]) continue;\n            S.push_back(u);\n            for(int e: inc[u]){\n                int v = U[e]^V[e]^u;\n                ll nd = d + W[e];\n                if(nd < dist[v]){\n                    dist[v]=nd;\n                    sigma[v]=sigma[u];\n                    pred[v].clear();\n                    pred[v].push_back({u,e});\n                    pq.push({nd,v});\n                } else if(nd==dist[v]){\n                    sigma[v]+=sigma[u];\n                    pred[v].push_back({u,e});\n                }\n            }\n        }\n        // accumulate\n        fill(delta.begin(), delta.end(), 0.0);\n        for(int i=(int)S.size()-1;i>=0;i--){\n            int w=S[i];\n            for(auto &pe: pred[w]){\n                int v=pe.first, e=pe.second;\n                double c=(sigma[v]/sigma[w])*(1.0+delta[w]);\n                delta[v]+=c;\n                central[e]+=c;\n            }\n        }\n    }\n\n    // --------------- INITIAL LPT PACKING ---------------\n    // weighted score\n    vector<double> wscore(M);\n    for(int e=0;e<M;e++){\n        wscore[e] = central[e] * (double)W[e];\n    }\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int a,int b){ return wscore[a]>wscore[b]; });\n\n    vector<int> ans(M,0), daycnt(D+1,0);\n    vector<double> daysum(D+1,0.0);\n    // vday[u][d] = how many of u's edges are on day d\n    vector<vector<int>> vday(N, vector<int>(D+1,0));\n\n    for(int e: order){\n        int bestD=-1;\n        double bestL=1e300;\n        // prefer no-conflict\n        for(int d=1;d<=D;d++){\n            if(daycnt[d]>=K) continue;\n            if(vday[U[e]][d]||vday[V[e]][d]) continue;\n            if(daysum[d]<bestL){\n                bestL=daysum[d];\n                bestD=d;\n            }\n        }\n        if(bestD<0){\n            for(int d=1;d<=D;d++){\n                if(daycnt[d]>=K) continue;\n                if(daysum[d]<bestL){\n                    bestL=daysum[d];\n                    bestD=d;\n                }\n            }\n        }\n        ans[e]=bestD;\n        daycnt[bestD]++;\n        daysum[bestD]+=wscore[e];\n        vday[U[e]][bestD]++;\n        vday[V[e]][bestD]++;\n    }\n\n    // build per-day lists & pos\n    vector<vector<int>> dayEdges(D+1);\n    vector<int> pos(M,-1);\n    for(int e=0;e<M;e++){\n        int d=ans[e];\n        pos[e]=(int)dayEdges[d].size();\n        dayEdges[d].push_back(e);\n    }\n\n    // measure how long we spent so far\n    auto assign_done = chrono::steady_clock::now();\n    double used = chrono::duration<double>(assign_done - time_start).count();\n    // leave a 0.3s margin\n    double TL_local = max(0.2, 5.7 - used);\n\n    // --------------- LOCAL SEARCH ---------------\n    auto local_start = chrono::steady_clock::now();\n    double curMax = *max_element(daysum.begin()+1, daysum.begin()+D+1);\n    int iter=0;\n\n    while(true){\n        if((++iter & 0x1FF)==0){\n            double t = chrono::duration<double>(\n                chrono::steady_clock::now() - local_start).count();\n            if(t > TL_local) break;\n        }\n        // pick heaviest & lightest\n        int dmax=1, dmin=1;\n        for(int d=2;d<=D;d++){\n            if(daysum[d]>daysum[dmax]) dmax=d;\n            if(daysum[d]<daysum[dmin]) dmin=d;\n        }\n        if(dmax==dmin) break;\n        // flip a coin\n        if(rng()&1){\n            // PAIR\u2010SWAP\n            auto &A = dayEdges[dmax];\n            auto &B = dayEdges[dmin];\n            if(A.empty()||B.empty()) continue;\n            int e1 = A[rng()%A.size()];\n            int e2 = B[rng()%B.size()];\n            if(e1==e2) continue;\n\n            // remove vday temporarily\n            vday[U[e1]][dmax]--; vday[V[e1]][dmax]--;\n            vday[U[e2]][dmin]--; vday[V[e2]][dmin]--;\n\n            // conflict check\n            bool conflict = false;\n            if(vday[U[e1]][dmin]||vday[V[e1]][dmin]||\n               vday[U[e2]][dmax]||vday[V[e2]][dmax]){\n                conflict=true;\n            }\n            if(conflict){\n                // revert vday\n                vday[U[e1]][dmax]++; vday[V[e1]][dmax]++;\n                vday[U[e2]][dmin]++; vday[V[e2]][dmin]++;\n                continue;\n            }\n\n            // compute new loads & new global max\n            double ndx = daysum[dmax] - wscore[e1] + wscore[e2];\n            double ndn = daysum[dmin] - wscore[e2] + wscore[e1];\n            double newMax = max(ndx, ndn);\n            for(int d=1; d<=D; d++){\n                if(d==dmax||d==dmin) continue;\n                if(daysum[d]>newMax) newMax=daysum[d];\n            }\n            if(!(newMax + 1e-9 < curMax)){\n                // no improvement \u2192 revert vday\n                vday[U[e1]][dmax]++; vday[V[e1]][dmax]++;\n                vday[U[e2]][dmin]++; vday[V[e2]][dmin]++;\n                continue;\n            }\n\n            // ACCEPT the swap:\n            // 1) remove both edges from their old day\u2010lists\n            //    (use the original pos[] before any overwrite)\n            int i1 = pos[e1], i2 = pos[e2];\n            // remove e1 from A\n            {\n                int back = A.back();\n                A[i1] = back; pos[back] = i1;\n                A.pop_back();\n            }\n            // remove e2 from B\n            {\n                int back = B.back();\n                B[i2] = back; pos[back] = i2;\n                B.pop_back();\n            }\n            // 2) insert swapped\n            pos[e2] = (int)A.size(); A.push_back(e2);\n            pos[e1] = (int)B.size(); B.push_back(e1);\n\n            // update everything\n            ans[e1] = dmin; ans[e2] = dmax;\n            daysum[dmax] = ndx;\n            daysum[dmin] = ndn;\n            // vday new\u2010day\n            vday[U[e1]][dmin]++; vday[V[e1]][dmin]++;\n            vday[U[e2]][dmax]++; vday[V[e2]][dmax]++;\n            curMax = newMax;\n        }\n        else {\n            // SINGLE\u2010MOVE from dmax -> dmin\n            auto &A = dayEdges[dmax];\n            if(A.empty()) continue;\n            int e = A[rng()%A.size()];\n            if(daycnt[dmin]>=K) continue;\n            if(vday[U[e]][dmin]||vday[V[e]][dmin]) continue;\n\n            double ndx = daysum[dmax] - wscore[e];\n            double ndn = daysum[dmin] + wscore[e];\n            double newMax = max(ndx, ndn);\n            for(int d=1; d<=D; d++){\n                if(d==dmax||d==dmin) continue;\n                if(daysum[d]>newMax) newMax=daysum[d];\n            }\n            if(!(newMax + 1e-9 < curMax)) continue;\n\n            // ACCEPT move\n            // remove e from A\n            {\n                int i = pos[e];\n                int back = A.back();\n                A[i] = back; pos[back] = i;\n                A.pop_back();\n            }\n            // add e to B\n            auto &B = dayEdges[dmin];\n            pos[e] = (int)B.size();\n            B.push_back(e);\n\n            ans[e] = dmin;\n            daycnt[dmax]--; daycnt[dmin]++;\n            daysum[dmax] = ndx;\n            daysum[dmin] = ndn;\n            vday[U[e]][dmax]--; vday[V[e]][dmax]--;\n            vday[U[e]][dmin]++; vday[V[e]][dmin]++;\n            curMax = newMax;\n        }\n    }\n\n    // --------------- OUTPUT ----------------\n    // direct buffered output\n    string buf;\n    buf.reserve(M*4);\n    for(int i=0;i<M;i++){\n        buf += char('0'+ (ans[i]/10000)%10); // dummy to speed up, you could do to_string\n        // but simplest: use ostringstream if you prefer correctness over micro\u2010opt.\n        buf += '0'; // placeholder\n        buf += ' '; \n    }\n    // well, for correctness let's just do:\n    for(int i=0;i<M;i++){\n        cout << ans[i] << (i+1<M?' ':'\\n');\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\n    int D;\n    cin >> D;\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for(int i = 0; i < D; i++) cin >> f1[i];\n    for(int i = 0; i < D; i++) cin >> r1[i];\n    for(int i = 0; i < D; i++) cin >> f2[i];\n    for(int i = 0; i < D; i++) cin >> r2[i];\n\n    int N = D*D*D;\n    auto idx = [&](int x,int y,int z){ return x*D*D + y*D + z; };\n\n    // build minimal\u2010cover shapes\n    vector<char> need1(N,0), need2(N,0);\n\n    auto build_min_shape = [&](const vector<string>& F, const vector<string>& R, vector<char>& need){\n        // for each z\u2010slice, solve the bipartite min\u2010edge\u2010cover on Sx\u00d7Sy\n        for(int z = 0; z < D; z++){\n            vector<int> Sx, Sy;\n            Sx.reserve(D); Sy.reserve(D);\n            for(int x = 0; x < D; x++) if(F[z][x]=='1') Sx.push_back(x);\n            for(int y = 0; y < D; y++) if(R[z][y]=='1') Sy.push_back(y);\n            int a = Sx.size(), b = Sy.size();\n            if(a==0 || b==0) continue;  // by problem guarantee this won't happen\n            \n            int m = min(a,b);\n            // 1) matching edges Sx[i]\u2013Sy[i] for i<m\n            for(int i = 0; i < m; i++){\n                int x = Sx[i], y = Sy[i];\n                need[idx(x,y,z)] = 1;\n            }\n            // 2) cover the leftover vertices\n            if(a > b){\n                // some x are unmatched, cover them by pairing to Sy[0]\n                int y0 = Sy[0];\n                for(int i = b; i < a; i++){\n                    int x = Sx[i];\n                    need[idx(x,y0,z)] = 1;\n                }\n            } else if(b > a){\n                // some y unmatched, cover by pairing to Sx[0]\n                int x0 = Sx[0];\n                for(int i = a; i < b; i++){\n                    int y = Sy[i];\n                    need[idx(x0,y,z)] = 1;\n                }\n            }\n        }\n    };\n\n    build_min_shape(f1, r1, need1);\n    build_min_shape(f2, r2, need2);\n\n    // We'll extract the intersection voxels, BFS to get 6\u2010connected components,\n    // and assign each component one common block.\n    vector<int> b1(N,0), b2(N,0);\n    vector<char> vis(N,0);\n    int block_id = 0;\n    static const int dx[6]={1,-1,0,0,0,0},\n                     dy[6]={0,0,1,-1,0,0},\n                     dz[6]={0,0,0,0,1,-1};\n\n    // 1) find CCs in intersection\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          int i = idx(x,y,z);\n          if(!vis[i] && need1[i] && need2[i]){\n            // BFS this component\n            queue<array<int,3>> q;\n            q.push({x,y,z});\n            vis[i]=1;\n            vector<int> comp;\n            comp.reserve(64);\n\n            while(!q.empty()){\n              auto c = q.front(); q.pop();\n              int cx=c[0], cy=c[1], cz=c[2];\n              int ci = idx(cx,cy,cz);\n              comp.push_back(ci);\n              for(int d=0;d<6;d++){\n                int nx=cx+dx[d], ny=cy+dy[d], nz=cz+dz[d];\n                if(nx<0||nx>=D||ny<0||ny>=D||nz<0||nz>=D) continue;\n                int ni = idx(nx,ny,nz);\n                if(!vis[ni] && need1[ni] && need2[ni]){\n                  vis[ni]=1;\n                  q.push({nx,ny,nz});\n                }\n              }\n            }\n            // assign one block to the entire component\n            ++block_id;\n            for(int vi: comp){\n              b1[vi] = block_id;\n              b2[vi] = block_id;\n            }\n          }\n        }\n      }\n    }\n\n    // 2) leftover voxels unique to silhouette1\n    for(int i=0;i<N;i++){\n      if(need1[i] && !need2[i]){\n        ++block_id;\n        b1[i] = block_id;\n      }\n    }\n    // 3) leftover voxels unique to silhouette2\n    for(int i=0;i<N;i++){\n      if(need2[i] && !need1[i]){\n        ++block_id;\n        b2[i] = block_id;\n      }\n    }\n\n    // output\n    cout << block_id << \"\\n\";\n    for(int i=0;i<N;i++){\n      cout << b1[i] << (i+1==N?'\\n':' ');\n    }\n    for(int i=0;i<N;i++){\n      cout << b2[i] << (i+1==N?'\\n':' ');\n    }\n\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll INF = (1LL<<60);\n\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n): p(n), r(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 SteinerInfo {\n    vector<int> sourceList;             \n    vector<pair<int,int>> steinerPairs; \n    vector<ll> steinerW;                \n    vector<int> B;                      \n    ll cableCost;\n};\n\nint N, M;\nvector<vector<pair<int,pair<ll,int>>>> g;\n\n// Compute the 2-approx Steiner tree on `terminals` via MST in the metric closure.\nSteinerInfo buildSteiner(const vector<int>& terminals){\n    int T = terminals.size();\n    vector<vector<ll>> distFrom(T, vector<ll>(N, INF));\n    vector<vector<int>> parentEdge(T, vector<int>(N,-1)), parentNode(T, vector<int>(N,-1));\n    // 1) Dijkstra from each terminal\n    for(int si=0; si<T; si++){\n        int src = terminals[si];\n        auto &dist = distFrom[si];\n        dist[src]=0;\n        priority_queue<pair<ll,int>, vector<pair<ll,int>>, greater<>> pq;\n        pq.push({0,src});\n        while(!pq.empty()){\n            auto [cd,u]=pq.top(); pq.pop();\n            if(cd>dist[u]) continue;\n            for(auto &ed: g[u]){\n                int v=ed.first, eid=ed.second.second;\n                ll w=ed.second.first;\n                if(dist[v]>cd+w){\n                    dist[v]=cd+w;\n                    parentEdge[si][v]=eid;\n                    parentNode[si][v]=u;\n                    pq.push({dist[v],v});\n                }\n            }\n        }\n    }\n    // 2) build complete graph on T vertices\n    struct E{ ll w; int i,j; };\n    vector<E> Kedges; Kedges.reserve(T*(T-1)/2);\n    for(int i=0;i<T;i++){\n        for(int j=i+1;j<T;j++){\n            ll d = distFrom[i][ terminals[j] ];\n            Kedges.push_back({d,i,j});\n        }\n    }\n    sort(Kedges.begin(), Kedges.end(),\n         [](auto &A, auto &B){ return A.w < B.w; });\n    // 3) Kruskal MST in that metric\n    DSU dsu(T);\n    vector<pair<int,int>> steinerPairs;\n    vector<ll> steinerW;\n    steinerPairs.reserve(T-1);\n    steinerW.reserve(T-1);\n    ll cableCost = 0;\n    for(auto &e: Kedges){\n        if(dsu.unite(e.i,e.j)){\n            steinerPairs.emplace_back(e.i,e.j);\n            steinerW.push_back(e.w);\n            cableCost += e.w;\n            if((int)steinerPairs.size()==T-1) break;\n        }\n    }\n    // 4) reconstruct original edges\n    vector<int> B(M,0);\n    for(int k=0;k<(int)steinerPairs.size();k++){\n        int si=steinerPairs[k].first,\n            sj=steinerPairs[k].second;\n        int u=terminals[si], v=terminals[sj];\n        int cur=v;\n        while(cur!=u){\n            int eid = parentEdge[si][cur];\n            B[eid]=1;\n            cur = parentNode[si][cur];\n        }\n    }\n    return {terminals, steinerPairs, steinerW, B, cableCost};\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int K;\n    cin >> N >> M >> K;\n    vector<ll> x(N), y(N);\n    for(int i=0;i<N;i++) cin>>x[i]>>y[i];\n    g.assign(N,{});\n    for(int j=0;j<M;j++){\n        int u,v; ll w;\n        cin>>u>>v>>w;\n        --u; --v;\n        g[u].push_back({v,{w,j}});\n        g[v].push_back({u,{w,j}});\n    }\n    vector<ll> a(K), b(K);\n    for(int i=0;i<K;i++) cin>>a[i]>>b[i];\n\n    // Precompute for each resident its top-3 nearest stations (distance^2, station)\n    vector<vector<pair<ll,int>>> nearest(K);\n    for(int r=0;r<K;r++){\n        nearest[r].reserve(3);\n        for(int i=0;i<N;i++){\n            ll dx=x[i]-a[r], dy=y[i]-b[r], d2=dx*dx+dy*dy;\n            nearest[r].push_back({d2,i});\n        }\n        sort(nearest[r].begin(), nearest[r].end());\n        if(nearest[r].size()>3) nearest[r].resize(3);\n    }\n\n    // Initial \u201cnearest-station\u201d assignment\n    vector<vector<int>> assignedLists(N);\n    for(int r=0;r<K;r++){\n        int i0 = nearest[r][0].second;\n        assignedLists[i0].push_back(r);\n    }\n\n    vector<int> bestP(N), bestB(M);\n    ll bestCost = INF;\n\n    const int MAX_ITERS = 50;\n    const int DROP_CUTOFF = 3;\n\n    for(int iter=0; iter<MAX_ITERS; iter++){\n        // 1) compute max_d2 and P[i]\n        vector<ll> max_d2(N,0);\n        for(int i=0;i<N;i++){\n            for(int r: assignedLists[i]){\n                ll dx=x[i]-a[r], dy=y[i]-b[r];\n                ll d2=dx*dx+dy*dy;\n                if(d2>max_d2[i]) max_d2[i]=d2;\n            }\n        }\n        vector<int> P(N,0);\n        for(int i=0;i<N;i++){\n            if(max_d2[i]>0){\n                ll d2=max_d2[i];\n                ll s=floor(sqrt((long double)d2));\n                while(s*s<d2) s++;\n                while(s>0 && (s-1)*(s-1)>=d2) s--;\n                P[i]=(int)s;\n            }\n        }\n        // 2) build terminal list\n        vector<int> terminals;\n        terminals.reserve(N);\n        terminals.push_back(0);\n        for(int i=1;i<N;i++) if(P[i]>0) terminals.push_back(i);\n        if(terminals.size()<=1) break;\n\n        // 3) build Steiner tree\n        auto info = buildSteiner(terminals);\n        ll cableCost = info.cableCost;\n        ll bc = 0;\n        for(int i=0;i<N;i++) bc += (ll)P[i]*P[i];\n        ll total = cableCost + bc;\n        if(total < bestCost){\n            bestCost = total;\n            bestP = P;\n            bestB = info.B;\n        }\n\n        // 4) try broadcast-only moves\n        ll bestDeltaBC = 0;\n        int bi=-1, br=-1, bj=-1;\n        for(int i=0;i<N;i++){\n            int sz = assignedLists[i].size();\n            if(sz<=1) continue;\n            // find farthest and 2nd-farthest resident\n            ll mx1=-1, mx2=-1; int r1=-1;\n            for(int r: assignedLists[i]){\n                ll d2 = (x[i]-a[r])*(x[i]-a[r]) + (y[i]-b[r])*(y[i]-b[r]);\n                if(d2>mx1){ mx2=mx1; mx1=d2; r1=r; }\n                else if(d2>mx2){ mx2=d2; }\n            }\n            // find r1's next-best station\n            int jj=-1; ll d2_j=0;\n            for(auto &pr: nearest[r1]){\n                if(pr.second!=i){\n                    jj=pr.second;\n                    d2_j=pr.first;\n                    break;\n                }\n            }\n            if(jj<0) continue;\n            // compute old and new P_i, P_j\n            auto CeilS = [&](ll d2){\n                ll s=floor(sqrt((long double)d2));\n                while(s*s<d2) s++;\n                while(s>0 && (s-1)*(s-1)>=d2) s--;\n                return s;\n            };\n            ll oldPi = P[i], newPi = CeilS(mx2);\n            ll oldPj = P[jj], newPj = CeilS(max(max_d2[jj], d2_j));\n            ll delta = (oldPi*oldPi + oldPj*oldPj) - (newPi*newPi + newPj*newPj);\n            if(delta > bestDeltaBC){\n                bestDeltaBC = delta;\n                bi=i; br=r1; bj=jj;\n            }\n        }\n        if(bestDeltaBC > 0){\n            // apply the broadcast move\n            auto &A = assignedLists[bi];\n            A.erase(find(A.begin(), A.end(), br));\n            assignedLists[bj].push_back(br);\n            continue;  // re-iterate\n        }\n\n        // 5) try drop-one-leaf move (<=DROP_CUTOFF residents)\n        int T = terminals.size();\n        vector<int> termIdx(N,-1);\n        for(int si=0;si<T;si++) termIdx[terminals[si]] = si;\n        ll bestDeltaDrop = 0;\n        int bestI = -1;\n        for(int i=1;i<N;i++){\n            int cnt = assignedLists[i].size();\n            if(cnt==0 || cnt>DROP_CUTOFF) continue;\n            int si = termIdx[i];\n            if(si<0) continue;\n            // cable saving = sum of MST edges incident to si\n            ll cableSaving=0;\n            for(int k=0;k<(int)info.steinerPairs.size();k++){\n                auto &pp = info.steinerPairs[k];\n                if(pp.first==si||pp.second==si)\n                    cableSaving += info.steinerW[k];\n            }\n            // broadcast increase\n            unordered_map<int,ll> newd;\n            for(int r: assignedLists[i]){\n                // assign r to next-best station\n                int jj=-1; ll d2j=0;\n                for(auto &pr: nearest[r]){\n                    if(pr.second!=i){\n                        jj=pr.second;\n                        d2j=pr.first;\n                        break;\n                    }\n                }\n                newd[jj] = max(newd[jj], d2j);\n            }\n            ll deltaB=0;\n            for(auto &pr: newd){\n                int j=pr.first; ll nd2=pr.second;\n                ll od2 = max_d2[j];\n                ll md2 = max(od2, nd2);\n                ll oldP=P[j];\n                ll np = floor(sqrt((long double)md2));\n                while(np*np<md2) np++;\n                while(np>0&&(np-1)*(np-1)>=md2) np--;\n                ll newP=np;\n                deltaB += (newP*newP - oldP*oldP);\n            }\n            ll delta = cableSaving + (ll)P[i]*P[i] - deltaB;\n            if(delta > bestDeltaDrop){\n                bestDeltaDrop = delta;\n                bestI = i;\n            }\n        }\n        if(bestI>=0){\n            // apply the drop\n            auto residents = assignedLists[bestI];\n            assignedLists[bestI].clear();\n            for(int r: residents){\n                int jj=-1; ll bd=INF;\n                for(auto &pr: nearest[r]){\n                    if(pr.second!=bestI){\n                        if(pr.first<bd){\n                            bd=pr.first;\n                            jj=pr.second;\n                        }\n                    }\n                }\n                assignedLists[jj].push_back(r);\n            }\n            continue;\n        }\n\n        // nothing improved, stop\n        break;\n    }\n\n    // final output\n    for(int i=0;i<N;i++){\n        cout<<bestP[i]<<(i+1<N?' ':'\\n');\n    }\n    for(int j=0;j<M;j++){\n        cout<<bestB[j]<<(j+1<M?' ':'\\n');\n    }\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nstatic const int N = 30;\nstatic const int M = N*(N+1)/2;  // 465\n\nstruct Move { int x1,y1,x2,y2; };\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // 1) Read the initial permutation\n    vector<int> posBall(M), curPos(M);\n    for(int x=0, idx=0; x<N; x++){\n        for(int y=0; y<=x; y++, idx++){\n            int b; \n            cin >> b;\n            posBall[idx] = b;\n            curPos[b] = idx;\n        }\n    }\n\n    // 2) id <-> (x,y) mappings\n    static int id2x[M], id2y[M];\n    auto xy2id = [&](int x,int y){ return x*(x+1)/2 + y; };\n    for(int x=0, idx=0; x<N; x++){\n        for(int y=0; y<=x; y++, idx++){\n            id2x[idx]=x;\n            id2y[idx]=y;\n        }\n    }\n\n    // 3) Build the 6\u2010neighbor adjacency on the triangular grid\n    static vector<int> adj[M];\n    for(int u=0; u<M; u++){\n        auto X = id2x[u], Y = id2y[u];\n        adj[u].clear();\n        if(X>0 && Y>0)      adj[u].push_back(xy2id(X-1,Y-1));\n        if(X>0 && Y<=X-1)   adj[u].push_back(xy2id(X-1,Y));\n        if(Y>0)             adj[u].push_back(xy2id(X  ,Y-1));\n        if(Y< X)            adj[u].push_back(xy2id(X  ,Y+1));\n        if(X+1< N){\n            adj[u].push_back(xy2id(X+1,Y));\n            adj[u].push_back(xy2id(X+1,Y+1));\n        }\n    }\n\n    // 4) Precompute all\u2010pairs shortest\u2010path distances distAll[u][v]\n    static int distAll[M][M];\n    static int Qtmp[M];\n    for(int s=0; s<M; s++){\n        auto dist = distAll[s];\n        // initialize\n        for(int i=0;i<M;i++) dist[i]=INT_MAX;\n        int qh=0, qt=0;\n        dist[s]=0;\n        Qtmp[qt++]=s;\n        while(qh<qt){\n            int u=Qtmp[qh++], du=dist[u];\n            for(int v: adj[u]){\n                if(dist[v] > du+1){\n                    dist[v]=du+1;\n                    Qtmp[qt++]=v;\n                }\n            }\n        }\n    }\n\n    // 5) We'll collect our swaps here\n    vector<Move> moves;\n    moves.reserve(M*8);\n\n    // 6) Prepare scratch space for the per\u2010ball BFS\n    static bool seen[M];\n    static int parentArr[M], Q[M], path[M];\n\n    // 7) Place balls in ascending label L=0..464\n    //    But skip L in the bottom row (no children, no E\u2010impact)\n    for(int L=0; L<M-N; L++){\n        int s = curPos[L], t = L;\n        if(s==t) continue;\n\n        // BFS on the subgraph { id>=L }, which is guaranteed connected\n        memset(seen, 0, sizeof(seen));\n        int qh=0, qt=0;\n        seen[s]=true;\n        parentArr[s]=-1;\n        Q[qt++]=s;\n\n        bool found=false;\n        while(qh<qt && !found){\n            int u = Q[qh++];\n            // gather up to 6 neighbors in a tiny array\n            int nbCnt=0;\n            static int nbV[6], nbD[6];\n            for(int v: adj[u]){\n                if(v < L) continue;      // locked prefix\n                if(seen[v]) continue;\n                seen[v]=true;\n                parentArr[v]=u;\n                // record for sorting\n                nbV[nbCnt] = v;\n                nbD[nbCnt] = distAll[v][t];\n                nbCnt++;\n            }\n            // insertion\u2010sort nbV[0..nbCnt) by nbD ascending\n            for(int i=1;i<nbCnt;i++){\n                int dv = nbD[i], vv=nbV[i], j=i;\n                while(j>0 && nbD[j-1] > dv){\n                    nbD[j]=nbD[j-1];\n                    nbV[j]=nbV[j-1];\n                    --j;\n                }\n                nbD[j]=dv; \n                nbV[j]=vv;\n            }\n            // enqueue in that \u201cbest\u2010first\u201d order\n            for(int i=0;i<nbCnt;i++){\n                int v=nbV[i];\n                Q[qt++]=v;\n                if(v==t){ found=true; break; }\n            }\n        }\n        // Reconstruct the path s -> \u2026 -> t\n        int plen=0;\n        for(int cur=t; cur!=-1; cur=parentArr[cur]){\n            path[plen++]=cur;\n        }\n        // path[] is in reverse (t\u2192\u2026\u2192s), so reverse it\n        for(int i=0;i<plen/2;i++){\n            swap(path[i], path[plen-1-i]);\n        }\n        // \u201cBubble\u201d L along that path\n        for(int i=1;i<plen;i++){\n            int u0=path[i-1], v0=path[i];\n            int A=posBall[u0], B=posBall[v0];\n            // swap in our model\n            posBall[u0]=B;  posBall[v0]=A;\n            curPos[A]=v0;   curPos[B]=u0;\n            // record the move\n            moves.push_back({\n                id2x[u0], id2y[u0],\n                id2x[v0], id2y[v0]\n            });\n        }\n    }\n\n    // 8) One final linear pass to strip out immediate \u201cundo\u201d swaps\n    vector<Move> clean;\n    clean.reserve(moves.size());\n    int K = (int)moves.size();\n    for(int i=0; i<K; i++){\n        if(i+1<K){\n            auto &a=moves[i], &b=moves[i+1];\n            bool same = (a.x1==b.x1 && a.y1==b.y1 && a.x2==b.x2 && a.y2==b.y2);\n            bool rev  = (a.x1==b.x2 && a.y1==b.y2 && a.x2==b.x1 && a.y2==b.y1);\n            if(same||rev){\n                i++; // skip both\n                continue;\n            }\n        }\n        clean.push_back(moves[i]);\n    }\n\n    // 9) Output\n    cout << clean.size() << \"\\n\";\n    for(auto &m: clean){\n        cout << m.x1 << \" \" << m.y1 << \" \"\n             << m.x2 << \" \" << m.y2 << \"\\n\";\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\nstatic const int MAXD = 9;\nint D, N, C;\nbool isObs[MAXD][MAXD];\nint dist0[MAXD][MAXD], deg0[MAXD][MAXD];\nint occ[MAXD][MAXD], posT[MAXD][MAXD], cellRank[MAXD][MAXD];\nint ex, ey;\nint dx[4]={1,-1,0,0}, dy[4]={0,0,1,-1};\ninline int ID(int i,int j){ return i*D+j; }\n\n// static all\u2010pairs distances ignoring containers\nint distAll[MAXD*MAXD][MAXD*MAXD];\nstruct P{ int x,y; };\nstatic P Q[MAXD*MAXD];\n\n// AP\u2010finding on current free graph\nstatic bool visitedAP[MAXD*MAXD], isAP[MAXD*MAXD];\nstatic int disc[MAXD*MAXD], low[MAXD*MAXD], parentAP[MAXD*MAXD], dfsTime;\nvoid dfs_art(int u){\n    visitedAP[u]=true;\n    disc[u]=low[u]=++dfsTime;\n    int ux=u/D, uy=u%D, child=0;\n    for(int k=0;k<4;k++){\n        int vx=ux+dx[k], vy=uy+dy[k];\n        if(vx<0||vx>=D||vy<0||vy>=D) continue;\n        if(occ[vx][vy]!=0) continue;\n        int v=ID(vx,vy);\n        if(!visitedAP[v]){\n            parentAP[v]=u; ++child;\n            dfs_art(v);\n            low[u]=min(low[u], low[v]);\n            if(parentAP[u]!=-1 && low[v]>=disc[u]) isAP[u]=true;\n        } else if(v!=parentAP[u]){\n            low[u]=min(low[u], disc[v]);\n        }\n    }\n    if(parentAP[u]==-1 && child>1) isAP[u]=true;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin>>D>>N;\n    ex=0; ey=(D-1)/2;\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++)\n        isObs[i][j]=false;\n    for(int i=0;i<N;i++){\n        int r,c; cin>>r>>c;\n        isObs[r][c]=true;\n    }\n\n    // 1) static BFS from entrance -> dist0\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++)\n        dist0[i][j]=-1;\n    int qs=0, qe=0;\n    dist0[ex][ey]=0; Q[qe++]={ex,ey};\n    while(qs<qe){\n        auto [x,y]=Q[qs++];\n        for(int k=0;k<4;k++){\n            int nx=x+dx[k], ny=y+dy[k];\n            if(nx<0||nx>=D||ny<0||ny>=D) continue;\n            if(isObs[nx][ny]||dist0[nx][ny]!=-1) continue;\n            dist0[nx][ny]=dist0[x][y]+1;\n            Q[qe++]={nx,ny};\n        }\n    }\n\n    // compute static degree deg0\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        if(isObs[i][j]){ deg0[i][j]=0; continue; }\n        int d=0;\n        for(int k=0;k<4;k++){\n            int ni=i+dx[k], nj=j+dy[k];\n            if(ni>=0&&ni<D&&nj>=0&&nj<D && !isObs[ni][nj])\n                d++;\n        }\n        deg0[i][j]=d;\n    }\n\n    // 2) precompute distAll[u][v] ignoring containers\n    int NC=D*D, INF=10000;\n    for(int u=0;u<NC;u++)\n        for(int v=0;v<NC;v++)\n            distAll[u][v]=INF;\n    for(int sx=0;sx<D;sx++) for(int sy=0;sy<D;sy++){\n        if(isObs[sx][sy]) continue;\n        int su=ID(sx,sy);\n        static int dloc[MAXD*MAXD];\n        for(int v=0;v<NC;v++) dloc[v]=INF;\n        int lqs=0, lqe=0;\n        dloc[su]=0; Q[lqe++]={sx,sy};\n        while(lqs<lqe){\n            auto [x,y]=Q[lqs++];\n            int cu=ID(x,y);\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(isObs[nx][ny]) continue;\n                int vu=ID(nx,ny);\n                if(dloc[vu]>dloc[cu]+1){\n                    dloc[vu]=dloc[cu]+1;\n                    Q[lqe++]={nx,ny};\n                }\n            }\n        }\n        for(int v=0;v<NC;v++)\n            distAll[su][v]=dloc[v];\n    }\n\n    // 3) build global list S sorted by (dist0 asc, deg0 desc, i, j)\n    vector<P> S;\n    S.reserve(NC);\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        if(isObs[i][j]||(i==ex&&j==ey)) continue;\n        S.push_back({i,j});\n    }\n    sort(S.begin(), S.end(), [&](auto &a, auto &b){\n        int da=dist0[a.x][a.y], db=dist0[b.x][b.y];\n        if(da!=db) return da<db;\n        int ga=deg0[a.x][a.y], gb=deg0[b.x][b.y];\n        if(ga!=gb) return ga>gb;\n        if(a.x!=b.x) return a.x<b.x;\n        return a.y<b.y;\n    });\n    for(int idx=0; idx<(int)S.size(); idx++){\n        cellRank[S[idx].x][S[idx].y]=idx;\n    }\n\n    // init occupancy\n    C=NC-1-N;\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        occ[i][j]=isObs[i][j]? -1:0;\n        posT[i][j]=-1;\n    }\n\n    // --- Storing phase ---\n    for(int step=0; step<C; step++){\n        int t; cin>>t;\n        // a) BFS over occ==0: mark reachable + record distCur\n        static bool vis[MAXD][MAXD];\n        static int distCur[MAXD][MAXD];\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            vis[i][j]=false; distCur[i][j]=INF;\n        }\n        int rqs=0, rqe=0;\n        vis[ex][ey]=true; distCur[ex][ey]=0;\n        Q[rqe++]={ex,ey};\n        while(rqs<rqe){\n            auto [x,y]=Q[rqs++];\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(vis[nx][ny]||occ[nx][ny]!=0) continue;\n                vis[nx][ny]=true;\n                distCur[nx][ny]=distCur[x][y]+1;\n                Q[rqe++]={nx,ny};\n            }\n        }\n        // b) mark APs\n        for(int u=0;u<NC;u++){\n            visitedAP[u]=false; isAP[u]=false; parentAP[u]=-1;\n        }\n        dfsTime=0;\n        dfs_art(ID(ex,ey));\n\n        // c) select minimizing (err, dyn, sta, -deg0, rank)\n        int sx=S[t].x, sy=S[t].y, su=ID(sx,sy);\n        int bestErr=INT_MAX, bestDyn=INF, bestSta=INF, bestDeg=-1, bestR=INT_MAX;\n        int bx=-1, by=-1;\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            if(i==ex&&j==ey) continue;\n            if(!vis[i][j]||occ[i][j]!=0) continue;\n            int u=ID(i,j);\n            if(isAP[u]) continue;\n            int r=cellRank[i][j];\n            int err=abs(r-t), dyn=distCur[i][j], sta=distAll[su][u], g=deg0[i][j];\n            if(err<bestErr\n            || (err==bestErr && dyn<bestDyn)\n            || (err==bestErr && dyn==bestDyn && sta<bestSta)\n            || (err==bestErr && dyn==bestDyn && sta==bestSta && g>bestDeg)\n            || (err==bestErr && dyn==bestDyn && sta==bestSta && g==bestDeg && r<bestR))\n            {\n                bestErr=err; bestDyn=dyn; bestSta=sta; bestDeg=g; bestR=r;\n                bx=i; by=j;\n            }\n        }\n        // fallback if none\n        if(bx<0){\n            for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n                if(i==ex&&j==ey) continue;\n                if(!vis[i][j]||occ[i][j]!=0) continue;\n                int u=ID(i,j);\n                int r=cellRank[i][j];\n                int err=abs(r-t), dyn=distCur[i][j], sta=distAll[su][u], g=deg0[i][j];\n                if(err<bestErr\n                || (err==bestErr && dyn<bestDyn)\n                || (err==bestErr && dyn==bestDyn && sta<bestSta)\n                || (err==bestErr && dyn==bestDyn && sta==bestSta && g>bestDeg)\n                || (err==bestErr && dyn==bestDyn && sta==bestSta && g==bestDeg && r<bestR))\n                {\n                    bestErr=err; bestDyn=dyn; bestSta=sta; bestDeg=g; bestR=r;\n                    bx=i; by=j;\n                }\n            }\n        }\n        occ[bx][by]=1;\n        posT[bx][by]=t;\n        cout<<bx<<\" \"<<by<<\"\\n\"<<flush;\n    }\n\n    // --- Retrieval phase: greedy on smallest tag ---\n    vector<pair<int,int>> answer;\n    answer.reserve(C);\n    for(int step=0; step<C; step++){\n        static bool vis2[MAXD][MAXD];\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++)\n            vis2[i][j]=false;\n        int rqs=0, rqe=0;\n        vis2[ex][ey]=true;\n        Q[rqe++]={ex,ey};\n        while(rqs<rqe){\n            auto [x,y]=Q[rqs++];\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(vis2[nx][ny]||occ[nx][ny]!=0) continue;\n                vis2[nx][ny]=true;\n                Q[rqe++]={nx,ny};\n            }\n        }\n        int pickT=INT_MAX, px=-1, py=-1;\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            if(occ[i][j]!=1) continue;\n            bool ok=false;\n            for(int k=0;k<4 && !ok;k++){\n                int nx=i+dx[k], ny=j+dy[k];\n                if(nx>=0&&nx<D&&ny>=0&&ny<D && vis2[nx][ny])\n                    ok=true;\n            }\n            if(!ok) continue;\n            int tt=posT[i][j];\n            if(tt<pickT){\n                pickT=tt; px=i; py=j;\n            }\n        }\n        occ[px][py]=0;\n        answer.emplace_back(px,py);\n    }\n    for(auto &p: answer){\n        cout<<p.first<<\" \"<<p.second<<\"\\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    const int N = 50, M = 100;\n    int n, m;\n    cin >> n >> m;\n    static int c[N][N];\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < n; j++){\n            cin >> c[i][j];\n        }\n    }\n\n    // Precompute INPUT adjacencies\n    static bool initial_adj[M+1][M+1];\n    static bool initial_adjOutside[M+1];\n    memset(initial_adj, 0, sizeof(initial_adj));\n    memset(initial_adjOutside, 0, sizeof(initial_adjOutside));\n\n    int dx[4]={-1,1,0,0}, dy[4]={0,0,-1,1};\n    for(int i=0;i<n;i++){\n        for(int j=0;j<n;j++){\n            int x=c[i][j];\n            if(i==0||i==n-1||j==0||j==n-1)\n                initial_adjOutside[x]=true;\n            for(int k=0;k<4;k++){\n                int ni=i+dx[k], nj=j+dy[k];\n                if(ni<0||ni>=n||nj<0||nj>=n){\n                    initial_adj[x][0]=true;\n                } else {\n                    int y=c[ni][nj];\n                    if(y!=x) initial_adj[x][y]=true;\n                }\n            }\n        }\n    }\n\n    // Time\u2010boxing\n    auto t0 = chrono::steady_clock::now();\n    const double TL = 1.9;\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    // Best answer so far\n    static int bestD[N][N];\n    int bestZeros = 0;\n    // Initialize bestD to input (zero\u2010count=0)\n    for(int i=0;i<n;i++) for(int j=0;j<n;j++) bestD[i][j]=c[i][j];\n\n    // Buffers for each trial\n    static int d[N][N];\n    static int color_count[M+1];\n    static int adjCnt[M+1][M+1];\n    static int deg[N][N];\n    static bool seen[N][N];\n    static pair<int,int> qbuf[N*N];\n\n    auto ward_conn_if_rem = [&](int ri,int rj)->bool{\n        int x=d[ri][rj], need=color_count[x]-1;\n        if(need<=0) return false;\n        int sx=-1, sy=-1;\n        for(int k=0;k<4;k++){\n            int ni=ri+dx[k], nj=rj+dy[k];\n            if(ni>=0&&ni<n&&nj>=0&&nj<n && d[ni][nj]==x){\n                sx=ni; sy=nj; break;\n            }\n        }\n        if(sx<0) return false;\n        // BFS\n        memset(seen,0,sizeof(seen));\n        int qh=0, qt=0;\n        seen[sx][sy]=true;\n        qbuf[qt++]={sx,sy};\n        int cnt=1;\n        while(qh<qt && cnt<need){\n            auto [i,j]=qbuf[qh++];\n            for(int k=0;k<4;k++){\n                int ni=i+dx[k], nj=j+dy[k];\n                if(ni==ri&&nj==rj) continue;\n                if(ni<0||ni>=n||nj<0||nj>=n) continue;\n                if(!seen[ni][nj] && d[ni][nj]==x){\n                    seen[ni][nj]=true;\n                    qbuf[qt++]={ni,nj};\n                    cnt++;\n                }\n            }\n        }\n        return cnt==need;\n    };\n\n    auto can_remove = [&](int i,int j)->bool{\n        int x=d[i][j];\n        if(x==0) return false;\n        // gather neighbor info\n        int zeroAdj=0, boundAdj=0;\n        array<int,4> neigh; int nc=0;\n        static int neighCnt[M+1];\n        memset(neighCnt,0,sizeof(neighCnt));\n\n        for(int k=0;k<4;k++){\n            int ni=i+dx[k], nj=j+dy[k];\n            if(ni<0||ni>=n||nj<0||nj>=n){\n                zeroAdj++; boundAdj++;\n            } else {\n                int y=d[ni][nj];\n                if(y==0){\n                    zeroAdj++;\n                } else if(y!=x){\n                    if(neighCnt[y]==0) neigh[nc++]=y;\n                    neighCnt[y]++;\n                }\n            }\n        }\n        if(zeroAdj==0) return false;\n\n        // 1) preserve x\u2013y adjacencies\n        for(int t=0;t<nc;t++){\n            int y=neigh[t];\n            if(initial_adj[x][y] && adjCnt[x][y] <= neighCnt[y])\n                return false;\n        }\n        if(initial_adjOutside[x] && adjCnt[x][0] <= zeroAdj)\n            return false;\n\n        // 2) never introduce 0\u2013y for y that never touched outside\n        if(!initial_adjOutside[x]) return false;\n        for(int t=0;t<nc;t++){\n            int y=neigh[t];\n            if(!initial_adjOutside[y]) return false;\n        }\n\n        // 3) connectivity\n        if(deg[i][j]>1){\n            if(!ward_conn_if_rem(i,j)) return false;\n        }\n        return true;\n    };\n\n    // multi\u2010start + hill\u2010climb\n    for(int attempt=0;;attempt++){\n        double elapsed = chrono::duration<double>(chrono::steady_clock::now() - t0).count();\n        if(elapsed > TL) break;\n\n        // choose seed: even attempts from original, odd from best so far\n        int (*src)[N] = (attempt%2==1 ? bestD : c);\n        // init d, color_count, adjCnt, deg\n        memset(color_count,0,sizeof(color_count));\n        memset(adjCnt,0,sizeof(adjCnt));\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++){\n                int v = src[i][j];\n                d[i][j]=v;\n                color_count[v]++;\n            }\n        }\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++){\n                int x=d[i][j];\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni<0||ni>=n||nj<0||nj>=n){\n                        adjCnt[x][0]++;\n                    } else {\n                        adjCnt[x][ d[ni][nj] ]++;\n                    }\n                }\n            }\n        }\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++){\n                int x=d[i][j], cdeg=0;\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni>=0&&ni<n&&nj>=0&&nj<n && d[ni][nj]==x)\n                        cdeg++;\n                }\n                deg[i][j]=cdeg;\n            }\n        }\n\n        // initial candidate stack\n        vector<pair<int,int>> stk;\n        stk.reserve(n*n);\n        for(int i=0;i<n;i++){\n            for(int j=0;j<n;j++){\n                if(can_remove(i,j)) stk.emplace_back(i,j);\n            }\n        }\n        shuffle(stk.begin(), stk.end(), rng);\n\n        // peel\n        while(!stk.empty()){\n            auto [i,j] = stk.back(); stk.pop_back();\n            int x=d[i][j];\n            if(x==0 || !can_remove(i,j)) continue;\n            // remove\n            d[i][j]=0; color_count[x]--;\n            for(int k=0;k<4;k++){\n                int ni=i+dx[k], nj=j+dy[k];\n                if(ni<0||ni>=n||nj<0||nj>=n){\n                    adjCnt[x][0]--;\n                } else {\n                    int y=d[ni][nj];\n                    adjCnt[x][y]--;\n                    adjCnt[y][x]--;\n                    if(y==x)\n                        deg[ni][nj]--;\n                    if(y!=0)\n                        adjCnt[y][0]++;\n                }\n            }\n            for(int k=0;k<4;k++){\n                int ni=i+dx[k], nj=j+dy[k];\n                if(ni>=0&&ni<n&&nj>=0&&nj<n && d[ni][nj]!=0){\n                    if(can_remove(ni,nj))\n                        stk.emplace_back(ni,nj);\n                }\n            }\n        }\n\n        // evaluate\n        int zeros=0;\n        for(int i=0;i<n;i++)for(int j=0;j<n;j++) if(d[i][j]==0) zeros++;\n        if(zeros > bestZeros){\n            bestZeros = zeros;\n            for(int i=0;i<n;i++) for(int j=0;j<n;j++) bestD[i][j]=d[i][j];\n        }\n    }\n\n    // output best\n    for(int i=0;i<n;i++){\n        for(int j=0;j<n;j++){\n            cout<<bestD[i][j]<<(j+1<n?' ':'\\n');\n        }\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\n//\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\n// Interactive primitives\nint N, D, Q, usedQ;\nvector<int> comp_cache;  // for mergesort only\n\n// Always\u2010issue one balance\u2010query comparing singleton {i} vs singleton {j}.\nint raw_query(int i, int j){\n    cout << 1 << ' ' << 1 << ' ' << i << ' ' << j << \"\\n\" << flush;\n    char c; \n    cin >> c;\n    usedQ++;\n    if(c=='>') return +1;\n    if(c=='<') return -1;\n    return 0;\n}\n\n// Cached comparator for mergesort: compares {i} vs {j} once, thereafter reuses result.\nint compare_cached(int i, int j){\n    if(i==j) return 0;\n    int &c = comp_cache[i*N + j];\n    if(c != -2) return c;\n    int r = raw_query(i, j);\n    c = r;\n    comp_cache[j*N + i] = -r;\n    return r;\n}\n\n// Simple recursive mergesort using compare_cached.\nvector<int> interactive_mergesort(const vector<int>& A){\n    int n = (int)A.size();\n    if(n <= 1) return A;\n    int m = n/2;\n    vector<int> L(A.begin(), A.begin()+m), R(A.begin()+m, A.end());\n    L = interactive_mergesort(L);\n    R = interactive_mergesort(R);\n    vector<int> M; M.reserve(n);\n    int i=0, j=0;\n    while(i < (int)L.size() && j < (int)R.size()){\n        int v = compare_cached(L[i], R[j]);\n        if(v>0 || (v==0 && L[i]<R[j])) M.push_back(L[i++]);\n        else                           M.push_back(R[j++]);\n    }\n    while(i < (int)L.size())  M.push_back(L[i++]);\n    while(j < (int)R.size())  M.push_back(R[j++]);\n    return M;\n}\n//\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> D >> Q;\n    comp_cache.assign(N*N, -2);\n    usedQ = 0;\n\n    // 1) How many compares to full\u2010sort via mergesort?  N\u00b7ceil(log2 N)\n    int LG = 0;\n    while((1<<LG) < N) LG++;\n    long long needSortQ = 1LL * N * LG;\n\n    // RNG + tiny jitter to break ties\n    mt19937_64 rng(71268726 ^ (N<<16) ^ (D<<8) ^ Q);\n    vector<double> jitter(N);\n    for(int i=0;i<N;i++) jitter[i] = (rng()%10000)*1e-4;\n\n    vector<int> final_assign(N,-1);\n\n    // If we have budget to fully sort, do it.\n    if(Q >= needSortQ){\n        // \u2014\u2014\u2014 A) FULL SORT BRANCH \u2014\u2014\u2014\n        vector<int> ids(N);\n        iota(ids.begin(), ids.end(), 0);\n        auto sorted = interactive_mergesort(ids);\n        // record rank_of[id]\n        vector<int> rank_of(N);\n        for(int r=0;r<N;r++) rank_of[ sorted[r] ] = r;\n\n        // build a simple approximate weight = (N-1-rank) + jitter\n        vector<double> weight(N);\n        for(int i=0;i<N;i++){\n            weight[i] = double(N-1 - rank_of[i]) + jitter[i];\n        }\n\n        // 2) how many queries remain?\n        int Q_rem = Q - usedQ;\n        // 3) dynamic\u2010assign up to M items:\n        //    we need (D-1) compares per item after the first D\n        int M = min(N, D + Q_rem / max(1, D-1));\n\n        // prepare bins\n        vector<vector<int>> bins(D);\n        vector<double> bin_load(D, 0.0);\n\n        // assign the top M items\n        for(int idx=0; idx<M; idx++){\n            int id = sorted[idx];\n            int b;\n            if(idx < D){\n                // seed each bin once\n                b = idx;\n            } else {\n                // find the lightest bin by D-1 compares\n                b = 0;\n                for(int j=1; j<D; j++){\n                    // compare sum(bins[b]) vs sum(bins[j])\n                    auto &L = bins[b], &R = bins[j];\n                    // both non-empty since idx>=D\n                    cout << (int)L.size() << ' ' << (int)R.size();\n                    for(int x:L) cout << ' ' << x;\n                    for(int x:R) cout << ' ' << x;\n                    cout << \"\\n\" << flush;\n                    char c; cin >> c;\n                    usedQ++;\n                    // if LHS > RHS, bin[b] is heavier \u2192 switch to j\n                    if(c == '>') b = j;\n                    // if '=' or '<', keep b\n                }\n            }\n            // fix assignment\n            final_assign[id] = b;\n            bins[b].push_back(id);\n            bin_load[b] += weight[id];\n        }\n\n        // 4) burn any leftover queries (fewer than D-1 remain)\n        while(usedQ < Q){\n            // compare two non-empty bins, say bin 0 vs bin 1\n            auto &L = bins[0], &R = bins[1];\n            cout << (int)L.size() << ' ' << (int)R.size();\n            for(int x:L) cout << ' ' << x;\n            for(int x:R) cout << ' ' << x;\n            cout << \"\\n\" << flush;\n            char c; cin >> c;\n            usedQ++;\n        }\n\n        // 5) tail\u2010assign the remaining items [M..N)\n        for(int idx=M; idx<N; idx++){\n            int id = sorted[idx];\n            // pick bin with minimal bin_load\n            int best=0;\n            for(int b=1;b<D;b++){\n                if(bin_load[b] < bin_load[best]) best = b;\n            }\n            final_assign[id] = best;\n            bin_load[best] += weight[id];\n        }\n    }\n    else {\n        // \u2014\u2014\u2014 B) FALLBACK BRANCH \u2014\u2014\u2014\n        // no full\u2010sort: fall back to win\u2010rate sampling + LPT\n        vector<int> wins(N,0), comps(N,0);\n        int base = Q / N, rem = Q % N;\n        for(int i=0;i<N;i++){\n            comps[i] = base + (i<rem);\n            for(int k=0;k<comps[i];k++){\n                // pick a random j!=i\n                int j = rng() % (N-1);\n                if(j >= i) ++j;\n                int r = raw_query(i,j);\n                if(r >= 0) wins[i]++;\n            }\n        }\n        // build pseudo\u2010weight = (wins/comps)*N + jitter\n        vector<double> weight(N);\n        for(int i=0;i<N;i++){\n            double ratio = comps[i]>0\n                         ? double(wins[i]) / double(comps[i])\n                         : 0.0;\n            weight[i] = ratio * N + jitter[i];\n        }\n        // LPT on weight[]\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        shuffle(order.begin(), order.end(), rng);\n        stable_sort(order.begin(), order.end(),\n                    [&](int a,int b){ return weight[a] > weight[b]; });\n        vector<double> bin_load(D,0.0);\n        for(int id: order){\n            int best=0;\n            for(int b=1;b<D;b++){\n                if(bin_load[b] < bin_load[best]) best = b;\n            }\n            final_assign[id] = best;\n            bin_load[best] += weight[id];\n        }\n    }\n\n    // \u2014\u2014\u2014 Finally: output the division \u2014\u2014\u2014\n    for(int i=0;i<N;i++){\n        cout << final_assign[i] << (i+1==N?'\\n':' ');\n    }\n    cout << flush;\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int,int>;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int INF = 1000000;\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> st(m);\n    for(int i = 0; i < m; i++){\n        st[i].resize(n/m);\n        for(int j = 0; j < n/m; j++){\n            cin >> st[i][j];\n        }\n    }\n\n    // min_content[i] = minimum label currently in stack i (or INF if empty)\n    vector<int> min_content(m, INF);\n    for(int i = 0; i < m; i++){\n        if(!st[i].empty()){\n            int mn = INF;\n            for(int x: st[i]) mn = min(mn, x);\n            min_content[i] = mn;\n        }\n    }\n\n    vector<pii> ops;\n    ops.reserve(2*n);\n\n    // For each v=1..n we need to expose and remove it.\n    for(int v = 1; v <= n; v++){\n        // 1) find v in some stack s at depth j\n        int s = -1, j = -1;\n        for(int i = 0; i < m && s==-1; i++){\n            for(int k = 0; k < (int)st[i].size(); k++){\n                if(st[i][k] == v){\n                    s = i; j = k;\n                    break;\n                }\n            }\n        }\n        int sz = st[s].size();\n        int above = sz - (j+1);\n        // 2) if there are boxes above it, move that entire segment\n        if(above > 0){\n            // collect the segment and its minimum\n            vector<int> segment;\n            segment.reserve(above);\n            int segment_min = INF;\n            for(int p = j+1; p < sz; p++){\n                segment.push_back(st[s][p]);\n                segment_min = min(segment_min, st[s][p]);\n            }\n            // choose destination stack t != s\n            int best_t = -1;\n            // 2a) first try to find \"safe\" stacks whose min_content > segment_min\n            //     among those pick the one of minimal height\n            int best_h = INT_MAX;\n            for(int t = 0; t < m; t++){\n                if(t == s) continue;\n                if(min_content[t] > segment_min){\n                    int h = st[t].size();\n                    if(h < best_h){\n                        best_h = h;\n                        best_t = t;\n                    }\n                }\n            }\n            // 2b) if no safe stack found, pick t with maximal min_content[t],\n            //     tie\u2010break on minimal height\n            if(best_t == -1){\n                int best_min = -1;\n                best_h = INT_MAX;\n                for(int t = 0; t < m; t++){\n                    if(t == s) continue;\n                    int mc = min_content[t];\n                    if(mc > best_min || (mc == best_min && (int)st[t].size() < best_h)){\n                        best_min = mc;\n                        best_h = st[t].size();\n                        best_t = t;\n                    }\n                }\n            }\n            // perform the move: we must specify the box immediately above v\n            int w = st[s][j+1];\n            ops.emplace_back(w, best_t+1);\n            // physically move it in our simulation\n            st[s].resize(j+1);\n            min_content[s] = INF;\n            for(int x: st[s]) min_content[s] = min(min_content[s], x);\n            for(int x: segment){\n                st[best_t].push_back(x);\n                min_content[best_t] = min(min_content[best_t], x);\n            }\n        }\n        // 3) now v is at the top of stack s, carry it out\n        ops.emplace_back(v, 0);\n        st[s].pop_back();\n        // update min_content[s]\n        min_content[s] = INF;\n        for(int x: st[s]) min_content[s] = min(min_content[s], x);\n    }\n\n    // output all operations\n    for(auto &op: ops){\n        cout << op.first << \" \" << op.second << \"\\n\";\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// xorshift64 for randomness\nstatic uint64_t _xr = chrono::high_resolution_clock::now().time_since_epoch().count();\ninline uint64_t xor64(){\n    _xr ^= _xr << 13;\n    _xr ^= _xr >> 7;\n    _xr ^= _xr << 17;\n    return _xr;\n}\n\n// DSU for MST\nstruct DSU {\n    vector<int> p;\n    DSU(int n):p(n,-1){}\n    int find(int x){ return p[x]<0?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(p[a]>p[b]) swap(a,b);\n        p[a]+=p[b];\n        p[b]=a;\n        return true;\n    }\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<string> h(N-1), v(N);\n    for(int i=0;i<N-1;i++) cin >> h[i];\n    for(int i=0;i<N;i++)   cin >> v[i];\n\n    int V = N*N;\n    auto id = [&](int i,int j){ return i*N+j; };\n\n    vector<int> dirt(V);\n    for(int i=0;i<N;i++) for(int j=0;j<N;j++) cin >> dirt[id(i,j)];\n\n    // Build adjacency + move\u2010labels\n    vector<vector<pair<int,char>>> nbr(V);\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            int u=id(i,j);\n            if(i+1<N && h[i][j]=='0'){\n                int w=id(i+1,j);\n                nbr[u].emplace_back(w,'D');\n                nbr[w].emplace_back(u,'U');\n            }\n            if(j+1<N && v[i][j]=='0'){\n                int w=id(i,j+1);\n                nbr[u].emplace_back(w,'R');\n                nbr[w].emplace_back(u,'L');\n            }\n        }\n    }\n\n    // 1) All-pairs BFS \u2192 dist[src*V + x], fm[...] = first\u2010move char\n    vector<int16_t> dist(V*V, -1);\n    vector<char>   fm  (V*V,  0);\n    deque<int> Q;\n    for(int src=0; src<V; src++){\n        int base = src*V;\n        // reset\n        for(int x=0;x<V;x++) dist[base+x] = -1;\n        dist[base+src] = 0;\n        Q.clear();\n        // seed with immediate neighbors\n        for(auto &pc: nbr[src]){\n            int t=pc.first;\n            dist[base+t]=1;\n            fm  [base+t]=pc.second;\n            Q.push_back(t);\n        }\n        // BFS\n        while(!Q.empty()){\n            int u=Q.front(); Q.pop_front();\n            int du=dist[base+u];\n            for(auto &pc: nbr[u]){\n                int t=pc.first;\n                if(dist[base+t]==-1){\n                    dist[base+t] = du+1;\n                    fm  [base+t] = fm[base+u];\n                    Q.push_back(t);\n                }\n            }\n        }\n    }\n    auto dptr = dist.data();\n\n    // 2) Precompute each node's K nearest neighbors by BFS-dist\n    const int K = 12;\n    vector<array<int,K>> knn(V);\n    for(int u=0;u<V;u++){\n        priority_queue<pair<int,int>> pq; \n        int base=u*V;\n        for(int w=0;w<V;w++){\n            if(w==u) continue;\n            int d0 = dptr[base+w];\n            if((int)pq.size()<K){\n                pq.emplace(d0,w);\n            } else if(d0 < pq.top().first){\n                pq.pop();\n                pq.emplace(d0,w);\n            }\n        }\n        for(int i=K-1;i>=0;i--){\n            knn[u][i] = pq.top().second;\n            pq.pop();\n        }\n    }\n\n    // 3) Build NN Tours (pure + jittered), + snake, + MST-preorder\n    auto buildNN = [&](bool jitter){\n        const int TOPK = 5;\n        vector<char> used(V,0);\n        vector<int> ord; ord.reserve(V);\n        int cur=0;\n        used[cur]=1; ord.push_back(cur);\n        vector<pair<double,int>> top; top.reserve(TOPK);\n\n        for(int step=1;step<V;step++){\n            int base=cur*V, pick=-1;\n            if(!jitter){\n                double bs=-1;\n                for(int w=0;w<V;w++) if(!used[w]){\n                    double sc = (double)dirt[w]/dist[base+w];\n                    if(sc>bs){ bs=sc; pick=w; }\n                }\n            } else {\n                top.clear();\n                for(int w=0;w<V;w++) if(!used[w]){\n                    double sc = (double)dirt[w]/dist[base+w];\n                    if((int)top.size()<TOPK){\n                        top.emplace_back(sc,w);\n                        if((int)top.size()==TOPK)\n                            sort(top.begin(), top.end());\n                    } else if(sc>top[0].first){\n                        top[0]={sc,w};\n                        // bubble\n                        for(int z=0;z+1<TOPK;z++){\n                            if(top[z].first>top[z+1].first) swap(top[z],top[z+1]);\n                            else break;\n                        }\n                    }\n                }\n                pick = top[xor64()%top.size()].second;\n            }\n            used[pick]=1;\n            ord.push_back(pick);\n            cur=pick;\n        }\n        return ord;\n    };\n\n    vector<vector<int>> cands;\n    cands.push_back(buildNN(false));\n    const int JITER=4;\n    for(int i=0;i<JITER;i++) cands.push_back(buildNN(true));\n    // snake ordering\n    {\n        vector<int> s; s.reserve(V);\n        for(int i=0;i<N;i++){\n            if(i%2==0) for(int j=0;j<N;j++) s.push_back(id(i,j));\n            else       for(int j=N-1;j>=0;j--) s.push_back(id(i,j));\n        }\n        cands.push_back(move(s));\n    }\n    // MST-preorder\n    {\n        // build sparse graph edges from knn\n        struct Edge{int u,v,w;};\n        vector<Edge> E;\n        E.reserve(V*K);\n        for(int u=0;u<V;u++){\n            for(int w: knn[u]){\n                if(u<w){\n                    E.push_back({u,w,dist[u*V+w]});\n                }\n            }\n        }\n        sort(E.begin(), E.end(), [&](auto &a,auto &b){return a.w<b.w;});\n        DSU dsu(V);\n        vector<vector<int>> tadj(V);\n        int ec=0;\n        for(auto &e:E){\n            if(dsu.unite(e.u,e.v)){\n                tadj[e.u].push_back(e.v);\n                tadj[e.v].push_back(e.u);\n                if(++ec==V-1) break;\n            }\n        }\n        // preorder DFS\n        vector<int> ord; ord.reserve(V);\n        vector<char> vis(V,0);\n        function<void(int)> dfs = [&](int u){\n            vis[u]=1; ord.push_back(u);\n            for(int w:tadj[u]) if(!vis[w]) dfs(w);\n        };\n        dfs(0);\n        cands.push_back(move(ord));\n    }\n\n    // 4) Guided 2-opt on each candidate\n    auto twoOpt = [&](vector<int> &ord){\n        int n=V;\n        vector<int> pos(n);\n        for(int i=0;i<n;i++) pos[ord[i]]=i;\n        for(int pass=0;pass<4;pass++){\n            bool improved=false;\n            for(int i=0;i<n-1 && !improved;i++){\n                int A=ord[i], B=ord[i+1];\n                for(int kk=0;kk<K;kk++){\n                    int C=knn[A][kk];\n                    int j=pos[C];\n                    if(j<=i+1) continue;\n                    int D=ord[(j+1)%n];\n                    ll oldc = (ll)dptr[A*V+B] + dptr[C*V+D];\n                    ll newc = (ll)dptr[A*V+C] + dptr[B*V+D];\n                    if(newc<oldc){\n                        reverse(ord.begin()+i+1, ord.begin()+j+1);\n                        for(int x=i+1;x<=j;x++) pos[ord[x]]=x;\n                        improved=true;\n                        break;\n                    }\n                }\n            }\n            if(!improved) break;\n        }\n    };\n    for(auto &o:cands) twoOpt(o);\n\n    // 5) Compute each tour\u2019s metric\u2010length\n    auto tourLen = [&](const vector<int> &ord){\n        ll s=0;\n        for(int i=0;i+1<V;i++) s+=dptr[ ord[i]*V + ord[i+1] ];\n        s+=dptr[ ord[V-1]*V + 0 ];\n        return s;\n    };\n\n    // 6) Compare to DFS-Euler baseline\n    ll bestL = 2LL*(V-1);\n    int bestIdx = -1; // -1 -> DFS-Euler\n    for(int i=0;i<(int)cands.size();i++){\n        ll L = tourLen(cands[i]);\n        if(L<bestL){\n            bestL=L;\n            bestIdx=i;\n        }\n    }\n\n    // 7) Materialize the best cycle\n    string ans;\n    ans.reserve(bestL+10);\n\n    if(bestIdx<0){\n        // fallback: plain DFS-Euler on the grid\n        vector<vector<bool>> vis2(N, vector<bool>(N,false));\n        static int di[4]={0,1,0,-1}, dj[4]={1,0,-1,0};\n        static char dc[4]={'R','D','L','U'};\n        function<void(int,int)> dfs2 = [&](int i,int j){\n            vis2[i][j]=true;\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(vis2[ni][nj]) continue;\n                if(d==0 && v[i][j]!='0') continue;\n                if(d==1 && h[i][j]!='0') continue;\n                if(d==2 && v[i][nj]!='0') continue;\n                if(d==3 && h[ni][j]!='0') continue;\n                ans.push_back(dc[d]);\n                dfs2(ni,nj);\n                ans.push_back(dc[d^2]);\n            }\n        };\n        dfs2(0,0);\n    } else {\n        // stitch BFS-paths along best TSP order\n        auto &ord = cands[bestIdx];\n        int cur=0;\n        auto go = [&](int dst){\n            while(cur!=dst){\n                char mv = fm[cur*V+dst];\n                ans.push_back(mv);\n                int ii=cur/N, jj=cur%N;\n                if(mv=='U') ii--;\n                else if(mv=='D') ii++;\n                else if(mv=='L') jj--;\n                else          jj++;\n                cur = id(ii,jj);\n            }\n        };\n        for(int x:ord) go(x);\n        go(0);\n    }\n\n    // safety truncate\n    if(ans.size()>100000) ans.resize(100000);\n    cout << ans << \"\\n\";\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int,int>;\nstatic const int INF = 1e9;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    cin >> N >> M;\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<string> A(N);\n    for(int i = 0; i < N; i++){\n        cin >> A[i];\n    }\n    vector<string> t(M);\n    for(int k = 0; k < M; k++){\n        cin >> t[k];\n    }\n\n    // Precompute positions of each letter\n    vector<vector<pii>> pos(26);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            pos[A[i][j] - 'A'].emplace_back(i, j);\n        }\n    }\n\n    vector<bool> used(M, false);\n    vector<pii> moves;\n    moves.reserve(5000);\n\n    int cur_i = si, cur_j = sj;\n    string lastS;    // keep up to the last 4 typed chars\n\n    // Temporary arrays for the small DP on rem letters\n    static int dp1[225], dp2[225];\n    // For reconstruction when we actually commit to the best word\n    static int parentArr[5][225];\n    int occSz[5];\n\n    // Greedy loop: pick one word at a time\n    for(int done = 0; done < M; done++){\n        int bestK = -1;\n        int bestCost = INF;\n        int bestOv = -1;\n\n        // Scan all unused words\n        for(int k = 0; k < M; k++){\n            if(used[k]) continue;\n            const string &w = t[k];\n            // Compute overlap with lastS (up to 4)\n            int maxOv = min((int)lastS.size(), 4);\n            int ov = 0;\n            for(int o = maxOv; o >= 1; o--){\n                bool ok = true;\n                for(int x = 0; x < o; x++){\n                    if(lastS[lastS.size()-o + x] != w[x]){\n                        ok = false;\n                        break;\n                    }\n                }\n                if(ok){\n                    ov = o;\n                    break;\n                }\n            }\n            int rem = 5 - ov;\n            int travel = 0;\n            if(rem > 0){\n                // DP over the rem letters w[ov..4], only Manhattan distances\n                // Stage 0: distance from (cur_i,cur_j) to each pos of w[ov]\n                int c0 = w[ov] - 'A';\n                int sz0 = pos[c0].size();\n                for(int j = 0; j < sz0; j++){\n                    dp1[j] = abs(cur_i - pos[c0][j].first)\n                           + abs(cur_j - pos[c0][j].second);\n                }\n                int prevSz = sz0;\n                // Stages 1..rem-1\n                for(int s2 = 1; s2 < rem; s2++){\n                    int cprev = w[ov + s2 - 1] - 'A';\n                    int ccur  = w[ov + s2]     - 'A';\n                    int szc   = pos[ccur].size();\n                    // init\n                    for(int j = 0; j < szc; j++) dp2[j] = INF;\n                    // relax\n                    for(int u = 0; u < prevSz; u++){\n                        auto &p0 = pos[cprev][u];\n                        int base = dp1[u];\n                        for(int v = 0; v < szc; v++){\n                            auto &p1 = pos[ccur][v];\n                            int cand = base\n                                     + abs(p0.first  - p1.first)\n                                     + abs(p0.second - p1.second);\n                            if(cand < dp2[v]) dp2[v] = cand;\n                        }\n                    }\n                    // swap in\n                    for(int j = 0; j < szc; j++) dp1[j] = dp2[j];\n                    prevSz = szc;\n                }\n                // take minimum\n                travel = INF;\n                for(int j = 0; j < prevSz; j++){\n                    travel = min(travel, dp1[j]);\n                }\n            }\n            int cost = travel + rem;  // +1 per keystroke for each of rem letters\n            // Tie-break on *larger* overlap\n            if(cost < bestCost || (cost == bestCost && ov > bestOv)){\n                bestCost = cost;\n                bestK = k;\n                bestOv = ov;\n            }\n        }\n\n        // Commit to bestK\n        used[bestK] = true;\n        const string &w = t[bestK];\n        // Recompute overlap\n        int maxOv = min((int)lastS.size(), 4);\n        int ov = 0;\n        for(int o = maxOv; o >= 1; o--){\n            bool ok = true;\n            for(int x = 0; x < o; x++){\n                if(lastS[lastS.size()-o + x] != w[x]){\n                    ok = false; break;\n                }\n            }\n            if(ok){ ov = o; break; }\n        }\n        int rem = 5 - ov;\n        if(rem > 0){\n            // We now do the DP *with* back\u2010pointers to recover the exact path\n            // Stage sizes\n            for(int s2 = 0; s2 < rem; s2++){\n                occSz[s2] = pos[w[ov + s2] - 'A'].size();\n            }\n            // Stage 0\n            {\n                int c0 = w[ov] - 'A';\n                for(int j = 0; j < occSz[0]; j++){\n                    auto &p0 = pos[c0][j];\n                    dp1[j] = abs(cur_i - p0.first)\n                           + abs(cur_j - p0.second);\n                    parentArr[0][j] = -1;\n                }\n            }\n            int prevSz = occSz[0];\n            // Stages 1..rem-1\n            for(int s2 = 1; s2 < rem; s2++){\n                int cprev = w[ov + s2 - 1] - 'A';\n                int ccur  = w[ov + s2]     - 'A';\n                int szc   = occSz[s2];\n                // init\n                for(int v = 0; v < szc; v++){\n                    dp2[v] = INF;\n                    parentArr[s2][v] = -1;\n                }\n                // relax\n                for(int u = 0; u < prevSz; u++){\n                    auto &pp = pos[cprev][u];\n                    int base = dp1[u];\n                    for(int v = 0; v < szc; v++){\n                        auto &pc = pos[ccur][v];\n                        int cand = base\n                                 + abs(pp.first  - pc.first)\n                                 + abs(pp.second - pc.second);\n                        if(cand < dp2[v]){\n                            dp2[v] = cand;\n                            parentArr[s2][v] = u;\n                        }\n                    }\n                }\n                // swap in\n                for(int v = 0; v < szc; v++){\n                    dp1[v] = dp2[v];\n                }\n                prevSz = szc;\n            }\n            // pick best end\n            int bestEnd = 0;\n            for(int j = 1; j < prevSz; j++){\n                if(dp1[j] < dp1[bestEnd]) bestEnd = j;\n            }\n            // backtrack indices\n            vector<int> idx(rem);\n            {\n                int cur = bestEnd;\n                for(int s2 = rem - 1; s2 >= 0; s2--){\n                    idx[s2] = cur;\n                    cur = parentArr[s2][cur];\n                }\n            }\n            // emit moves\n            for(int s2 = 0; s2 < rem; s2++){\n                int c = w[ov + s2] - 'A';\n                auto &p = pos[c][ idx[s2] ];\n                moves.emplace_back(p);\n                cur_i = p.first;\n                cur_j = p.second;\n                // update tail\u2010buffer\n                lastS.push_back(w[ov + s2]);\n                if((int)lastS.size() > 4){\n                    lastS.erase(lastS.begin(),\n                                lastS.end() - 4);\n                }\n            }\n        }\n    }\n\n    // Output all moves (\u2264 200*5 = 1000)\n    for(auto &mv : moves){\n        cout << mv.first << \" \" << mv.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    cin >> N >> M >> eps;\n\n    // 1) Read shapes\n    vector<vector<pair<int,int>>> shape(M);\n    vector<int> shape_mx_i(M), shape_mx_j(M);\n    for(int k = 0; k < M; k++){\n        int d; \n        cin >> d;\n        int mi = 0, mj = 0;\n        shape[k].resize(d);\n        for(int t = 0; t < d; t++){\n            int ii, jj;\n            cin >> ii >> jj;\n            shape[k][t] = {ii,jj};\n            mi = max(mi, ii);\n            mj = max(mj, jj);\n        }\n        shape_mx_i[k] = mi;\n        shape_mx_j[k] = mj;\n    }\n\n    int NN = N * N;\n\n    // 2) Enumerate all placements for each shape,\n    //    build coverList: for each cell id, the list of (shape,pid).\n    vector<vector<pair<int,int>>> coverList(NN);\n    vector<vector<vector<int>>>    placement_cells(M);\n    vector<vector<char>>           alive(M);\n    vector<int>                    aliveCnt(M, 0);\n\n    for(int k = 0; k < M; k++){\n        for(int di = 0; di + shape_mx_i[k] < N; di++){\n            for(int dj = 0; dj + shape_mx_j[k] < N; dj++){\n                int pid = (int)placement_cells[k].size();\n                placement_cells[k].push_back({});\n                alive[k].push_back(1);\n                aliveCnt[k]++;\n                auto &cells = placement_cells[k].back();\n                for(auto &p : shape[k]){\n                    int id = (di + p.first)*N + (dj + p.second);\n                    cells.push_back(id);\n                    coverList[id].emplace_back(k, pid);\n                }\n            }\n        }\n    }\n\n    // 3) Global coverCount, and per\u2010shape count_k\n    vector<int> coverCount(NN, 0);\n    vector<vector<int>> count_k(M, vector<int>(NN, 0));\n    for(int id = 0; id < NN; id++){\n        coverCount[id] = (int)coverList[id].size();\n        for(auto &kp : coverList[id]){\n            count_k[kp.first][id]++;\n        }\n    }\n\n    // 4) Cell state: -1=unknown, 0=zero, >0=oil\n    vector<int>  vgrid(NN, -1);\n    vector<char> drilled(NN, 0);\n\n    // 5) Track shapes that have been \"locked in\" by single\u2010placement\n    vector<char> shapeFixed(M, 0);\n\n    // kill a single placement (shape k, pid), updating all counts\n    auto kill_placement = [&](int k, int pid, queue<int>* q_zero){\n        alive[k][pid] = 0;\n        aliveCnt[k]--;\n        for(int cid : placement_cells[k][pid]){\n            coverCount[cid]--;\n            count_k[k][cid]--;\n            if(q_zero){\n                // new zero\u2010inference?\n                if(vgrid[cid]==-1 && coverCount[cid]==0){\n                    vgrid[cid]   = 0;\n                    drilled[cid] = 1;\n                    q_zero->push(cid);\n                }\n            }\n        }\n    };\n\n    // 6) Eliminate all placements covering a known\u2010zero cell \"id\",\n    //    cascade any new zeros, then run shape\u2010inference\n    function<void(int)> eliminate_at_zero = [&](int id){\n        queue<int> q;\n        // eliminate directly covering\n        for(auto &kp : coverList[id]){\n            int k = kp.first, pid = kp.second;\n            if(alive[k][pid]){\n                kill_placement(k, pid, &q);\n            }\n        }\n        // BFS cascade\n        while(!q.empty()){\n            int z = q.front(); q.pop();\n            for(auto &kp : coverList[z]){\n                int k = kp.first, pid = kp.second;\n                if(alive[k][pid]){\n                    kill_placement(k, pid, &q);\n                }\n            }\n        }\n        // 7) Shape\u2010inference loop: \n        //    (a) single\u2010placement \u21d2 lock in all its cells as oil\n        //    (b) intersection \u21d2 any cell covered by *every* alive placement\n        bool changed = true;\n        while(changed){\n            changed = false;\n            for(int k = 0; k < M; k++){\n                // single\u2010placement\n                if(!shapeFixed[k] && aliveCnt[k] == 1){\n                    shapeFixed[k] = 1;\n                    int the_pid = -1;\n                    for(int pid = 0; pid < (int)alive[k].size(); pid++){\n                        if(alive[k][pid]){\n                            the_pid = pid;\n                            break;\n                        }\n                    }\n                    if(the_pid >= 0){\n                        for(int cid : placement_cells[k][the_pid]){\n                            if(vgrid[cid] == -1){\n                                vgrid[cid]   = 1;\n                                drilled[cid] = 1;\n                                changed = true;\n                            }\n                        }\n                    }\n                }\n                // intersection\n                if(aliveCnt[k] >= 1){\n                    for(int cid = 0; cid < NN; cid++){\n                        if(vgrid[cid] == -1 \n                           && count_k[k][cid] == aliveCnt[k]){\n                            vgrid[cid]   = 1;\n                            drilled[cid] = 1;\n                            changed = true;\n                        }\n                    }\n                }\n            }\n        }\n    };\n\n    // 8) Initial shape\u2010inference (no zeros yet, just positives)\n    {\n        bool changed = true;\n        while(changed){\n            changed = false;\n            for(int k = 0; k < M; k++){\n                // single\u2010placement\n                if(!shapeFixed[k] && aliveCnt[k] == 1){\n                    shapeFixed[k] = 1;\n                    int the_pid = -1;\n                    for(int pid = 0; pid < (int)alive[k].size(); pid++){\n                        if(alive[k][pid]){\n                            the_pid = pid;\n                            break;\n                        }\n                    }\n                    if(the_pid >= 0){\n                        for(int cid : placement_cells[k][the_pid]){\n                            if(vgrid[cid] == -1){\n                                vgrid[cid]   = 1;\n                                drilled[cid] = 1;\n                                changed = true;\n                            }\n                        }\n                    }\n                }\n                // intersection\n                if(aliveCnt[k] >= 1){\n                    for(int cid = 0; cid < NN; cid++){\n                        if(vgrid[cid] == -1\n                           && count_k[k][cid] == aliveCnt[k]){\n                            vgrid[cid]   = 1;\n                            drilled[cid] = 1;\n                            changed = true;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // 9) Drill helper\n    auto drillOne = [&](int id){\n        int i = id / N, j = id % N;\n        cout << \"q 1 \" << i << \" \" << j << \"\\n\" << flush;\n        int v; \n        if(!(cin >> v)) \n            exit(0);\n        vgrid[id] = v;\n        drilled[id] = 1;\n        if(v == 0){\n            eliminate_at_zero(id);\n        }\n    };\n\n    // 10) Phase 1: drill *even\u2010parity* cells by descending coverCount\n    vector<pair<int,int>> evens;\n    evens.reserve(NN/2+1);\n    for(int id = 0; id < NN; id++){\n        int i = id / N, j = id % N;\n        if( ((i+j)&1) == 0 ){\n            evens.emplace_back(-coverCount[id], id);\n        }\n    }\n    sort(evens.begin(), evens.end());\n    for(auto &pr : evens){\n        int id = pr.second;\n        if(vgrid[id] != -1) continue;        // already known\n        if(coverCount[id] == 0){\n            vgrid[id] = 0;\n            drilled[id] = 1;\n            eliminate_at_zero(id);\n        } else {\n            drillOne(id);\n        }\n    }\n\n    // 11) Phase 2: drill *odd\u2010parity* cells by descending coverCount,\n    //     but only those having \u22651 even\u2010parity oil\u2010neighbor\n    static int di[4] = {1,-1,0,0}, dj[4] = {0,0,1,-1};\n    vector<pair<int,int>> odds;\n    odds.reserve(NN/2+1);\n    for(int id = 0; id < NN; id++){\n        int i = id / N, j = id % N;\n        if( ((i+j)&1) == 1 ){\n            odds.emplace_back(-coverCount[id], id);\n        }\n    }\n    sort(odds.begin(), odds.end());\n    for(auto &pr : odds){\n        int id = pr.second;\n        if(vgrid[id] != -1) continue;\n        int i = id / N, j = id % N;\n        bool hasOilNb = false;\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(vgrid[ni*N + nj] > 0){\n                hasOilNb = true;\n                break;\n            }\n        }\n        if(!hasOilNb || coverCount[id] == 0){\n            vgrid[id] = 0;\n            drilled[id] = 1;\n            eliminate_at_zero(id);\n        } else {\n            drillOne(id);\n        }\n    }\n\n    // 12) Whatever remains unknown must be zero\n    for(int id = 0; id < NN; id++){\n        if(vgrid[id] == -1){\n            vgrid[id] = 0;\n        }\n    }\n\n    // 13) Output answer\n    vector<pair<int,int>> ans;\n    ans.reserve(NN);\n    for(int id = 0; id < NN; id++){\n        if(vgrid[id] > 0){\n            ans.emplace_back(id / N, id % N);\n        }\n    }\n    cout << \"a \" << ans.size();\n    for(auto &p : ans){\n        cout << \" \" << p.first << \" \" << p.second;\n    }\n    cout << \"\\n\" << flush;\n\n    // final verdict (ignored)\n    int verdict;\n    cin >> verdict;\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int W = 1000;\n    int D, N;\n    cin >> ws >> ws; // skip potential leading whitespace (safe no\u2010op)\n    // Actually the problem gives W=1000 first:\n    cin.clear();\n    cin.seekg(0);\n    int tmpW;\n    cin >> tmpW >> D >> N;\n    // tmpW should be 1000\n    vector<vector<int>> a(D, vector<int>(N));\n    for(int d = 0; d < D; d++)\n        for(int k = 0; k < N; k++)\n            cin >> a[d][k];\n\n    // For each day independently, we build w[k] \u2265 1 so as to minimize:\n    //   100*max(0, a[d][k] - 1000*w[k])  subject to sum w[k] \u2264 1000\n    // By classic \u201cmarginal\u2010benefit\u201d greedy: start w[k]=1 (used=N), then\n    // collect all positive marginals m[k][t]=min(1000, a-1000*t) for t=1..ceil(a/1000)-1,\n    // sort them descending, and take the top (W-N).\n    vector<pair<int,int>> M; \n    M.reserve(2000);\n\n    vector<int> w(N), X(N+1);\n    for(int d = 0; d < D; d++){\n        // 1) init\n        for(int k = 0; k < N; k++) w[k] = 1;\n        int used = N;\n        int rem = W - used;\n\n        // 2) build all positive marginals\n        M.clear();\n        for(int k = 0; k < N; k++){\n            int ad = a[d][k];\n            // for t=1.. until ad - 1000*t <= 0\n            // marginal of the t-th extra column (beyond the first)\n            // is min(1000, ad - 1000*t).\n            for(int t = 1; ; t++){\n                int leftover = ad - 1000 * t;\n                if(leftover <= 0) break;\n                M.emplace_back(min(1000, leftover), k);\n            }\n        }\n\n        // 3) pick the top rem marginals\n        if(!M.empty()){\n            nth_element(M.begin(), M.begin() + min(rem, (int)M.size()), M.end(),\n                        [](auto &A, auto &B){ return A.first > B.first; });\n            int take = min(rem, (int)M.size());\n            // count how many times each k appears in the top\u2010take\n            static vector<int> cnt;\n            cnt.assign(N, 0);\n            for(int i = 0; i < take; i++){\n                if(M[i].first <= 0) break;\n                cnt[M[i].second]++;\n            }\n            for(int k = 0; k < N; k++){\n                w[k] += cnt[k];\n            }\n        }\n\n        // 4) compute X\u2010coordinates\n        X[0] = 0;\n        for(int k = 0; k < N; k++){\n            X[k+1] = X[k] + w[k];\n        }\n        // 5) output this day's rectangles\n        //    rectangle k:  i0=0, j0=X[k], i1=1000, j1=X[k+1]\n        for(int k = 0; k < N; k++){\n            cout << 0 << ' ' << X[k] << ' ' << W << ' ' << X[k+1] << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nstatic const int MOD = 998244353;\n\n// xorshift RNG\nstatic uint64_t rndX = chrono::steady_clock::now().time_since_epoch().count();\ninline uint32_t fast_rand() {\n    rndX ^= rndX << 13;\n    rndX ^= rndX >> 7;\n    rndX ^= rndX << 17;\n    return uint32_t(rndX);\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N,M,K;\n    cin >> N >> M >> K;\n    assert(N==9 && M==20 && K==81);\n\n    // read initial board flat\n    static int B0[81];\n    for(int i=0;i<9;i++){\n        for(int j=0;j<9;j++){\n            ll x; cin >> x;\n            B0[i*9+j] = int(x % MOD);\n        }\n    }\n    // read stamps flat 3\u00d73\u21929\n    static int stamps[20][9];\n    for(int m=0;m<20;m++){\n        for(int i=0;i<3;i++){\n            for(int j=0;j<3;j++){\n                ll x; cin >> x;\n                stamps[m][i*3+j] = int(x % MOD);\n            }\n        }\n    }\n\n    // build all candidate placements\n    // candM[c], candP[c], candQ[c], off[c][0..8], mapCI[m][p][q]\u2192c\n    static int candM[980], candP[980], candQ[980], off[980][9];\n    static int mapCI[20][9][9];\n    memset(mapCI,-1,sizeof mapCI);\n    int C=0;\n    for(int m=0;m<20;m++){\n        for(int p=0;p+2<9;p++){\n            for(int q=0;q+2<9;q++){\n                candM[C]=m; candP[C]=p; candQ[C]=q;\n                int idx=0;\n                for(int di=0;di<3;di++) for(int dj=0;dj<3;dj++){\n                    off[C][idx++] = (p+di)*9 + (q+dj);\n                }\n                mapCI[m][p][q] = C;\n                C++;\n            }\n        }\n    }\n    const int CAND = C; // should be 980\n\n    auto compute_delta = [&](const int A[81], int ci)->ll{\n        // score delta if we ADD placement ci onto board A\n        int m = candM[ci];\n        ll d=0;\n        for(int k=0;k<9;k++){\n            int v = A[ off[ci][k] ] + stamps[m][k];\n            if(v < MOD)      d += stamps[m][k];\n            else             d += (ll)stamps[m][k] - MOD;\n        }\n        return d;\n    };\n    auto apply_add = [&](int A[81], int ci){\n        int m = candM[ci];\n        for(int k=0;k<9;k++){\n            int &c = A[ off[ci][k] ];\n            c += stamps[m][k];\n            if(c >= MOD) c -= MOD;\n        }\n    };\n\n    // time\u2010base\n    auto t0 = chrono::steady_clock::now();\n\n    // ----------------------------------------------------------------\n    // 1) HEAVY 3\u2010step/2\u2010step lookahead to seed a strong solution\n    // ----------------------------------------------------------------\n    static int Bheavy[81], T1[81], T2[81], T3[81];\n    memcpy(Bheavy, B0, sizeof B0);\n    vector<array<int,3>> heavyOps;\n    heavyOps.reserve(K);\n\n    while((int)heavyOps.size() < K){\n        int used = heavyOps.size();\n        int rem  = K - used;\n        struct Cand{ ll d; int ci; };\n        Cand best1{LLONG_MIN,-1}, best2{LLONG_MIN,-1};\n        // find top\u20102\n        for(int ci=0;ci<CAND;ci++){\n            ll d = compute_delta(Bheavy,ci);\n            if(d > best1.d){ best2 = best1; best1={d,ci}; }\n            else if(d > best2.d){ best2={d,ci}; }\n        }\n        if(best1.d <= 0) break;\n        if(rem==1){\n            apply_add(Bheavy,best1.ci);\n            heavyOps.push_back({candM[best1.ci],candP[best1.ci],candQ[best1.ci]});\n            break;\n        }\n        // branch0: best1 \u2192 best2_0 \u2192 best3_0\n        memcpy(T1,Bheavy,sizeof Bheavy);\n        apply_add(T1,best1.ci);\n        Cand best2_0{LLONG_MIN,-1};\n        for(int ci=0;ci<CAND;ci++){\n            ll d = compute_delta(T1,ci);\n            if(d>best2_0.d) best2_0={d,ci};\n        }\n        memcpy(T2,T1,sizeof T1);\n        apply_add(T2,best2_0.ci);\n        Cand best3_0{LLONG_MIN,-1};\n        for(int ci=0;ci<CAND;ci++){\n            ll d = compute_delta(T2,ci);\n            if(d>best3_0.d) best3_0={d,ci};\n        }\n        // branch1: best2 \u2192 best2_1\n        memcpy(T3,Bheavy,sizeof Bheavy);\n        apply_add(T3,best2.ci);\n        Cand best2_1{LLONG_MIN,-1};\n        for(int ci=0;ci<CAND;ci++){\n            ll d = compute_delta(T3,ci);\n            if(d>best2_1.d) best2_1={d,ci};\n        }\n        // sums\n        ll s1   = best1.d;\n        ll s2_0 = best1.d + best2_0.d;\n        ll s2_1 = best2.d  + best2_1.d;\n        ll s3_0 = best1.d + best2_0.d + best3_0.d;\n        // pick best chain within rem\n        ll bestSum = s1;\n        int bestR=1, bestBr=0;\n        if(rem>=2){\n            if(s2_0>bestSum){ bestSum=s2_0; bestR=2; bestBr=0; }\n            if(s2_1>bestSum){ bestSum=s2_1; bestR=2; bestBr=1; }\n        }\n        if(rem>=3 && s3_0>bestSum){\n            bestSum=s3_0; bestR=3; bestBr=0;\n        }\n        if(bestSum <= 0) break;\n        // commit\n        if(bestR==1){\n            apply_add(Bheavy,best1.ci);\n            heavyOps.push_back({candM[best1.ci],candP[best1.ci],candQ[best1.ci]});\n        } else if(bestR==2){\n            if(bestBr==0){\n                apply_add(Bheavy,best1.ci);\n                apply_add(Bheavy,best2_0.ci);\n                heavyOps.push_back({candM[best1.ci],candP[best1.ci],candQ[best1.ci]});\n                heavyOps.push_back({candM[best2_0.ci],candP[best2_0.ci],candQ[best2_0.ci]});\n            } else {\n                apply_add(Bheavy,best2.ci);\n                apply_add(Bheavy,best2_1.ci);\n                heavyOps.push_back({candM[best2.ci],candP[best2.ci],candQ[best2.ci]});\n                heavyOps.push_back({candM[best2_1.ci],candP[best2_1.ci],candQ[best2_1.ci]});\n            }\n        } else {\n            // bestR==3 on branch0\n            apply_add(Bheavy,best1.ci);\n            apply_add(Bheavy,best2_0.ci);\n            apply_add(Bheavy,best3_0.ci);\n            heavyOps.push_back({candM[best1.ci],candP[best1.ci],candQ[best1.ci]});\n            heavyOps.push_back({candM[best2_0.ci],candP[best2_0.ci],candQ[best2_0.ci]});\n            heavyOps.push_back({candM[best3_0.ci],candP[best3_0.ci],candQ[best3_0.ci]});\n        }\n    }\n\n    ll heavyScore=0;\n    for(int i=0;i<81;i++) heavyScore += Bheavy[i];\n    ll bestScore = heavyScore;\n    vector<array<int,3>> bestOps = heavyOps;\n\n    // ----------------------------------------------------------------\n    // 2) TIME\u2010BOXED MULTI\u2010START GREEDY (pick 1 of top\u20103 each step)\n    // ----------------------------------------------------------------\n    static int Br[81];\n    int iter = 0;\n    while(true){\n        if((++iter & 1)==0){\n            auto tnow = chrono::steady_clock::now();\n            if(chrono::duration_cast<chrono::milliseconds>(tnow - t0).count() > 1550)\n                break;\n        }\n        memcpy(Br, B0, sizeof B0);\n        vector<array<int,3>> ops;\n        ops.reserve(K);\n        for(int step=0; step<K; step++){\n            // find top\u20103 immediate gains\n            ll bd[3] = {LLONG_MIN,LLONG_MIN,LLONG_MIN};\n            int bi[3] = {-1,-1,-1};\n            for(int ci=0; ci<CAND; ci++){\n                ll d=0;\n                int m=candM[ci];\n                for(int k=0;k<9;k++){\n                    int v = Br[ off[ci][k] ] + stamps[m][k];\n                    if(v < MOD) d += stamps[m][k];\n                    else        d += (ll)stamps[m][k] - MOD;\n                }\n                if(d > bd[0]){\n                    bd[2]=bd[1]; bi[2]=bi[1];\n                    bd[1]=bd[0]; bi[1]=bi[0];\n                    bd[0]=d;    bi[0]=ci;\n                } else if(d > bd[1]){\n                    bd[2]=bd[1]; bi[2]=bi[1];\n                    bd[1]=d;    bi[1]=ci;\n                } else if(d > bd[2]){\n                    bd[2]=d;    bi[2]=ci;\n                }\n            }\n            if(bd[0] <= 0) break;\n            int Tcur = min(3, K-step);\n            int pick = int(fast_rand() % Tcur);\n            int ci = bi[pick];\n            // apply\n            apply_add(Br,ci);\n            ops.push_back({candM[ci],candP[ci],candQ[ci]});\n        }\n        ll sc=0;\n        for(int i=0;i<81;i++) sc += Br[i];\n        if(sc > bestScore){\n            bestScore = sc;\n            bestOps   = ops;\n        }\n    }\n\n    // ----------------------------------------------------------------\n    // 3) FINAL HILL\u2010CLIMBING SWAP/ADD\n    // ----------------------------------------------------------------\n    // rebuild best\u2010so\u2010far board\n    static int Bcurr[81], Btemp[81];\n    memcpy(Bcurr, B0, sizeof B0);\n    for(auto &op : bestOps){\n        int m=op[0], p=op[1], q=op[2];\n        int ci = mapCI[m][p][q];\n        apply_add(Bcurr, ci);\n    }\n    ll currScore = bestScore;\n    auto localOps = bestOps;\n\n    int li=0;\n    while(true){\n        if((++li & 15)==0){\n            auto tnow = chrono::steady_clock::now();\n            if(chrono::duration_cast<chrono::milliseconds>(tnow - t0).count() > 1980)\n                break;\n        }\n        // 5% chance to try an ADD if room\n        if((int)localOps.size() < K && (fast_rand() & 31) == 0){\n            int ci_new = int(fast_rand() % CAND);\n            memcpy(Btemp, Bcurr, sizeof Bcurr);\n            apply_add(Btemp, ci_new);\n            ll scn=0;\n            for(int i=0;i<81;i++) scn += Btemp[i];\n            if(scn > currScore){\n                currScore = scn;\n                localOps.push_back({candM[ci_new],candP[ci_new],candQ[ci_new]});\n                memcpy(Bcurr, Btemp, sizeof Bcurr);\n            }\n        } else {\n            // replace one existing op\n            if(localOps.empty()) continue;\n            int idx = fast_rand() % localOps.size();\n            auto [mo,po,qo] = localOps[idx];\n            int ci_old = mapCI[mo][po][qo];\n            int ci_new = int(fast_rand() % CAND);\n            if(ci_new == ci_old) continue;\n            // sim remove+add\n            memcpy(Btemp, Bcurr, sizeof Bcurr);\n            // removal\n            int m_old = candM[ci_old];\n            for(int k=0;k<9;k++){\n                int pos = off[ci_old][k];\n                int c = Btemp[pos] - stamps[m_old][k];\n                if(c < 0) c += MOD;\n                Btemp[pos] = c;\n            }\n            // addition\n            apply_add(Btemp, ci_new);\n            // score\n            ll scn=0;\n            for(int i=0;i<81;i++) scn += Btemp[i];\n            if(scn > currScore){\n                currScore = scn;\n                localOps[idx] = {candM[ci_new],candP[ci_new],candQ[ci_new]};\n                memcpy(Bcurr, Btemp, sizeof Bcurr);\n            }\n        }\n    }\n\n    // output the best found\n    cout << localOps.size() << \"\\n\";\n    for(auto &op : localOps){\n        cout << op[0] << \" \" << op[1] << \" \" << op[2] << \"\\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    cin >> N;\n    vector<vector<int>> A(N, vector<int>(N));\n    for(int i = 0; i < N; i++)\n        for(int j = 0; j < N; j++)\n            cin >> A[i][j];\n\n    // We'll bomb the N-1 small cranes and do everything with crane 0.\n    vector<string> S(N);\n    S[0] = \"\";\n    for(int i = 1; i < N; i++){\n        S[i] = \"B\";               // turn 0: bomb crane i\n    }\n\n    // State for the large crane 0:\n    int curR = 0, curC = 0;       // its current position\n    vector<int> picked(N, 0);     // how many we've picked from each receiving gate\n    vector<int> delivered(N, 0);  // how many we've dispatched at each dispatch gate\n    vector<char> ops0;\n    ops0.reserve(1000);\n\n    int total = N * N;\n    for(int done = 0; done < total; done++){\n        // 1) Gather all head\u2010of\u2010queue candidates:\n        struct Cand { int r, id, dest, cost; };\n        vector<Cand> safe, all;\n        for(int r = 0; r < N; r++){\n            if(picked[r] < N){\n                int id = A[r][ picked[r] ];\n                int dest = id / N;\n                int cost = abs(curR - r) + abs(curC - 0);\n                all.push_back({r,id,dest,cost});\n                // safe if this id is exactly the next we need at its dispatch gate\n                if(id == dest * N + delivered[dest]){\n                    safe.push_back({r,id,dest,cost});\n                }\n            }\n        }\n\n        // 2) Choose which gate to service:\n        int bestR=-1, bestID=-1, bestDest=-1;\n        if(!safe.empty()){\n            // pick the safe one with minimal travel cost (tie\u2010break by smaller ID)\n            auto it = min_element(safe.begin(), safe.end(),\n                [](auto &a, auto &b){\n                    if(a.cost != b.cost) return a.cost < b.cost;\n                    return a.id < b.id;\n                });\n            bestR = it->r;  bestID = it->id;  bestDest = it->dest;\n        } else {\n            // no safe pick \u21d2 we must pick something, so fall back\n            // to \u201csmallest head\u2010ID\u201d (tie\u2010break by cost)\n            auto it = min_element(all.begin(), all.end(),\n                [](auto &a, auto &b){\n                    if(a.id != b.id) return a.id < b.id;\n                    return a.cost < b.cost;\n                });\n            bestR = it->r;  bestID = it->id;  bestDest = it->dest;\n        }\n\n        // 3) Move crane0 from (curR,curC) to (bestR,0)\n        int dr = bestR - curR;\n        if(dr > 0) while(dr--) ops0.push_back('D');\n        else      while(dr++) ops0.push_back('U');\n        int dc = 0 - curC;\n        if(dc > 0) while(dc--) ops0.push_back('R');\n        else       while(dc++) ops0.push_back('L');\n\n        // 4) Pick up\n        ops0.push_back('P');\n        picked[bestR]++;\n\n        // 5) Carry it to its correct dispatch gate at (bestDest, N-1)\n        //    first move horizontally to column N-1\n        for(int x = 0; x < N-1; x++)\n            ops0.push_back('R');\n        //    then vertically from row=bestR to bestDest\n        dr = bestDest - bestR;\n        if(dr > 0) while(dr--) ops0.push_back('D');\n        else      while(dr++) ops0.push_back('U');\n\n        // 6) Drop\n        ops0.push_back('Q');\n        delivered[bestDest]++;\n\n        // 7) Update crane0 position\n        curR = bestDest;\n        curC = N-1;\n    }\n\n    // Build the final output, padding all strings to the same length:\n    int M = ops0.size();\n    // Crane 0's commands:\n    S[0].reserve(M);\n    for(char c : ops0) S[0].push_back(c);\n    // The others: we already have 'B' at turn 0, now pad with '.'\n    for(int i = 1; i < N; i++){\n        S[i].append(M-1, '.');\n    }\n\n    // Print\n    for(int i = 0; i < N; i++){\n        cout << S[i] << \"\\n\";\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Task {\n    int sx, sy;\n    int tx, ty;\n    int d;\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<vector<int>> h(N, vector<int>(N));\n    for(int i = 0; i < N; i++)\n        for(int j = 0; j < N; j++)\n            cin >> h[i][j];\n\n    // 1) collect sources and sinks\n    vector<pair<int,int>> src, dst;\n    vector<int> supply, demand;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(h[i][j] > 0){\n                src.emplace_back(i,j);\n                supply.push_back(h[i][j]);\n            } else if(h[i][j] < 0){\n                dst.emplace_back(i,j);\n                demand.push_back(-h[i][j]);\n            }\n        }\n    }\n    int S = src.size(), T = dst.size();\n    if(S == 0){\n        // already flat?\n        return 0;\n    }\n\n    // 2) build all pairs with distance\n    struct Edge { int dist, i, j; };\n    vector<Edge> E;\n    E.reserve(S*T);\n    for(int i = 0; i < S; i++){\n        for(int j = 0; j < T; j++){\n            int d = abs(src[i].first - dst[j].first)\n                  + abs(src[i].second - dst[j].second);\n            E.push_back({d, i, j});\n        }\n    }\n    sort(E.begin(), E.end(),\n         [&](auto &a, auto &b){ return a.dist < b.dist; });\n\n    // 3) greedy matching\n    vector<int> remS = supply, remT = demand;\n    vector<vector<int>> flow(S, vector<int>(T,0));\n    for(auto &e : E){\n        int i = e.i, j = e.j;\n        if(remS[i] == 0 || remT[j] == 0) continue;\n        int d = min(remS[i], remT[j]);\n        flow[i][j] = d;\n        remS[i] -= d;\n        remT[j] -= d;\n    }\n\n    // 4) collect tasks\n    vector<Task> tasks;\n    tasks.reserve(S+T);\n    for(int i = 0; i < S; i++){\n        for(int j = 0; j < T; j++){\n            if(flow[i][j] > 0){\n                tasks.push_back({\n                    src[i].first, src[i].second,\n                    dst[j].first, dst[j].second,\n                    flow[i][j]\n                });\n            }\n        }\n    }\n\n    // 5) execute tasks in nearest\u2010neighbor order\n    int cx = 0, cy = 0;\n    vector<string> ops;\n    ops.reserve(40000);\n\n    auto go = [&](int nx, int ny){\n        while(cx < nx){ ops.push_back(\"D\"); cx++; }\n        while(cx > nx){ ops.push_back(\"U\"); cx--; }\n        while(cy < ny){ ops.push_back(\"R\"); cy++; }\n        while(cy > ny){ ops.push_back(\"L\"); cy--; }\n    };\n\n    while(!tasks.empty()){\n        // pick the task whose source is closest (empty travel)\n        int best = 0, bestd = INT_MAX;\n        for(int i = 0; i < (int)tasks.size(); i++){\n            int d = abs(tasks[i].sx - cx)\n                  + abs(tasks[i].sy - cy);\n            if(d < bestd){\n                bestd = d;\n                best = i;\n            }\n        }\n        Task t = tasks[best];\n        // remove it\n        tasks[best] = tasks.back();\n        tasks.pop_back();\n\n        // move to source\n        go(t.sx, t.sy);\n        // load\n        ops.push_back(\"+\" + to_string(t.d));\n        // move to sink\n        go(t.tx, t.ty);\n        // unload\n        ops.push_back(\"-\" + to_string(t.d));\n    }\n\n    // output\n    for(auto &s : ops) {\n        cout << s << \"\\n\";\n    }\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    cin >> N >> M >> T;\n    const int S = 2 * N * (N - 1);    // 60 when N=6\n\n    // read initial seeds\n    vector<vector<int>> X(S, vector<int>(M));\n    for(int i = 0; i < S; i++)\n      for(int j = 0; j < M; j++)\n        cin >> X[i][j];\n\n    // precompute the four 2\u00d72 central cells\n    vector<pair<int,int>> core;\n    int a = N/2 - 1, b = N/2;\n    core.push_back({a, a});\n    core.push_back({a, b});\n    core.push_back({b, a});\n    core.push_back({b, b});\n\n    // precompute the other interior (deg=4), edge (deg=3), corner (deg=2) cells\n    auto dist2 = [&](int i, int j){\n        // manhattan to true center (N-1)/2, scaled by 2 to avoid fractions\n        return abs(2*i - (N-1)) + abs(2*j - (N-1));\n    };\n    vector<pair<int,int>> interior, edges, corners;\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            int deg = (i>0) + (i<N-1) + (j>0) + (j<N-1);\n            bool inCore = (i==a||i==b) && (j==a||j==b);\n            if(deg==4 && !inCore){\n                interior.emplace_back(i,j);\n            } else if(deg==3){\n                edges.emplace_back(i,j);\n            } else if(deg==2){\n                corners.emplace_back(i,j);\n            }\n        }\n    }\n    // sort interior & edges by centrality\n    sort(interior.begin(), interior.end(), [&](auto &A, auto &B){\n        int d1 = dist2(A.first,A.second), d2 = dist2(B.first,B.second);\n        if(d1!=d2) return d1<d2;\n        return A < B;\n    });\n    sort(edges.begin(), edges.end(), [&](auto &A, auto &B){\n        int d1 = dist2(A.first,A.second), d2 = dist2(B.first,B.second);\n        if(d1!=d2) return d1<d2;\n        return A < B;\n    });\n    sort(corners.begin(), corners.end());\n\n    // main T turns\n    for(int turn = 0; turn < T; turn++){\n        // 1) compute per\u2010seed total sums\n        vector<int> sumVal(S);\n        vector<pair<int,int>> V(S);\n        for(int i = 0; i < S; i++){\n            int s = 0;\n            for(int x : X[i]) s += x;\n            sumVal[i] = s;\n            V[i] = {s, i};\n        }\n        sort(V.begin(), V.end(), greater<>());  // by sum desc\n\n        // 2) pick the champion\u2010of\u2010each\u2010dimension\n        vector<int> best_dim(M), champSeeds;\n        {\n            vector<char> used(S,0);\n            for(int d = 0; d < M; d++){\n                int who = 0, bv = -1;\n                for(int i = 0; i < S; i++){\n                    if(X[i][d] > bv){\n                        bv = X[i][d];\n                        who = i;\n                    }\n                }\n                if(!used[who]){\n                    used[who] = 1;\n                    champSeeds.push_back(who);\n                }\n            }\n        }\n        // 3) fill up to N*N = 36 by top\u2010sum\n        vector<char> usedSel(S,0);\n        vector<int> picks = champSeeds;\n        for(int id : champSeeds) usedSel[id] = 1;\n        for(auto &pr : V){\n            if((int)picks.size() >= N*N) break;\n            int id = pr.second;\n            if(!usedSel[id]){\n                usedSel[id] = 1;\n                picks.push_back(id);\n            }\n        }\n        // 4) sort our picks by their total\u2010sum descending\n        sort(picks.begin(), picks.end(), [&](int a, int b){\n            return sumVal[a] > sumVal[b];\n        });\n\n        // 5) carve off the top\u20104 for the core\n        vector<int> top4(picks.begin(), picks.begin()+4);\n        //    and rebuild the champion\u2010only list EXcluding any of those top4\n        vector<int> ch2;\n        for(int c: champSeeds){\n            if(find(top4.begin(), top4.end(), c) == top4.end())\n                ch2.push_back(c);\n        }\n        //    sort those by sum desc so best champions get closest to center\n        sort(ch2.begin(), ch2.end(), [&](int a, int b){\n            return sumVal[a] > sumVal[b];\n        });\n\n        // 6) assign into the grid\n        vector<vector<int>> A(N, vector<int>(N, -1));\n        vector<char> usedA(S,0);\n        // 6a) core\n        for(int i = 0; i < 4; i++){\n            auto [r,c] = core[i];\n            A[r][c] = top4[i];\n            usedA[top4[i]] = 1;\n        }\n        // 6b) interior\u2010exclusive\n        int idx = 0;\n        for(int i = 0; i < (int)interior.size() && i < (int)ch2.size(); i++){\n            auto [r,c] = interior[i];\n            A[r][c] = ch2[i];\n            usedA[ch2[i]] = 1;\n            idx = i+1;\n        }\n        // 6c) fill the rest of interior with the highest\u2010sum picks\n        int ptr = 0;\n        for(int i = idx; i < (int)interior.size(); i++){\n            while(usedA[picks[ptr]]) ptr++;\n            auto [r,c] = interior[i];\n            A[r][c] = picks[ptr++];\n            usedA[A[r][c]] = 1;\n        }\n        // 6d) fill edges\n        for(auto &cell : edges){\n            while(usedA[picks[ptr]]) ptr++;\n            A[cell.first][cell.second] = picks[ptr++];\n            usedA[A[cell.first][cell.second]] = 1;\n        }\n        // 6e) fill corners\n        for(auto &cell : corners){\n            while(usedA[picks[ptr]]) ptr++;\n            A[cell.first][cell.second] = picks[ptr++];\n            usedA[A[cell.first][cell.second]] = 1;\n        }\n\n        // 7) output & flush\n        for(int i = 0; i < N; i++){\n            for(int j = 0; j < N; j++){\n                cout << A[i][j] << (j+1<N? ' ':'\\n');\n            }\n        }\n        cout << flush;\n\n        // 8) read the next generation\n        for(int i = 0; i < S; i++){\n            for(int j = 0; j < M; j++){\n                cin >> X[i][j];\n            }\n        }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Directions: 0=right,1=down,2=left,3=up\nstatic const int DX[4] = {0,1,0,-1};\nstatic const int DY[4] = {1,0,-1,0};\nstatic const char DIRC[4] = {'R','D','L','U'};\n\nint N, M, Vmax, F, Vp;\nvector<pair<int,int>> src, dst;\nvector<vector<char>> cur;\nvector<int> dir_leaf;            // direction of each leaf\nvector<bool> holding_leaf;       // holding\u2010flag per leaf\nint rx, ry;                      // root position\nvector<string> ops;\n\n// Map each source\u2010cell to its index (or -1 if none)\nvector<vector<int>> src_idx;\n\n// Precomputed for each target j: the src\u2010index that shares that cell, or -1\nvector<int> dst_src_idx;\n\n// Compute minimal turns for leaf `lid` to move its fingertip onto (tx,ty)\nint schedule_cost(int lid, int tx, int ty) {\n    int best = INT_MAX;\n    int d0 = dir_leaf[lid];\n    for(int d=0; d<4; d++){\n        int brx = tx - DX[d], bry = ty - DY[d];\n        if(brx<0||brx>=N||bry<0||bry>=N) continue;\n        int dist = abs(brx-rx)+abs(bry-ry);\n        int cw  = (d - d0 + 4) % 4;\n        int ccw = (d0 - d + 4) % 4;\n        int rot = min(cw, ccw);\n        best = min(best, max(dist, rot));\n    }\n    return best;\n}\n\n// Actually move leaf `lid` so its fingertip ends on (tx,ty) and emit exactly one 'P'\nvoid move_finger(int lid, int tx, int ty){\n    // 1) Find best orientation + new root\n    int bestT=INT_MAX, bestD=0, brx=0, bry=0, brot=0, bcw=0;\n    int d0 = dir_leaf[lid];\n    for(int d=0; d<4; d++){\n        int nrx = tx - DX[d], nry = ty - DY[d];\n        if(nrx<0||nrx>=N||nry<0||nry>=N) continue;\n        int dist = abs(nrx-rx)+abs(nry-ry);\n        int cw  = (d - d0 + 4) % 4;\n        int ccw = (d0 - d + 4) % 4;\n        int rot = min(cw, ccw);\n        int T = max(dist, rot);\n        if(T < bestT){\n            bestT = T;\n            bestD = d;\n            brx = nrx; bry = nry;\n            brot = rot;\n            bcw = (cw <= ccw);\n        }\n    }\n    if(bestT == INT_MAX){\n        // Should never happen\n        ops.push_back(string(2*Vp, '.'));\n        return;\n    }\n    // We need \u22651 turn (to do the P).\n    int T = max(1, bestT);\n    int dist   = abs(brx - rx) + abs(bry - ry);\n    int rotCnt = brot;\n    int rem_dx = brx - rx, rem_dy = bry - ry;\n    char rotCh = (bcw ? 'R' : 'L');\n\n    for(int step=0; step<T; step++){\n        char m='.', r='.', a='.';\n        // Move root\n        if(step < dist){\n            if(rem_dx>0){ m='D'; rem_dx--; rx++; }\n            else if(rem_dx<0){ m='U'; rem_dx++; rx--; }\n            else if(rem_dy>0){ m='R'; rem_dy--; ry++; }\n            else if(rem_dy<0){ m='L'; rem_dy++; ry--; }\n        }\n        // Rotate this leaf\n        if(step < rotCnt){\n            r = rotCh;\n            if(rotCh=='R') dir_leaf[lid] = (dir_leaf[lid]+1)&3;\n            else           dir_leaf[lid] = (dir_leaf[lid]+3)&3;\n        }\n        // On last step, do P if valid\n        if(step == T-1){\n            int fx = rx + DX[ dir_leaf[lid] ];\n            int fy = ry + DY[ dir_leaf[lid] ];\n            if(0<=fx && fx<N && 0<=fy && fy<N){\n                if(!holding_leaf[lid] && cur[fx][fy]){\n                    // pickup\n                    cur[fx][fy] = 0;\n                    holding_leaf[lid] = true;\n                    a = 'P';\n                } else if(holding_leaf[lid] && !cur[fx][fy]){\n                    // drop\n                    cur[fx][fy] = 1;\n                    holding_leaf[lid] = false;\n                    a = 'P';\n                }\n            }\n        }\n        // Build the 2*Vp string: [move][rot(1)][rot(2)]\u2026[rot(F)] [act(0)] [act(1)]\u2026[act(F)]\n        string S(2*Vp, '.');\n        S[0]       = m;\n        S[lid]     = r;\n        S[Vp + lid]= a;\n        ops.push_back(S);\n    }\n    dir_leaf[lid] = bestD;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M >> Vmax;\n    vector<string> Sin(N), Tin(N);\n    for(int i=0;i<N;i++) cin>>Sin[i];\n    for(int i=0;i<N;i++) cin>>Tin[i];\n\n    // Read sources & targets\n    src.reserve(M);\n    dst.reserve(M);\n    cur.assign(N, vector<char>(N,0));\n    vector<vector<char>> occ(N, vector<char>(N,0));\n    for(int i=0;i<N;i++) for(int j=0;j<N;j++){\n        if(Sin[i][j]=='1'){\n            src.emplace_back(i,j);\n            cur[i][j] = 1;\n            occ[i][j]=1;\n        }\n        if(Tin[i][j]=='1'){\n            dst.emplace_back(i,j);\n            occ[i][j]=1;\n        }\n    }\n\n    // Build src_idx map\n    src_idx.assign(N, vector<int>(N, -1));\n    for(int i=0;i<M;i++){\n        auto &p = src[i];\n        src_idx[p.first][p.second] = i;\n    }\n    // Build dst_src_idx\n    dst_src_idx.assign(M, -1);\n    for(int j=0;j<M;j++){\n        auto &p = dst[j];\n        dst_src_idx[j] = src_idx[p.first][p.second];\n    }\n\n    // We'll use a star\u2010arm of F leaves\n    F  = min((int)src.size(), Vmax-1);\n    Vp = F + 1;\n    cout << Vp << \"\\n\";\n    for(int i=1;i<=F;i++){\n        cout << 0 << \" \" << 1 << \"\\n\";\n    }\n\n    // Pick initial root near center on an empty square\n    int center = (N-1)/2, bestd = INT_MAX;\n    rx = ry = 0;\n    for(int i=0;i<N;i++) for(int j=0;j<N;j++){\n        if(occ[i][j]) continue;\n        int d = abs(i-center)+abs(j-center);\n        if(d < bestd){\n            bestd = d;\n            rx = i; ry = j;\n        }\n    }\n    cout << rx << \" \" << ry << \"\\n\";\n\n    // Init per\u2010leaf state\n    dir_leaf.assign(Vp, 0);\n    holding_leaf.assign(Vp, false);\n    vector<char> used_src(M,0), used_dst(M,0);\n    int remaining = M;\n\n    // Process in batches of size F\n    while(remaining > 0){\n        int batch = min(remaining, F);\n        // 1) pickups\n        for(int u=1; u<=batch; u++){\n            int best_i=-1, bestC=INT_MAX;\n            for(int i=0;i<M;i++){\n                if(used_src[i]) continue;\n                int c = schedule_cost(u, src[i].first, src[i].second);\n                if(c < bestC){\n                    bestC = c;\n                    best_i = i;\n                }\n            }\n            used_src[best_i] = 1;\n            move_finger(u, src[best_i].first, src[best_i].second);\n        }\n        // 2) drops\n        for(int u=1; u<=batch; u++){\n            int best_j=-1, bestC=INT_MAX;\n            for(int j=0;j<M;j++){\n                if(used_dst[j]) continue;\n                // *Enforce overlap-dependency*: if this target cell was also a source\n                // and that source hasn't been picked yet, skip it.\n                int si = dst_src_idx[j];\n                if(si >= 0 && !used_src[si]) continue;\n                int c = schedule_cost(u, dst[j].first, dst[j].second);\n                if(c < bestC){\n                    bestC = c;\n                    best_j = j;\n                }\n            }\n            used_dst[best_j] = 1;\n            move_finger(u, dst[best_j].first, dst[best_j].second);\n        }\n        remaining -= batch;\n    }\n\n    // Emit all turns\n    for(auto &s: ops){\n        cout << s << \"\\n\";\n    }\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pt { int x, y, w; };\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int HMAX = 100000;\n    const int CG   = 200;\n    const int KREF = 50;   // allow bridging gutters up to 50\n    const int JTR  = 40;   // final jitter trials\n    const int RRS  = 25;   // random\u2010restart trials\n\n    // Multiscale X\u2013sliding windows: (width, trials)\n    vector<pair<int,int>> XSETS = {\n      {  50,  5},\n      { 100,  8},\n      { 200, 15},\n      { 350, 30},\n      { 600,  5}\n    };\n    // Multiscale Y\u2013sliding windows: (height, trials)\n    vector<pair<int,int>> YSETS = {\n      {  50,  5},\n      { 100,  8},\n      { 200, 10},\n      { 300,  6},\n      { 600,  3}\n    };\n\n    int N;\n    cin >> N;\n    vector<Pt> pts(2*N);\n    for(int i = 0; i < 2*N; i++){\n        cin >> pts[i].x >> pts[i].y;\n        pts[i].w = (i < N ? +1 : -1);\n    }\n\n    // 1) Coordinate compression\n    vector<int> xs, ys;\n    xs.reserve(2*N); ys.reserve(2*N);\n    for(auto &p: pts){\n        xs.push_back(p.x);\n        ys.push_back(p.y);\n    }\n    sort(xs.begin(), xs.end());\n    xs.erase(unique(xs.begin(), xs.end()), xs.end());\n    sort(ys.begin(), ys.end());\n    ys.erase(unique(ys.begin(), ys.end()), ys.end());\n    int MX = xs.size(), MY = ys.size();\n\n    vector<int> cX(2*N), cY(2*N);\n    for(int i = 0; i < 2*N; i++){\n        cX[i] = int(lower_bound(xs.begin(), xs.end(), pts[i].x) - xs.begin());\n        cY[i] = int(lower_bound(ys.begin(), ys.end(), pts[i].y) - ys.begin());\n    }\n\n    // 2) Build per\u2010column & per\u2010row bins + prefix sums\n    vector<vector<pair<int,int>>> binsX(MX), binsY(MY);\n    for(int i = 0; i < 2*N; i++){\n        binsX[cX[i]].emplace_back(cY[i], pts[i].w);\n        binsY[cY[i]].emplace_back(cX[i], pts[i].w);\n    }\n    vector<vector<int>> bX_y(MX), bX_ps(MX), bY_x(MY), bY_ps(MY);\n    for(int x = 0; x < MX; x++){\n        auto &v = binsX[x];\n        sort(v.begin(), v.end());\n        int m = v.size();\n        bX_y[x].resize(m);\n        bX_ps[x].resize(m);\n        for(int i = 0; i < m; i++){\n            bX_y[x][i]  = v[i].first;\n            bX_ps[x][i] = v[i].second + (i ? bX_ps[x][i-1] : 0);\n        }\n    }\n    for(int y = 0; y < MY; y++){\n        auto &v = binsY[y];\n        sort(v.begin(), v.end());\n        int m = v.size();\n        bY_x[y].resize(m);\n        bY_ps[y].resize(m);\n        for(int i = 0; i < m; i++){\n            bY_x[y][i]  = v[i].first;\n            bY_ps[y][i] = v[i].second + (i ? bY_ps[y][i-1] : 0);\n        }\n    }\n\n    // Helpers: sum of column cx over y\u2208[y1..y2], row cy over x\u2208[x1..x2]\n    auto colSum = [&](int cx, int y1, int y2){\n        auto &vy = bX_y[cx], &ps = bX_ps[cx];\n        int lo = int(lower_bound(vy.begin(), vy.end(), y1) - vy.begin());\n        int hi = int(upper_bound(vy.begin(), vy.end(), y2) - vy.begin()) - 1;\n        if(lo > hi) return 0;\n        return ps[hi] - (lo ? ps[lo-1] : 0);\n    };\n    auto rowSum = [&](int cy, int x1, int x2){\n        auto &vx = bY_x[cy], &ps = bY_ps[cy];\n        int lo = int(lower_bound(vx.begin(), vx.end(), x1) - vx.begin());\n        int hi = int(upper_bound(vx.begin(), vx.end(), x2) - vx.begin()) - 1;\n        if(lo > hi) return 0;\n        return ps[hi] - (lo ? ps[lo-1] : 0);\n    };\n\n    // 3) Multi\u2010step local refine for a rectangle [x1..x2]\u00d7[y1..y2]\n    auto refineRect = [&](int &x1, int &x2, int &y1, int &y2, int &A){\n        bool improved = true;\n        while(improved){\n            improved = false;\n            // expansions\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && x1-k>=0; k++){\n                    s += colSum(x1-k, y1, y2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ x1-=bk; A+=best; improved=true; continue; }\n            }\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && x2+k<MX; k++){\n                    s += colSum(x2+k, y1, y2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ x2+=bk; A+=best; improved=true; continue; }\n            }\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && y1-k>=0; k++){\n                    s += rowSum(y1-k, x1, x2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ y1-=bk; A+=best; improved=true; continue; }\n            }\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && y2+k<MY; k++){\n                    s += rowSum(y2+k, x1, x2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ y2+=bk; A+=best; improved=true; continue; }\n            }\n            // contractions\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && x1+k-1<=x2; k++){\n                    s += colSum(x1+k-1, y1, y2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ x1+=bk; A-=worst; improved=true; continue; }\n            }\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && x2-k+1>=x1; k++){\n                    s += colSum(x2-k+1, y1, y2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ x2-=bk; A-=worst; improved=true; continue; }\n            }\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && y1+k-1<=y2; k++){\n                    s += rowSum(y1+k-1, x1, x2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ y1+=bk; A-=worst; improved=true; continue; }\n            }\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && y2-k+1>=y1; k++){\n                    s += rowSum(y2-k+1, x1, x2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ y2-=bk; A-=worst; improved=true; continue; }\n            }\n        }\n    };\n\n    struct Rect { int x1,x2,y1,y2,A; };\n    vector<Rect> cands;\n    mt19937_64 rng(1234567);\n\n    // 4) Multiscale X\u2010sliding windows\n    for(auto &ws : XSETS){\n        int K = ws.first, NI = ws.second;\n        uniform_int_distribution<int> distL(0, max(0, MX - K));\n        vector<int> W(MY);\n        int bestA = INT_MIN, bx1=0,bx2=0,by1=0,by2=0;\n        for(int it=0; it<NI; it++){\n            int L = (MX>K ? distL(rng) : 0);\n            fill(W.begin(), W.end(), 0);\n            int Rlim = min(MX, L + K);\n            for(int R=L; R<Rlim; R++){\n                for(auto &pr: binsX[R])\n                    W[pr.first] += pr.second;\n                // Kadane on W\n                int cur=W[0], t0=0, best=cur, sy=0, ey=0;\n                for(int y=1; y<MY; y++){\n                    if(cur>0) cur+=W[y];\n                    else { cur=W[y]; t0=y; }\n                    if(cur>best){ best=cur; sy=t0; ey=y; }\n                }\n                if(best>bestA){\n                    bestA=best;\n                    bx1=L; bx2=R;\n                    by1=sy; by2=ey;\n                }\n            }\n        }\n        if(bestA>INT_MIN/2)\n            cands.push_back({bx1,bx2,by1,by2,bestA});\n    }\n\n    // 5) Multiscale Y\u2010sliding windows (Kadane on X)\n    for(auto &hs : YSETS){\n        int Ht=hs.first, NI=hs.second;\n        uniform_int_distribution<int> distY(0, max(0, MY - Ht));\n        vector<int> W2(MX);\n        int bestA=INT_MIN, hy1=0,hy2=0,hx1=0,hx2=0;\n        for(int it=0; it<NI; it++){\n            int Ly = (MY>Ht ? distY(rng) : 0);\n            fill(W2.begin(), W2.end(), 0);\n            int Rym = min(MY, Ly + Ht);\n            for(int Ry=Ly; Ry<Rym; Ry++){\n                for(auto &pr: binsY[Ry])\n                    W2[pr.first] += pr.second;\n                // Kadane on W2\n                int cur=W2[0], t0=0, best=cur, sx=0, ex=0;\n                for(int x=1; x<MX; x++){\n                    if(cur>0) cur+=W2[x];\n                    else { cur=W2[x]; t0=x; }\n                    if(cur>best){ best=cur; sx=t0; ex=x; }\n                }\n                if(best>bestA){\n                    bestA=best;\n                    hy1=Ly; hy2=Ry;\n                    hx1=sx; hx2=ex;\n                }\n            }\n        }\n        if(bestA>INT_MIN/2)\n            cands.push_back({hx1,hx2,hy1,hy2,bestA});\n    }\n\n    // 6) Full\u2010width & full\u2010height stripes\n    {\n        vector<int> Wcol(MX);\n        for(int x=0; x<MX; x++)\n            Wcol[x] = bX_ps[x].empty() ? 0 : bX_ps[x].back();\n        int cur=Wcol[0], t0=0, best=cur, sx=0, ex=0;\n        for(int x=1; x<MX; x++){\n            if(cur>0) cur+=Wcol[x];\n            else { cur=Wcol[x]; t0=x; }\n            if(cur>best){ best=cur; sx=t0; ex=x; }\n        }\n        cands.push_back({sx,ex,0,MY-1,best});\n    }\n    {\n        vector<int> Wrow(MY);\n        for(int y=0; y<MY; y++)\n            Wrow[y] = bY_ps[y].empty() ? 0 : bY_ps[y].back();\n        int cur=Wrow[0], t0=0, best=cur, sy=0, ey=0;\n        for(int y=1; y<MY; y++){\n            if(cur>0) cur+=Wrow[y];\n            else { cur=Wrow[y]; t0=y; }\n            if(cur>best){ best=cur; sy=t0; ey=y; }\n        }\n        cands.push_back({0,MX-1,sy,ey,best});\n    }\n\n    // 7) Coarse\u2192fine rectangle\n    static int cgrid[CG][CG];\n    int CW = (HMAX + CG) / CG;\n    for(int i=0;i<CG;i++) for(int j=0;j<CG;j++) cgrid[i][j]=0;\n    for(auto &p: pts){\n        int xi = min(CG-1, p.x / CW);\n        int yi = min(CG-1, p.y / CW);\n        cgrid[xi][yi] += p.w;\n    }\n    vector<int> tmpCG(CG);\n    int bestA2=INT_MIN, cx1=0,cx2=0,cy1=0,cy2=0;\n    for(int Lx=0; Lx<CG; Lx++){\n        fill(tmpCG.begin(), tmpCG.end(), 0);\n        for(int Rx=Lx; Rx<CG; Rx++){\n            for(int y=0;y<CG;y++)\n                tmpCG[y] += cgrid[Rx][y];\n            int cur=tmpCG[0], t0=0, best=cur, sy=0, ey=0;\n            for(int y=1;y<CG;y++){\n                if(cur>0) cur+=tmpCG[y];\n                else { cur=tmpCG[y]; t0=y; }\n                if(cur>best){ best=cur; sy=t0; ey=y; }\n            }\n            if(best>bestA2){\n                bestA2=best;\n                cx1=Lx; cx2=Rx;\n                cy1=sy; cy2=ey;\n            }\n        }\n    }\n    {\n        int X0 = cx1*CW, X1 = min(HMAX,(cx2+1)*CW - 1);\n        int Y0 = cy1*CW, Y1 = min(HMAX,(cy2+1)*CW - 1);\n        vector<Pt> sub; sub.reserve(2000);\n        for(auto &p: pts)\n            if(p.x>=X0 && p.x<=X1 && p.y>=Y0 && p.y<=Y1)\n                sub.push_back(p);\n        if(!sub.empty()){\n            vector<int> xs3, ys3;\n            xs3.reserve(sub.size()); ys3.reserve(sub.size());\n            for(auto &q: sub){\n                xs3.push_back(q.x);\n                ys3.push_back(q.y);\n            }\n            sort(xs3.begin(), xs3.end());\n            xs3.erase(unique(xs3.begin(), xs3.end()), xs3.end());\n            sort(ys3.begin(), ys3.end());\n            ys3.erase(unique(ys3.begin(), ys3.end()), ys3.end());\n            int RX = xs3.size(), RY = ys3.size();\n            vector<int> cqx(sub.size()), cqy(sub.size());\n            for(int i=0;i<(int)sub.size();i++){\n                cqx[i] = int(lower_bound(xs3.begin(), xs3.end(), sub[i].x) - xs3.begin());\n                cqy[i] = int(lower_bound(ys3.begin(), ys3.end(), sub[i].y) - ys3.begin());\n            }\n            vector<vector<pair<int,int>>> bX2(RX);\n            for(int i=0;i<(int)sub.size();i++){\n                bX2[cqx[i]].emplace_back(cqy[i], sub[i].w);\n            }\n            int bestA3=INT_MIN, rx1=0,rx2=0,ry1=0,ry2=0;\n            if(RX <= 500){\n                vector<int> tmp(RY);\n                for(int L=0; L<RX; L++){\n                    fill(tmp.begin(), tmp.end(), 0);\n                    for(int R=L; R<RX; R++){\n                        for(auto &pr: bX2[R]) tmp[pr.first] += pr.second;\n                        int cur=tmp[0], t0=0, best=cur, sy=0, ey=0;\n                        for(int y=1;y<RY;y++){\n                            if(cur>0) cur+=tmp[y];\n                            else { cur=tmp[y]; t0=y; }\n                            if(cur>best){ best=cur; sy=t0; ey=y; }\n                        }\n                        if(best>bestA3){\n                            bestA3=best;\n                            rx1=L; rx2=R; ry1=sy; ry2=ey;\n                        }\n                    }\n                }\n            } else {\n                vector<int> tmp(RY);\n                uniform_int_distribution<int> dist2(0, max(0, RX-600));\n                vector<int> starts(6);\n                for(int i=0;i<6;i++) starts[i] = (RX>600?dist2(rng):0);\n                for(int L: starts){\n                    fill(tmp.begin(), tmp.end(), 0);\n                    int Rlim = min(RX, L+600);\n                    for(int R=L; R<Rlim; R++){\n                        for(auto &pr: bX2[R]) tmp[pr.first] += pr.second;\n                        int cur=tmp[0], t0=0, best=cur, sy=0, ey=0;\n                        for(int y=1;y<RY;y++){\n                            if(cur>0) cur+=tmp[y];\n                            else { cur=tmp[y]; t0=y; }\n                            if(cur>best){ best=cur; sy=t0; ey=y; }\n                        }\n                        if(best>bestA3){\n                            bestA3=best;\n                            rx1=L; rx2=R; ry1=sy; ry2=ey;\n                        }\n                    }\n                }\n            }\n            if(bestA3>INT_MIN/2){\n                int gx1 = int(lower_bound(xs.begin(), xs.end(), xs3[rx1]) - xs.begin());\n                int gx2 = int(lower_bound(xs.begin(), xs.end(), xs3[rx2]) - xs.begin());\n                int gy1 = int(lower_bound(ys.begin(), ys.end(), ys3[ry1]) - ys.begin());\n                int gy2 = int(lower_bound(ys.begin(), ys.end(), ys3[ry2]) - ys.begin());\n                if(gx1<=gx2 && gy1<=gy2){\n                    int A3=0;\n                    for(int xx=gx1; xx<=gx2; xx++)\n                        A3 += colSum(xx, gy1, gy2);\n                    cands.push_back({gx1,gx2,gy1,gy2,A3});\n                }\n            }\n        }\n    }\n\n    // 8) Refine all candidates\n    for(auto &r : cands){\n        if(r.x1<=r.x2 && r.y1<=r.y2)\n            refineRect(r.x1, r.x2, r.y1, r.y2, r.A);\n    }\n\n    // 9) Pick current best\n    int bestA = INT_MIN, bx1=0,bx2=0,by1=0,by2=0;\n    for(auto &r : cands){\n        if(r.A > bestA){\n            bestA=r.A;\n            bx1=r.x1; bx2=r.x2;\n            by1=r.y1; by2=r.y2;\n        }\n    }\n\n    // 10) Random\u2010Restart: try RRS random rectangles\n    uniform_int_distribution<int> distX0(0, MX-2), distY0(0, MY-2);\n    for(int it=0; it<RRS; it++){\n        int rx1 = distX0(rng);\n        int ry1 = distY0(rng);\n        int rx2 = uniform_int_distribution<int>(rx1+1, MX-1)(rng);\n        int ry2 = uniform_int_distribution<int>(ry1+1, MY-1)(rng);\n        int A = 0;\n        for(int x=rx1; x<=rx2; x++)\n            A += colSum(x, ry1, ry2);\n        refineRect(rx1, rx2, ry1, ry2, A);\n        if(A > bestA){\n            bestA = A;\n            bx1 = rx1; bx2 = rx2;\n            by1 = ry1; by2 = ry2;\n        }\n    }\n\n    // 11) Final jitter around best\n    uniform_int_distribution<int> uni01(0,1);\n    for(int it=0; it<JTR; it++){\n        int w = bx2 - bx1 + 1, h = by2 - by1 + 1;\n        int dx = max(1, w/2), dy = max(1, h/2);\n        uniform_int_distribution<int> dX(-dx, dx), dY(-dy, dy);\n        int rx1 = clamp(bx1 + dX(rng), 0, MX-2);\n        int rx2 = clamp(bx2 + dX(rng), rx1+1, MX-1);\n        int ry1 = clamp(by1 + dY(rng), 0, MY-2);\n        int ry2 = clamp(by2 + dY(rng), ry1+1, MY-1);\n        int A = 0;\n        for(int x=rx1; x<=rx2; x++)\n            A += colSum(x, ry1, ry2);\n        refineRect(rx1, rx2, ry1, ry2, A);\n        if(A > bestA){\n            bestA = A;\n            bx1 = rx1; bx2 = rx2;\n            by1 = ry1; by2 = ry2;\n        }\n    }\n\n    // 12) Fallback if non\u2010positive or degenerate\n    if(bestA <= 0 || bx2 <= bx1 || by2 <= by1){\n        bx1 = by1 = 0;\n        bx2 = by2 = 1;\n    }\n\n    // 13) Output final 4\u2010vertex rectangle\n    cout << 4 << \"\\n\";\n    cout << xs[bx1] << \" \" << ys[by1] << \"\\n\";\n    cout << xs[bx1] << \" \" << ys[by2] << \"\\n\";\n    cout << xs[bx2] << \" \" << ys[by2] << \"\\n\";\n    cout << xs[bx2] << \" \" << ys[by1] << \"\\n\";\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstatic const int MAXN = 100;\n\nstruct Cand {\n    ll sc;            // predicted score = max_row_width + sum_row_heights\n    int R;            // number of shelves\n    int row[MAXN];    // row[i] = shelf index of rectangle i\n    int rep[MAXN];    // rep[r] = index of tallest rectangle in shelf r\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    ll sigma;\n    if(!(cin >> N >> T >> sigma)) return 0;\n\n    static ll w0[MAXN], h0[MAXN], wi[MAXN], hi[MAXN];\n    for(int i = 0; i < N; i++){\n        cin >> w0[i] >> h0[i];\n        wi[i] = min(w0[i], h0[i]);\n        hi[i] = max(w0[i], h0[i]);\n    }\n\n    // total width sum\n    ll totalW = 0;\n    for(int i = 0; i < N; i++) totalW += wi[i];\n\n    // build up to 2N candidates\n    vector<Cand> cands;\n    cands.reserve(2 * N);\n\n    // temporaries for partitioning\n    static int start1[MAXN], sz1[MAXN];\n    static ll sumW1[MAXN], maxH1[MAXN];\n    static int start2[MAXN], sz2[MAXN];\n    static ll sumW2[MAXN], maxH2[MAXN];\n    static int rowTmp[MAXN], repTmp[MAXN];\n\n    for(int R = 1; R <= N; R++){\n        // ---- Scheme 1: count\u2010balanced ----\n        int base = N / R, rem = N % R;\n        int idx = 0;\n        for(int r = 0; r < R; r++){\n            start1[r] = idx;\n            sz1[r] = base + (r < rem);\n            idx += sz1[r];\n        }\n        // compute rowTmp[], repTmp[], sumW1[], maxH1[]\n        ll sumH = 0, maxW = 0;\n        for(int r = 0; r < R; r++){\n            ll sw = 0, mh = 0;\n            int s = start1[r];\n            int t = s; // for tallest\n            for(int j = 0; j < sz1[r]; j++){\n                int i = s + j;\n                rowTmp[i] = r;\n                sw += wi[i];\n                if(hi[i] > mh) mh = hi[i];\n                if(hi[i] > hi[t]) t = i;\n            }\n            repTmp[r] = t;\n            sumW1[r] = sw;\n            maxH1[r] = mh;\n            if(sw > maxW) maxW = sw;\n            sumH += mh;\n        }\n        {\n            Cand c;\n            c.sc = maxW + sumH;\n            c.R  = R;\n            memcpy(c.row, rowTmp, sizeof(int)*N);\n            memcpy(c.rep, repTmp, sizeof(int)*R);\n            cands.push_back(c);\n        }\n\n        // ---- Scheme 2: width\u2010greedy ----\n        ll target = totalW / R;\n        idx = 0;\n        for(int r = 0; r < R; r++){\n            start2[r] = idx;\n            if(r == R - 1){\n                sz2[r] = N - idx;\n                idx = N;\n            } else {\n                ll acc = wi[idx];\n                sz2[r] = 1;\n                idx++;\n                while(idx < N && acc + wi[idx] <= target){\n                    acc += wi[idx];\n                    sz2[r]++;\n                    idx++;\n                }\n            }\n        }\n        // compute rowTmp, repTmp, sumW2, maxH2\n        sumH = 0; maxW = 0;\n        for(int r = 0; r < R; r++){\n            ll sw = 0, mh = 0;\n            int s = start2[r];\n            int t = s;\n            for(int j = 0; j < sz2[r]; j++){\n                int i = s + j;\n                rowTmp[i] = r;\n                sw += wi[i];\n                if(hi[i] > mh) mh = hi[i];\n                if(hi[i] > hi[t]) t = i;\n            }\n            repTmp[r] = t;\n            sumW2[r] = sw;\n            maxH2[r] = mh;\n            if(sw > maxW) maxW = sw;\n            sumH += mh;\n        }\n        {\n            Cand c;\n            c.sc = maxW + sumH;\n            c.R  = R;\n            memcpy(c.row, rowTmp, sizeof(int)*N);\n            memcpy(c.rep, repTmp, sizeof(int)*R);\n            cands.push_back(c);\n        }\n    }\n\n    // sort candidates by predicted sc ascending\n    sort(cands.begin(), cands.end(),\n         [&](auto &a, auto &b){ return a.sc < b.sc; });\n\n    int C = (int)cands.size();\n    int uniqueTrials = min(C, T);\n\n    ll bestMeasured = LLONG_MAX;\n    int bestIdx     = 0;\n\n    // multi\u2010turn probing\n    for(int t = 0; t < T; t++){\n        int idxCand = (t < uniqueTrials ? t : bestIdx);\n        auto &cd = cands[idxCand];\n\n        // output this candidate\n        cout << N << \"\\n\";\n        for(int i = 0; i < N; i++){\n            int shelf = cd.row[i];\n            int rbit  = (w0[i] > h0[i] ? 1 : 0);\n            char d;\n            int b;\n            if(shelf == 0){\n                // top shelf: push upward, chaining along x\n                d = 'U';\n                if(i > 0 && cd.row[i-1] == 0) b = i-1;\n                else                           b = -1;\n            } else {\n                // other shelves: push left under rep of shelf-1\n                d = 'L';\n                b = cd.rep[shelf - 1];\n            }\n            cout << i << \" \" << rbit << \" \" << d << \" \" << b << \"\\n\";\n        }\n        cout << flush;\n\n        // read back noisy measurement\n        ll Wp, Hp;\n        if(!(cin >> Wp >> Hp)) break;\n        ll meas = Wp + Hp;\n        if(meas < bestMeasured){\n            bestMeasured = meas;\n            bestIdx      = idxCand;\n        }\n    }\n\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, H;\n    cin >> N >> M >> H;\n\n    vector<int> A(N);\n    for(int i = 0; i < N; i++) 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    // discard coordinates\n    for(int i = 0; i < N; i++){\n        int x,y; \n        cin >> x >> y;\n    }\n\n    // ------------------------------------------------\n    // 1) Precompute for each r the list of (v,dist) with dist<=H\n    //    and the staticScore[r] = sum_{v,dist} (dist+1)*A[v]\n    // ------------------------------------------------\n    vector<vector<pair<int,uint8_t>>> reach(N);\n    vector<ll> staticScore(N, 0);\n    vector<int> q(N), dist(N, -1);\n\n    for(int r = 0; r < N; r++){\n        int ql = 0, qr = 0;\n        dist[r] = 0;\n        q[qr++] = r;\n        while(ql < qr){\n            int u = q[ql++];\n            if(dist[u] == H) continue;\n            for(int w: adj[u]){\n                if(dist[w] == -1){\n                    dist[w] = dist[u] + 1;\n                    q[qr++] = w;\n                }\n            }\n        }\n        ll sc = 0;\n        reach[r].reserve(qr);\n        for(int i = 0; i < qr; i++){\n            int v = q[i], d = dist[v];\n            reach[r].emplace_back(v, (uint8_t)d);\n            sc += ll(d + 1) * A[v];\n            dist[v] = -1;\n        }\n        staticScore[r] = sc;\n    }\n\n    // ------------------------------------------------\n    // 2) Multi\u2010start randomized greedy covering\n    // ------------------------------------------------\n    const int RUNS   = 40;  // independent restarts\n    const int TOPS   = 70;  // consider only the top\u201070 static\u2010score roots\n    const int Kbest  = 15;  // randomize among the top\u201015 by dynamic score\n    const int MAX_SUB = 80; // allow reattaching subtrees up to size 80\n\n    mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());\n\n    vector<int> bestParent(N), bestDepth(N);\n    ll bestGlobal = -1;\n\n    // working arrays for each run\n    vector<char> covered(N);\n    vector<int> parent(N), depth(N), dist2(N), q2(N);\n    vector<int> cand(TOPS), idx(TOPS);\n    vector<ll> dyn(TOPS);\n\n    for(int run = 0; run < RUNS; run++){\n        // build a run\u2010specific static ordering by adding \u00b120% noise\n        vector<pair<double,int>> order(N);\n        for(int i = 0; i < N; i++){\n            double noise = (double(rng()%40001)/10000.0 - 2.0) * 0.1; // [-0.2,+0.2]\n            order[i] = { staticScore[i] * (1.0 + noise), i };\n        }\n        sort(order.begin(), order.end(),\n             [&](auto &a, auto &b){ return a.first > b.first; });\n        vector<int> staticRun(N);\n        for(int i = 0; i < N; i++) staticRun[i] = order[i].second;\n\n        // reset\n        fill(covered.begin(), covered.end(), 0);\n        fill(parent.begin(), parent.end(), -1);\n        fill(depth.begin(), depth.end(), 0);\n        int rem = N;\n\n        // greedy\u2010cover loop\n        while(rem > 0){\n            // pick up to TOPS uncovered by staticRun\n            int S = 0;\n            for(int v: staticRun){\n                if(!covered[v]){\n                    cand[S++] = v;\n                    if(S == TOPS) break;\n                }\n            }\n            // compute dynamic scores\n            for(int i = 0; i < S; i++){\n                ll sc = 0;\n                int r = cand[i];\n                for(auto &pr: reach[r]){\n                    if(!covered[pr.first]){\n                        sc += ll(pr.second + 1) * A[pr.first];\n                    }\n                }\n                dyn[i] = sc;\n                idx[i] = i;\n            }\n            // partial sort by dyn[]\n            sort(idx.begin(), idx.begin()+S,\n                 [&](int i, int j){ return dyn[i] > dyn[j]; });\n\n            // pick one root (pure greedy on run0, otherwise random among top Kbest)\n            int pick;\n            if(run == 0){\n                pick = idx[0];\n            } else {\n                int L = min(Kbest, S);\n                uniform_int_distribution<int> D(0, L-1);\n                pick = idx[D(rng)];\n            }\n            int root = cand[pick];\n\n            // carve out an H\u2010limited BFS\u2010tree from root\n            fill(dist2.begin(), dist2.end(), -1);\n            int ql2 = 0, qr2 = 0;\n            dist2[root] = 0;\n            covered[root] = 1;\n            parent[root]  = -1;\n            depth[root]   = 0;\n            q2[qr2++]    = root;\n            rem--;\n\n            while(ql2 < qr2){\n                int u = q2[ql2++];\n                if(dist2[u] == H) continue;\n                for(int w: adj[u]){\n                    if(!covered[w] && dist2[w] == -1){\n                        dist2[w]    = dist2[u] + 1;\n                        covered[w]  = 1;\n                        parent[w]   = u;\n                        depth[w]    = dist2[w];\n                        q2[qr2++]   = w;\n                        rem--;\n                    }\n                }\n            }\n        }\n\n        // score this run\n        ll runScore = 0;\n        for(int v = 0; v < N; v++){\n            runScore += ll(depth[v] + 1) * A[v];\n        }\n        if(runScore > bestGlobal){\n            bestGlobal = runScore;\n            bestParent = parent;\n            bestDepth  = depth;\n        }\n    }\n\n    // ------------------------------------------------\n    // 3) \u201cSmall\u2010subtree reattachment\u201d local search (\u00d72 passes)\n    // ------------------------------------------------\n    vector<vector<int>> children(N);\n    vector<int> rootOf(N), tin(N), tout(N), subSize(N), subMaxD(N);\n    vector<ll> subSumA(N);\n    int timer;\n\n    auto rebuild = [&](){\n        for(int i = 0; i < N; i++) children[i].clear();\n        for(int v = 0; v < N; v++){\n            int p = bestParent[v];\n            if(p >= 0) children[p].push_back(v);\n        }\n        fill(rootOf.begin(), rootOf.end(), -1);\n        deque<int> dq;\n        for(int v = 0; v < N; v++){\n            if(bestParent[v] < 0){\n                rootOf[v] = v;\n                dq.push_back(v);\n                while(!dq.empty()){\n                    int u = dq.front(); dq.pop_front();\n                    for(int c: children[u]){\n                        rootOf[c] = rootOf[v];\n                        dq.push_back(c);\n                    }\n                }\n            }\n        }\n    };\n\n    function<void(int)> dfsSub = [&](int v){\n        tin[v] = timer++;\n        subSize[v]   = 1;\n        subSumA[v]   = A[v];\n        subMaxD[v]   = 0;\n        for(int c: children[v]){\n            dfsSub(c);\n            subSize[v]   += subSize[c];\n            subSumA[v]   += subSumA[c];\n            subMaxD[v]   = max(subMaxD[v], subMaxD[c] + 1);\n        }\n        tout[v] = timer;\n    };\n\n    for(int pass = 0; pass < 2; pass++){\n        while(true){\n            rebuild();\n            timer = 0;\n            for(int v = 0; v < N; v++){\n                if(bestParent[v] < 0) dfsSub(v);\n            }\n            ll bestGain = 0;\n            int  bestV = -1, bestU = -1, oldP = -1;\n\n            // try detaching **any** subtree of size \u2264 MAX_SUB\n            for(int v = 0; v < N; v++){\n                int p = bestParent[v];\n                if(p < 0) continue;\n                int sz = subSize[v];\n                if(sz > MAX_SUB) continue;\n                ll sm = subSumA[v];\n                int dv = bestDepth[v];\n                int md = subMaxD[v];\n                for(int u: adj[v]){\n                    // forbid cycles\n                    if(tin[u] >= tin[v] && tin[u] < tout[v]) continue;\n                    int du = bestDepth[u];\n                    if(du + 1 + md > H) continue;\n                    ll gain = ll(du - dv + 1) * sm;\n                    if(gain > bestGain){\n                        bestGain = gain;\n                        bestV     = v;\n                        bestU     = u;\n                        oldP      = p;\n                    }\n                }\n            }\n            if(bestGain <= 0) break;\n\n            // apply the best subtree\u2010move\n            auto &sib = children[oldP];\n            for(int i = 0; i < (int)sib.size(); i++){\n                if(sib[i] == bestV){\n                    sib[i] = sib.back();\n                    sib.pop_back();\n                    break;\n                }\n            }\n            children[bestU].push_back(bestV);\n            bestParent[bestV] = bestU;\n\n            // fix depths & rootOf in that moved subtree\n            deque<int> dq2;\n            bestDepth[bestV] = bestDepth[bestU] + 1;\n            rootOf[bestV]    = rootOf[bestU];\n            dq2.push_back(bestV);\n            while(!dq2.empty()){\n                int x = dq2.front(); dq2.pop_front();\n                for(int c: children[x]){\n                    bestDepth[c] = bestDepth[x] + 1;\n                    rootOf[c]    = rootOf[bestV];\n                    dq2.push_back(c);\n                }\n            }\n        }\n    }\n\n    // ------------------------------------------------\n    // 4) Output\n    // ------------------------------------------------\n    for(int v = 0; v < N; v++){\n        cout << bestParent[v] << (v+1 == N ? '\\n' : ' ');\n    }\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\nusing ull = unsigned long long;\n\n// map directions to 0..3 and back\ninline int dir_code(char d) {\n    return (d=='L'?0:(d=='R'?1:(d=='U'?2:3)));\n}\ninline char code_dir(int c) {\n    return (c==0?'L': c==1?'R': c==2?'U':'D');\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<string> B(N);\n    for(int i = 0; i < N; i++){\n        cin >> B[i];\n    }\n\n    // 1) collect Oni positions\n    vector<pair<int,int>> oni_pos;\n    oni_pos.reserve(2*N);\n    vector<vector<int>> pos2id(N, vector<int>(N,-1));\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(B[i][j] == 'x'){\n                int id = (int)oni_pos.size();\n                oni_pos.emplace_back(i,j);\n                pos2id[i][j] = id;\n            }\n        }\n    }\n    int M = (int)oni_pos.size();  // should be 2N\n\n    // 2) for each row/col find the nearest Fukunokami\n    const int INF = 1<<20;\n    vector<int> row_min_o(N, INF), row_max_o(N, -INF);\n    vector<int> col_min_o(N, INF), col_max_o(N, -INF);\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            if(B[i][j] == 'o'){\n                row_min_o[i] = min(row_min_o[i], j);\n                row_max_o[i] = max(row_max_o[i], j);\n                col_min_o[j] = min(col_min_o[j], i);\n                col_max_o[j] = max(col_max_o[j], i);\n            }\n        }\n    }\n\n    // 3) build exactly one *minimal* segment per Oni per clear direction\n    struct Seg { char d; int idx, k, cost; vector<int> cover; };\n    vector<Seg> segs;\n    segs.reserve(M*4);\n    unordered_map<int,int> seg_map;\n    seg_map.reserve(M*4);\n\n    auto add_seg = [&](char d, int idx, int k){\n        int dc = dir_code(d);\n        // key = ((dc * N + idx)*(N+1)) + k\n        int key = ((dc * N + idx)*(N+1)) + k;\n        if(!seg_map.count(key)){\n            int s = (int)segs.size();\n            seg_map[key] = s;\n            segs.push_back({d, idx, k, 2*k, {}});\n        }\n    };\n\n    for(int id = 0; id < M; id++){\n        auto [r,c] = oni_pos[id];\n        if(row_min_o[r] > c)       add_seg('L', r, c+1);\n        if(row_max_o[r] < c)       add_seg('R', r, N-c);\n        if(col_min_o[c] > r)       add_seg('U', c, r+1);\n        if(col_max_o[c] < r)       add_seg('D', c, N-r);\n    }\n\n    int S = (int)segs.size();\n    // 4) build each segment's coverage list and 64-bit mask\n    vector<ull> segMask(S, 0);\n    for(int s = 0; s < S; s++){\n        auto &sg = segs[s];\n        if(sg.d=='L'){\n            int r = sg.idx;\n            for(int x = 0; x < sg.k; x++){\n                int id = pos2id[r][x];\n                if(id>=0){\n                    sg.cover.push_back(id);\n                    segMask[s] |= (1ULL<<id);\n                }\n            }\n        } else if(sg.d=='R'){\n            int r = sg.idx;\n            for(int x = N-sg.k; x < N; x++){\n                int id = pos2id[r][x];\n                if(id>=0){\n                    sg.cover.push_back(id);\n                    segMask[s] |= (1ULL<<id);\n                }\n            }\n        } else if(sg.d=='U'){\n            int c = sg.idx;\n            for(int x = 0; x < sg.k; x++){\n                int id = pos2id[x][c];\n                if(id>=0){\n                    sg.cover.push_back(id);\n                    segMask[s] |= (1ULL<<id);\n                }\n            }\n        } else { // 'D'\n            int c = sg.idx;\n            for(int x = N-sg.k; x < N; x++){\n                int id = pos2id[x][c];\n                if(id>=0){\n                    sg.cover.push_back(id);\n                    segMask[s] |= (1ULL<<id);\n                }\n            }\n        }\n    }\n\n    // 5) Precompute alternative cost-penalties\n    vector<double> costPow2(S), costPow03(S);\n    for(int s = 0; s < S; s++){\n        costPow2[s]  = sqrt((double)segs[s].cost);\n        costPow03[s] = pow((double)segs[s].cost, 0.3);\n    }\n\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    vector<char> used(S);\n    vector<int>  cov_cnt(M);\n    vector<double> randf(S);\n\n    int best_cost = INT_MAX;\n    vector<tuple<char,int,int>> best_one;\n\n    const int REPS = 2000;\n    // 5) randomized\u2010greedy + prune + merge (one\u2010per\u2010(dir,idx))\n    for(int rep = 0; rep < REPS; rep++){\n        // random perturbation\n        for(int s = 0; s < S; s++){\n            int r = int(rng()%1001);\n            randf[s] = 1.0 + (r - 500)/5000.0;\n        }\n        int mode = rep % 3;\n\n        fill(used.begin(), used.end(), 0);\n        ull covered = 0;\n        vector<int> pick;\n        pick.reserve(M);\n\n        // greedy cover\n        while(__builtin_popcountll(covered) < M){\n            double bestR = -1.0;\n            int bestS = -1;\n            ull need = ~covered;\n            for(int s = 0; s < S; s++){\n                if(used[s]) continue;\n                ull newMask = segMask[s] & need;\n                int nc = __builtin_popcountll(newMask);\n                if(nc==0) continue;\n                double denom = (mode==0 ? segs[s].cost\n                                : mode==1 ? costPow2[s]\n                                          : costPow03[s]);\n                double r = nc * randf[s] / denom;\n                if(r > bestR){\n                    bestR = r;\n                    bestS = s;\n                }\n            }\n            if(bestS < 0) break;\n            used[bestS] = 1;\n            covered |= segMask[bestS];\n            pick.push_back(bestS);\n        }\n        if(__builtin_popcountll(covered) < M) \n            continue;  // failed this rep\n\n        // prune fully-redundant\n        fill(cov_cnt.begin(), cov_cnt.end(), 0);\n        for(int s: pick){\n            for(int id: segs[s].cover)\n                cov_cnt[id]++;\n        }\n        vector<int> pruned;\n        pruned.reserve(pick.size());\n        for(int s: pick){\n            bool red = true;\n            for(int id: segs[s].cover){\n                if(cov_cnt[id] <= 1){\n                    red = false;\n                    break;\n                }\n            }\n            if(red){\n                for(int id: segs[s].cover)\n                    cov_cnt[id]--;\n            } else {\n                pruned.push_back(s);\n            }\n        }\n\n        // merge \u2192 one segment per (dir,idx)\n        vector<int> bestk(4*N, 0);\n        for(int s: pruned){\n            int key = dir_code(segs[s].d)*N + segs[s].idx;\n            bestk[key] = max(bestk[key], segs[s].k);\n        }\n        int cost = 0;\n        vector<tuple<char,int,int>> one;\n        one.reserve(pruned.size());\n        for(int key = 0; key < 4*N; key++){\n            int k = bestk[key];\n            if(k > 0){\n                cost += 2*k;\n                one.emplace_back(code_dir(key/N), key%N, k);\n            }\n        }\n        if(cost < best_cost){\n            best_cost = cost;\n            best_one   = move(one);\n        }\n    }\n\n    // 6) build candidate lists for shrinking\n    vector<vector<pair<int,ull>>> cand(4*N);\n    cand.reserve(4*N);\n    for(int s = 0; s < S; s++){\n        int key = dir_code(segs[s].d)*N + segs[s].idx;\n        cand[key].emplace_back(segs[s].k, segMask[s]);\n    }\n    for(int key = 0; key < 4*N; key++){\n        // sort ascending by k so we try the smallest k first\n        sort(cand[key].begin(), cand[key].end(),\n             [](auto &a, auto &b){ return a.first < b.first; });\n    }\n\n    // 7) initial shrink of best_one \u2192 bestk\n    vector<int> bestk(4*N,0);\n    {\n        ull unionAll = 0;\n        for(auto &t: best_one){\n            char d; int idx,k;\n            tie(d,idx,k) = t;\n            int key = dir_code(d)*N + idx;\n            bestk[key] = k;\n            int mapkey = key*(N+1) + k;\n            int s = seg_map[mapkey];\n            unionAll |= segMask[s];\n        }\n        bool changed = true;\n        while(changed){\n            changed = false;\n            // for each active segment try to shrink\n            for(int key = 0; key < 4*N; key++){\n                int oldk = bestk[key];\n                if(oldk <= 0) continue;\n                // build coverage excluding this segment\n                ull covEx = 0;\n                for(int k2 = 0; k2 < 4*N; k2++){\n                    int kk = bestk[k2];\n                    if(kk > 0 && k2 != key){\n                        int mk = seg_map[k2*(N+1) + kk];\n                        covEx |= segMask[mk];\n                    }\n                }\n                // try any smaller k\n                for(auto &pr: cand[key]){\n                    int kk = pr.first;\n                    ull  mk = pr.second;\n                    if(kk >= oldk) continue;\n                    ull test = covEx | mk;\n                    if((int)__builtin_popcountll(test) == M){\n                        bestk[key] = kk;\n                        unionAll    = test;\n                        changed     = true;\n                        break;\n                    }\n                }\n                if(changed) break;\n            }\n        }\n    }\n\n    // 8) now bestk[] and best_cost\n    best_cost = 0;\n    for(int key = 0; key < 4*N; key++){\n        if(bestk[key] > 0) best_cost += 2*bestk[key];\n    }\n\n    // 9) k-opt Local Search: drop 1\u20132 segments, refill, prune, merge, shrink\n    const int LS_ITERS = 200;\n    for(int it = 0; it < LS_ITERS; it++){\n        // collect active keys\n        vector<int> active;\n        active.reserve(4*N);\n        for(int key = 0; key < 4*N; key++){\n            if(bestk[key] > 0) active.push_back(key);\n        }\n        if(active.empty()) break;\n\n        // drop 1 or 2\n        int drop_cnt = (active.size() > 1 && (rng()%100)<30) ? 2 : 1;\n        shuffle(active.begin(), active.end(), rng);\n        vector<int> curk = bestk;\n        for(int i = 0; i < drop_cnt; i++){\n            curk[active[i]] = 0;\n        }\n\n        // coverage of the remaining\n        ull covered = 0;\n        for(int key = 0; key < 4*N; key++){\n            int k = curk[key];\n            if(k > 0){\n                int s = seg_map[key*(N+1) + k];\n                covered |= segMask[s];\n            }\n        }\n\n        vector<char> used2(S,0);\n        // greedy refill missing Oni\n        while(__builtin_popcountll(covered) < M){\n            double bestR = -1.0;\n            int bestS = -1;\n            ull need = ~covered;\n            for(int s = 0; s < S; s++){\n                if(used2[s]) continue;\n                ull nm = segMask[s] & need;\n                int nc = __builtin_popcountll(nm);\n                if(nc==0) continue;\n                double r = double(nc) / segs[s].cost;\n                if(r > bestR){\n                    bestR = r;\n                    bestS = s;\n                }\n            }\n            if(bestS < 0) break;\n            used2[bestS] = 1;\n            covered |= segMask[bestS];\n            int key = dir_code(segs[bestS].d)*N + segs[bestS].idx;\n            curk[key] = max(curk[key], segs[bestS].k);\n        }\n        if(__builtin_popcountll(covered) < M) \n            continue;  // couldn't refill\n\n        // prune fully\u2010redundant\n        fill(cov_cnt.begin(), cov_cnt.end(), 0);\n        for(int key = 0; key < 4*N; key++){\n            int k = curk[key];\n            if(k>0){\n                int s = seg_map[key*(N+1) + k];\n                for(int id: segs[s].cover) cov_cnt[id]++;\n            }\n        }\n        vector<int> kept;\n        for(int key = 0; key < 4*N; key++){\n            int k = curk[key];\n            if(k>0){\n                int s = seg_map[key*(N+1) + k];\n                bool red = true;\n                for(int id: segs[s].cover){\n                    if(cov_cnt[id] <= 1){\n                        red = false;\n                        break;\n                    }\n                }\n                if(red){\n                    for(int id: segs[s].cover) cov_cnt[id]--;\n                } else {\n                    kept.push_back(key);\n                }\n            }\n        }\n        // merge\n        vector<int> newk(4*N,0);\n        for(int key: kept){\n            newk[key] = curk[key];\n        }\n        // shrink newk\n        {\n            ull unionAll = 0;\n            for(int key = 0; key < 4*N; key++){\n                int k = newk[key];\n                if(k>0){\n                    int s = seg_map[key*(N+1) + k];\n                    unionAll |= segMask[s];\n                }\n            }\n            bool changed = true;\n            while(changed){\n                changed = false;\n                for(int key = 0; key < 4*N; key++){\n                    int oldk = newk[key];\n                    if(oldk <= 0) continue;\n                    // build coverage excluding this\n                    ull covEx = 0;\n                    for(int k2 = 0; k2 < 4*N; k2++){\n                        int kk = newk[k2];\n                        if(kk>0 && k2!=key){\n                            int s2 = seg_map[k2*(N+1)+kk];\n                            covEx |= segMask[s2];\n                        }\n                    }\n                    // try smaller k\n                    for(auto &pr: cand[key]){\n                        int kk = pr.first;\n                        ull mk = pr.second;\n                        if(kk >= oldk) continue;\n                        ull test = covEx | mk;\n                        if((int)__builtin_popcountll(test) == M){\n                            newk[key] = kk;\n                            unionAll    = test;\n                            changed     = true;\n                            break;\n                        }\n                    }\n                    if(changed) break;\n                }\n            }\n        }\n\n        // evaluate\n        int newCost = 0;\n        for(int key = 0; key < 4*N; key++){\n            if(newk[key] > 0) newCost += 2*newk[key];\n        }\n        if(newCost < best_cost){\n            best_cost = newCost;\n            bestk     = move(newk);\n        }\n    }\n\n    // 10) finally emit all shifts\n    auto opposite = [&](char d){\n        if(d=='L') return 'R';\n        if(d=='R') return 'L';\n        if(d=='U') return 'D';\n        return 'U';\n    };\n    vector<pair<char,int>> ops;\n    ops.reserve(best_cost);\n    for(int key = 0; key < 4*N; key++){\n        int k = bestk[key];\n        if(k>0){\n            char d   = code_dir(key/N);\n            int idx  = key%N;\n            for(int i=0;i<k;i++) ops.emplace_back(d, idx);\n            char od = opposite(d);\n            for(int i=0;i<k;i++) ops.emplace_back(od, idx);\n        }\n    }\n    // print\n    for(auto &p: ops){\n        cout << p.first << \" \" << p.second << \"\\n\";\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    long long L;\n    cin >> N >> L;\n    vector<long long> T(N);\n    for(int i = 0; i < N; i++){\n        cin >> T[i];\n    }\n\n    // Baseline: one big cycle of length N.\n    // We set a[i] = b[i] = (i+1)%N so that the walker cycles\n    // around 0\u21921\u21922\u2192...\u2192N-1\u21920\u2192...\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;\nusing ll = long long;\n\n// Hilbert\u2010curve mapping of (x,y) in [0,2^bits)\n// into a 2*bits\u2010bit key.  Improves spatial locality.\nstatic inline uint64_t hilbertOrder(int x, int y, int bits = 14) {\n    uint64_t d = 0;\n    for(int s = bits - 1; s >= 0; s--) {\n        uint64_t rx = (x >> s) & 1;\n        uint64_t ry = (y >> s) & 1;\n        d = (d << 2) | ((rx << 1) | (rx ^ ry));\n        if(ry == 0) {\n            if(rx == 1) {\n                x = ((1<<bits) - 1) ^ x;\n                y = ((1<<bits) - 1) ^ y;\n            }\n            std::swap(x, y);\n        }\n    }\n    return d;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for(int i = 0; i < M; i++) cin >> G[i];\n    vector<int> lx(N), rx(N), ly(N), ry(N);\n    for(int i = 0; i < N; i++){\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n\n    // 1) Compute centers (integers in [0..10000]) for ordering\n    vector<int> cx(N), cy(N);\n    for(int i = 0; i < N; i++){\n        cx[i] = (lx[i] + rx[i]) >> 1;\n        cy[i] = (ly[i] + ry[i]) >> 1;\n    }\n\n    // 2) Sort all cities by their Hilbert\u2010curve key\n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    vector<uint64_t> key(N);\n    for(int i = 0; i < N; i++){\n        key[i] = hilbertOrder(cx[i], cy[i], 14);\n    }\n    sort(idx.begin(), idx.end(), [&](int a, int b){\n        return key[a] < key[b];\n    });\n\n    // 3) Slice into the prescribed group\u2010sizes G[0],G[1],...\n    vector<vector<int>> groups(M);\n    {\n        int p = 0;\n        for(int k = 0; k < M; k++){\n            groups[k].reserve(G[k]);\n            for(int t = 0; t < G[k]; t++){\n                groups[k].push_back(idx[p++]);\n            }\n        }\n    }\n\n    // Collect the final edges here:\n    vector<vector<pair<int,int>>> answer_edges(M);\n    int remQ = Q;\n\n    // A simple Prim fallback in case we ever run out of queries.\n    auto prim_on_centers = [&](int k){\n        auto &g = groups[k];\n        int K = (int)g.size();\n        if(K <= 1) return;\n        vector<bool> in_mst(K,false);\n        vector<double> dist(K,1e18);\n        vector<int> par(K,-1);\n        dist[0] = 0;\n        for(int it=0; it<K; it++){\n            int u=-1; double best=1e18;\n            for(int i=0;i<K;i++){\n                if(!in_mst[i] && dist[i]<best){\n                    best=dist[i]; u=i;\n                }\n            }\n            in_mst[u]=true;\n            if(par[u]!=-1){\n                answer_edges[k].emplace_back(g[u], g[par[u]]);\n            }\n            for(int v=0;v<K;v++){\n                if(in_mst[v]) continue;\n                double dx = cx[g[u]] - cx[g[v]];\n                double dy = cy[g[u]] - cy[g[v]];\n                double d = floor(sqrt(dx*dx + dy*dy));\n                if(d < dist[v]){\n                    dist[v]=d;\n                    par[v]=u;\n                }\n            }\n        }\n    };\n\n    // 4) For each group, either query windows or fallback\n    for(int k = 0; k < M; k++){\n        auto &g = groups[k];\n        int K = (int)g.size();\n        if(K <= 1) continue;\n\n        // how many queries we need\n        int need = (K <= L\n                    ? 1\n                    : ( (K + L - 3) / (L - 1) )  // ceil((K-1)/(L-1)) = (K+L-3)/(L-1)\n                   );\n        if(remQ >= need){\n            int step = L - 1;\n            // issue exactly 'need' windows\n            for(int j = 0; j < need; j++){\n                int start = j * step;\n                int end = min(start + L, K);\n                int sz = end - start;  // guaranteed >= 2\n                cout << \"? \" << sz;\n                for(int t = start; t < end; t++){\n                    cout << ' ' << g[t];\n                }\n                cout << \"\\n\" << flush;\n                remQ--;\n\n                // read sz-1 edges\n                for(int e = 0; e < sz - 1; e++){\n                    int a, b;\n                    cin >> a >> b;\n                    answer_edges[k].emplace_back(a, b);\n                }\n            }\n        } else {\n            // fallback to approximate MST\n            prim_on_centers(k);\n        }\n    }\n\n    // 5) Output the final solution\n    cout << \"!\\n\";\n    for(int k = 0; k < M; k++){\n        // cities in group k\n        for(int i = 0; i < (int)groups[k].size(); i++){\n            if(i) cout << ' ';\n            cout << groups[k][i];\n        }\n        cout << \"\\n\";\n        // the (G[k] - 1) edges\n        for(auto &e : answer_edges[k]){\n            cout << e.first << \" \" << e.second << \"\\n\";\n        }\n    }\n    cout << flush;\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    cin >> N >> M;\n    vector<pair<int,int>> pts(M);\n    for(int i = 0; i < M; i++){\n        cin >> pts[i].first >> pts[i].second;\n    }\n    int ci = pts[0].first, cj = pts[0].second;\n    vector<pair<char,char>> ans;\n    const int INF = 1e9;\n\n    for(int k = 1; k < M; k++){\n        int ti = pts[k].first;\n        int tj = pts[k].second;\n        int di = ti - ci;\n        int dj = tj - cj;\n        int costVM = abs(di);\n        int costHM = abs(dj);\n        int costVS = INF, costHS = INF;\n\n        // cost of sliding vertically via boundary then back\n        if(di > 0){\n            // slide down to row N-1, then move up to ti\n            costVS = 1 + ((N-1) - ti);\n        } else if(di < 0){\n            // slide up to row 0, then move down to ti\n            costVS = 1 + ti;\n        }\n        // cost of sliding horizontally via boundary then back\n        if(dj > 0){\n            // slide right to col N-1, then move left to tj\n            costHS = 1 + ((N-1) - tj);\n        } else if(dj < 0){\n            // slide left to col 0, then move right to tj\n            costHS = 1 + tj;\n        }\n\n        bool useV = costVS < costVM;\n        bool useH = costHS < costHM;\n\n        // First do horizontal phase\n        if(useH){\n            if(dj > 0){\n                ans.emplace_back('S','R');\n                int moves = (N-1) - tj;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','L');\n                }\n            } else {\n                // dj<0\n                ans.emplace_back('S','L');\n                int moves = tj;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','R');\n                }\n            }\n            cj = tj;\n        } else {\n            // simple moves\n            if(dj > 0){\n                for(int t = 0; t < dj; t++){\n                    ans.emplace_back('M','R');\n                }\n            } else if(dj < 0){\n                for(int t = 0; t < -dj; t++){\n                    ans.emplace_back('M','L');\n                }\n            }\n            cj = tj;\n        }\n\n        // Then do vertical phase\n        if(useV){\n            if(di > 0){\n                ans.emplace_back('S','D');\n                int moves = (N-1) - ti;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','U');\n                }\n            } else {\n                // di<0\n                ans.emplace_back('S','U');\n                int moves = ti;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','D');\n                }\n            }\n            ci = ti;\n        } else {\n            // simple moves\n            if(di > 0){\n                for(int t = 0; t < di; t++){\n                    ans.emplace_back('M','D');\n                }\n            } else if(di < 0){\n                for(int t = 0; t < -di; t++){\n                    ans.emplace_back('M','U');\n                }\n            }\n            ci = ti;\n        }\n    }\n\n    // Output all actions\n    for(auto &ac : ans){\n        cout << ac.first << \" \" << ac.second << \"\\n\";\n    }\n    return 0;\n}"},"16":{"ahc001":"#include <bits/stdc++.h>\n#include <chrono>\nusing namespace std;\n\n// A half\u2010open free rectangle [x1,x2)\u00d7[y1,y2)\nstruct Rect { int x1,y1,x2,y2; };\n\n// If a and b share a full edge, merge them into o and return true.\ninline bool canMerge(const Rect &a, const Rect &b, Rect &o) {\n    // vertical\n    if(a.x1==b.x1 && a.x2==b.x2) {\n        if(a.y2==b.y1){ o={a.x1,a.y1,a.x2,b.y2}; return true; }\n        if(b.y2==a.y1){ o={a.x1,b.y1,a.x2,a.y2}; return true; }\n    }\n    // horizontal\n    if(a.y1==b.y1 && a.y2==b.y2) {\n        if(a.x2==b.x1){ o={a.x1,a.y1,b.x2,a.y2}; return true; }\n        if(b.x2==a.x1){ o={b.x1,a.y1,a.x2,a.y2}; return true; }\n    }\n    return false;\n}\n\n// Morton\u2010(Z\u2010)order key for (x,y) with up to 14 bits each (0..9999)\nstatic inline uint32_t mortonKey(int x, int y) {\n    uint32_t m=0;\n    for(int i=0;i<14;i++){\n        m |= ((x>>i)&1u) << (2*i+1);\n        m |= ((y>>i)&1u) << (2*i);\n    }\n    return m;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n; \n    cin>>n;\n    vector<int> x(n), y(n);\n    vector<long long> r(n);\n    for(int i=0;i<n;i++){\n        cin>>x[i]>>y[i]>>r[i];\n    }\n\n    // 1) Build a richer list of (w,h) \u2248 sqrt(r_i) with \u00b11,\u00b12 perturbations:\n    vector<vector<pair<int,int>>> dims0(n);\n    for(int i=0;i<n;i++){\n        long long ri=r[i];\n        int w0=int(floor(sqrt((long double)ri)));\n        while(1LL*w0*w0>ri) --w0;\n        while(1LL*(w0+1)*(w0+1)<=ri) ++w0;\n        w0 = max(1, min(w0,10000));\n        int h0 = int((ri + w0 - 1)/w0);\n        if(h0>10000){\n            h0=10000;\n            w0=int((ri+h0-1)/h0);\n        }\n        auto &D=dims0[i];\n        // core\n        D.emplace_back(w0,h0);\n        if(h0!=w0) D.emplace_back(h0,w0);\n        // square\n        D.emplace_back(w0,w0);\n        // \u00b11,\u00b12 in w\n        for(int d=-2;d<=2;d++){\n            if(d==0) continue;\n            int w=w0+d;\n            if(w<1||w>10000) continue;\n            int h=int((ri+w-1)/w);\n            if(h>10000) continue;\n            D.emplace_back(w,h);\n        }\n        // \u00b11,\u00b12 in h\n        for(int d=-2;d<=2;d++){\n            if(d==0) continue;\n            int h=h0+d;\n            if(h<1||h>10000) continue;\n            int w=int((ri+h-1)/h);\n            if(w>10000) continue;\n            D.emplace_back(w,h);\n        }\n        sort(D.begin(), D.end());\n        D.erase(unique(D.begin(), D.end()), D.end());\n    }\n\n    // 2) Prepare base list and 10 static order\u2010variants (8 old + 2 Morton)\n    vector<int> base(n);\n    iota(base.begin(), base.end(), 0);\n    vector<vector<int>> orderVars;\n    orderVars.reserve(10);\n\n    // (a) r desc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){ return r[a]>r[b]; });\n        orderVars.push_back(o);\n    }\n    // (b) r desc, x asc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]>r[b];\n                 return x[a]<x[b];\n             });\n        orderVars.push_back(o);\n    }\n    // (c) r desc, y asc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]>r[b];\n                 return y[a]<y[b];\n             });\n        orderVars.push_back(o);\n    }\n    // (d) r desc, dist\u2192center asc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]>r[b];\n                 long long da=(x[a]-5000LL)*(x[a]-5000LL)\n                             +(y[a]-5000LL)*(y[a]-5000LL);\n                 long long db=(x[b]-5000LL)*(x[b]-5000LL)\n                             +(y[b]-5000LL)*(y[b]-5000LL);\n                 return da<db;\n             });\n        orderVars.push_back(o);\n    }\n    // (e) one random shuffle\n    {\n        auto o=base;\n        mt19937_64 tmp(7126871263ULL);\n        shuffle(o.begin(), o.end(), tmp);\n        orderVars.push_back(o);\n    }\n    // (f) r asc (small\u2010first)\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){ return r[a]<r[b]; });\n        orderVars.push_back(o);\n    }\n    // (g) r asc, x asc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]<r[b];\n                 return x[a]<x[b];\n             });\n        orderVars.push_back(o);\n    }\n    // (h) r asc, y asc\n    {\n        auto o=base;\n        sort(o.begin(), o.end(),\n             [&](int a,int b){\n                 if(r[a]!=r[b]) return r[a]<r[b];\n                 return y[a]<y[b];\n             });\n        orderVars.push_back(o);\n    }\n    // (i) Morton\u2010asc\n    {\n        vector<pair<uint32_t,int>> tmp;\n        tmp.reserve(n);\n        for(int i=0;i<n;i++) tmp.emplace_back(mortonKey(x[i],y[i]),i);\n        sort(tmp.begin(), tmp.end());\n        vector<int> o(n);\n        for(int i=0;i<n;i++) o[i]=tmp[i].second;\n        orderVars.push_back(o);\n    }\n    // (j) Morton\u2010desc\n    {\n        vector<pair<uint32_t,int>> tmp;\n        tmp.reserve(n);\n        for(int i=0;i<n;i++) tmp.emplace_back(mortonKey(x[i],y[i]),i);\n        sort(tmp.begin(), tmp.end(), greater<>());\n        vector<int> o(n);\n        for(int i=0;i<n;i++) o[i]=tmp[i].second;\n        orderVars.push_back(o);\n    }\n\n    int V = int(orderVars.size());\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_real_distribution<double> P2(0.0,0.30);\n    vector<double> pick2(V);\n    for(int i=0;i<V;i++) pick2[i]=P2(rng);\n\n    // workspace\n    vector<array<int,4>> bestAns(n), ans(n);\n    double bestScore=-1;\n    vector<Rect> freeRects;\n    freeRects.reserve(2000);\n\n    auto removeRect=[&](int i){\n        freeRects[i]=freeRects.back();\n        freeRects.pop_back();\n    };\n    auto addFree=[&](Rect R){\n        if(R.x1>=R.x2||R.y1>=R.y2) return;\n        bool again=true;\n        while(again){\n            again=false;\n            for(int i=0;i<(int)freeRects.size();i++){\n                Rect M;\n                if(canMerge(R, freeRects[i], M)){\n                    removeRect(i);\n                    R=M;\n                    again=true;\n                    break;\n                }\n            }\n        }\n        freeRects.push_back(R);\n    };\n\n    struct Cand{int ridx,w,h,L,Rg,D,U,waste,area;};\n    struct Fb {int j,w,h,L,Rg,D,U;};\n\n    // Single greedy+fallback pass\n    auto doRun = [&](const vector<int> &order, double p2){\n        freeRects.clear();\n        freeRects.push_back({0,0,10000,10000});\n        for(int idx: order){\n            long long ri=r[idx];\n            int xi=x[idx], yi=y[idx];\n            // collect guillotine fits\n            vector<Cand> cands;\n            cands.reserve(dims0[idx].size()*freeRects.size());\n            for(auto &wh: dims0[idx]){\n                int w=wh.first, h=wh.second;\n                for(int j=0;j<(int)freeRects.size();j++){\n                    auto &F=freeRects[j];\n                    int Rw=F.x2-F.x1, Rh=F.y2-F.y1;\n                    if(Rw<w||Rh<h) continue;\n                    int L=max(F.x1, xi-w+1), Rg=min(xi, F.x2-w);\n                    if(L>Rg) continue;\n                    int D=max(F.y1, yi-h+1), U=min(yi, F.y2-h);\n                    if(D>U) continue;\n                    int A=Rw*Rh;\n                    cands.push_back({j,w,h,L,Rg,D,U,A - w*h, A});\n                }\n            }\n            if(!cands.empty()){\n                // pick best & 2nd-best by (waste,area)\n                int b0=0, b1=-1;\n                int w0=cands[0].waste, A0=cands[0].area;\n                for(int i=1;i<(int)cands.size();i++){\n                    int wi=cands[i].waste, Ai=cands[i].area;\n                    if(wi<w0 || (wi==w0 && Ai<A0)){\n                        b1=b0; b0=i; w0=wi; A0=Ai;\n                    } else if(b1<0){\n                        b1=i;\n                    } else {\n                        int w1=cands[b1].waste, A1=cands[b1].area;\n                        if(wi<w1 || (wi==w1 && Ai<A1)){\n                            b1=i;\n                        }\n                    }\n                }\n                int pick=b0;\n                if(b1>=0 && (rng()%10000)<int(p2*10000.0)) pick=b1;\n                auto &c=cands[pick];\n                int a0=xi - c.w/2; a0=min(max(a0,c.L),c.Rg);\n                int b0y=yi - c.h/2; b0y=min(max(b0y,c.D),c.U);\n                ans[idx]={a0,b0y,a0+c.w,b0y+c.h};\n                // carve it out\n                Rect F=freeRects[c.ridx];\n                removeRect(c.ridx);\n                addFree({F.x1,      F.y1,    a0,       F.y2});\n                addFree({a0+c.w,    F.y1,    F.x2,     F.y2});\n                addFree({a0,        F.y1,    a0+c.w,   b0y});\n                addFree({a0,        b0y+c.h, a0+c.w,   F.y2});\n            } else {\n                // improved 1D fallback\n                double bestR=-1;\n                Fb bestFb{};\n                for(int j=0;j<(int)freeRects.size();j++){\n                    auto &F=freeRects[j];\n                    if(!(F.x1<=xi&&xi<F.x2&&F.y1<=yi&&yi<F.y2))\n                        continue;\n                    int Rw=F.x2-F.x1, Rh=F.y2-F.y1;\n                    // vary width\n                    if(Rh>0){\n                        for(int t=-1;t<=1;t+=2){\n                            long long w = (t<0? ri/Rh : (ri+Rh-1)/Rh);\n                            if(w<1||w>Rw) continue;\n                            int W=int(w), H=Rh;\n                            int L0=max(F.x1, xi-W+1), Rg0=min(xi, F.x2-W);\n                            int D0=max(F.y1, yi-H+1), U0=min(yi, F.y2-H);\n                            if(L0>Rg0||D0>U0) continue;\n                            double rat = (t<0? double(W*1LL*H)/ri : double(ri)/double(W*1LL*H));\n                            if(rat>bestR){\n                                bestR=rat;\n                                bestFb={j,W,H,L0,Rg0,D0,U0};\n                            }\n                        }\n                    }\n                    // vary height\n                    if(Rw>0){\n                        for(int t=-1;t<=1;t+=2){\n                            long long h = (t<0? ri/Rw : (ri+Rw-1)/Rw);\n                            if(h<1||h>Rh) continue;\n                            int W=Rw, H=int(h);\n                            int L0=max(F.x1, xi-W+1), Rg0=min(xi, F.x2-W);\n                            int D0=max(F.y1, yi-H+1), U0=min(yi, F.y2-H);\n                            if(L0>Rg0||D0>U0) continue;\n                            double rat = (t<0? double(W*1LL*H)/ri : double(ri)/double(W*1LL*H));\n                            if(rat>bestR){\n                                bestR=rat;\n                                bestFb={j,W,H,L0,Rg0,D0,U0};\n                            }\n                        }\n                    }\n                }\n                if(bestR>0){\n                    int j=bestFb.j, W=bestFb.w, H=bestFb.h;\n                    int a0=xi-W/2;  a0=min(max(a0,bestFb.L),bestFb.Rg);\n                    int b0y=yi-H/2; b0y=min(max(b0y,bestFb.D),bestFb.U);\n                    ans[idx]={a0,b0y,a0+W,b0y+H};\n                    Rect F=freeRects[j];\n                    removeRect(j);\n                    addFree({F.x1,      F.y1,    a0,       F.y2});\n                    addFree({a0+W,      F.y1,    F.x2,     F.y2});\n                    addFree({a0,        F.y1,    a0+W,     b0y});\n                    addFree({a0,        b0y+H,   a0+W,     F.y2});\n                } else {\n                    // final 1\u00d71\n                    Rect F=freeRects.back();\n                    removeRect((int)freeRects.size()-1);\n                    int a0=F.x1, b0y=F.y1;\n                    ans[idx]={a0,b0y,a0+1,b0y+1};\n                    addFree({F.x1,      F.y1,    a0,       F.y2});\n                    addFree({a0+1,      F.y1,    F.x2,     F.y2});\n                    addFree({a0,        F.y1,    a0+1,     b0y});\n                    addFree({a0,        b0y+1,   a0+1,     F.y2});\n                }\n            }\n        }\n        // evaluate\n        double S=0;\n        for(int i=0;i<n;i++){\n            auto &rc=ans[i];\n            if(rc[0]<=x[i]&&x[i]<rc[2]&&rc[1]<=y[i]&&y[i]<rc[3]){\n                long long si=1LL*(rc[2]-rc[0])*(rc[3]-rc[1]);\n                double rt=double(min(r[i],si))/double(max(r[i],si));\n                S += 1.0 - (1.0-rt)*(1.0-rt);\n            }\n        }\n        if(S>bestScore){\n            bestScore=S;\n            bestAns=ans;\n        }\n    };\n\n    // 3) static runs\n    for(int i=0;i<V;i++){\n        doRun(orderVars[i], pick2[i]);\n    }\n    // 4) random\u2010shuffle restarts up to ~4.8\u2009s\n    auto t0=chrono::steady_clock::now();\n    auto TL=chrono::milliseconds(4800);\n    while(chrono::steady_clock::now() - t0 < TL){\n        auto ord=base;\n        shuffle(ord.begin(), ord.end(), rng);\n        doRun(ord, P2(rng));\n    }\n    // 5) output best\n    for(int i=0;i<n;i++){\n        auto &a=bestAns[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\nstatic constexpr int H = 50, W = 50;\nstatic constexpr int DX[4] = {-1,1,0,0};\nstatic constexpr int DY[4] = {0,0,-1,1};\nstatic constexpr char DC[4] = {'U','D','L','R'};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int si, sj;\n    cin >> si >> sj;\n    static int tile[H][W], pval[H][W];\n    int maxT = 0;\n    for(int i=0;i<H;i++) for(int j=0;j<W;j++){\n        cin >> tile[i][j];\n        maxT = max(maxT, tile[i][j]);\n    }\n    for(int i=0;i<H;i++) for(int j=0;j<W;j++){\n        cin >> pval[i][j];\n    }\n\n    const int M   = maxT + 1;  // # tiles\n    const int TOT = M;          // max steps\n\n    // visited\u2010stamp trick\n    vector<int> visited(M, 0);\n    int stamp = 1;\n\n    // RNG\n    uint64_t seed = chrono::high_resolution_clock::now()\n                        .time_since_epoch().count();\n    mt19937_64 rng(seed ^ (seed<<13));\n\n    // best\u2010found\n    vector<char> bestPath;\n    long long    bestScore = -1;\n    int bestWD = 10000, bestWP = 10000; // for hyper\u2010annealing\n\n    vector<char> curPath;\n    curPath.reserve(TOT);\n\n    // timing\n    auto T0 = chrono::steady_clock::now();\n    constexpr double TIME_LIMIT = 1.85;\n\n    // cycle parameters\n    const int CYCLE   = 120;\n    const int EXT_BEG = 3, EXT_END = 10;   // 3..9 prefix\u2010extension\n    const int RAND_MODE = 10;              // 10 = pure random\n    const int MINVAL_MODE = 11;            // 11 = min\u2010p sweep\n    const int MAXDEG_MODE = 12;            // 12 = max\u2010deg sweep\n\n    double elapsed = 0;\n    for(int iter = 0; ; iter++){\n        if((iter & 31)==0){\n            elapsed = chrono::duration<double>(chrono::steady_clock::now() - T0).count();\n            if(elapsed > TIME_LIMIT) break;\n        }\n\n        int mode = iter % CYCLE;\n        bool isStatic  = (mode==0 || mode==1 || mode==2 || mode==MINVAL_MODE || mode==MAXDEG_MODE);\n        bool isExtend  = (!isStatic) && !bestPath.empty() && (mode>=EXT_BEG && mode<EXT_END);\n        bool isRandom  = (mode == RAND_MODE);\n        bool dynMix    = (!isStatic && !isRandom);\n\n        int WD=0, WP=0;\n        if(isStatic){\n            // 0=Warnsdorff(min\u2010deg), 1=max\u2010val, 2=balanced,\n            // 11=min\u2010val, 12=max\u2010deg\n            if(mode==1){        WD =    0; WP = 20000; }\n            else if(mode==2){   WD =10000; WP = 10000; }\n            else if(mode==MINVAL_MODE){\n                                WD =    0; WP =-20000; }\n            else if(mode==MAXDEG_MODE){\n                                WD = 20000; WP =    0; }\n            // mode==0 => handled by Warnsdorff branch\n        } else if(dynMix){\n            // dynamic\u2010explore\u2192exploit or extension\n            if(elapsed < TIME_LIMIT*0.5){\n                WD = int(rng() % 20001);\n                WP = int(rng() % 20001);\n            } else {\n                int off = int(20000 * (1.0 - elapsed/TIME_LIMIT) + 0.5);\n                if(off<0) off=0;\n                WD = bestWD; WP = bestWP;\n                if(off){\n                    WD += int(rng()%(2*off+1)) - off;\n                    WP += int(rng()%(2*off+1)) - off;\n                    WD = clamp(WD,0,20000);\n                    WP = clamp(WP,0,20000);\n                }\n            }\n        }\n        // pure\u2010random has no WD/WP\n\n        // start run\n        int runStamp = stamp++;\n        curPath.clear();\n        long long curScore = 0;\n        int ci = si, cj = sj, steps = 0;\n\n        // mark start\n        visited[ tile[ci][cj] ] = runStamp;\n        curScore = pval[ci][cj];\n\n        // prefix\u2010extension\n        if(isExtend){\n            int Lmax = (int)bestPath.size();\n            int a = int(rng()%Lmax), b = int(rng()%Lmax);\n            int L = min(a,b);\n            for(int i=0;i<L;i++){\n                char d = bestPath[i];\n                int dir = (d=='U'?0: d=='D'?1: d=='L'?2:3);\n                ci += DX[dir]; cj += DY[dir];\n                curPath.push_back(d);\n                if(visited[ tile[ci][cj] ] != runStamp){\n                    visited[ tile[ci][cj] ] = runStamp;\n                    curScore += pval[ci][cj];\n                }\n            }\n            steps = L;\n        }\n\n        // pure\u2010random walk\n        if(isRandom){\n            while(true){\n                int cand[4], csz=0;\n                for(int d=0; d<4; d++){\n                    int ti=ci+DX[d], tj=cj+DY[d];\n                    if(ti<0||ti>=H||tj<0||tj>=W) continue;\n                    if(visited[ tile[ti][tj] ]==runStamp) continue;\n                    cand[csz++] = d;\n                }\n                if(csz==0) break;\n                int d = cand[rng()%csz];\n                ci += DX[d]; cj += DY[d];\n                visited[ tile[ci][cj] ] = runStamp;\n                curScore += pval[ci][cj];\n                curPath.push_back( DC[d] );\n            }\n            if(curScore > bestScore){\n                bestScore = curScore;\n                bestPath  = curPath;\n            }\n            continue;\n        }\n\n        // one\u2010step lookahead greedy\n        while(true){\n            long long bestW = LLONG_MIN;\n            int bestD = -1, ni=0, nj=0;\n            long long degScale=0, valScale=0;\n            if(dynMix){\n                degScale = 1LL * WD * (TOT - steps);\n                valScale = 1LL * WP * steps;\n            }\n\n            if(mode==0){\n                // multi\u2010level Warnsdorff (min\u2010deg)\n                int bd1=INT_MAX, bd2=INT_MAX;\n                for(int d=0; d<4; d++){\n                    int ti=ci+DX[d], tj=cj+DY[d];\n                    if(ti<0||ti>=H||tj<0||tj>=W) continue;\n                    int tid=tile[ti][tj];\n                    if(visited[tid]==runStamp) continue;\n                    int deg1=0, deg2=0;\n                    for(int d2=0;d2<4;d2++){\n                        int xi=ti+DX[d2], xj=tj+DY[d2];\n                        if(xi<0||xi>=H||xj<0||xj>=W) continue;\n                        if(visited[ tile[xi][xj] ]!=runStamp) deg1++;\n                    }\n                    for(int d2=0;d2<4;d2++){\n                        int xi=ti+DX[d2], xj=tj+DY[d2];\n                        if(xi<0||xi>=H||xj<0||xj>=W) continue;\n                        int tid2=tile[xi][xj];\n                        if(visited[tid2]==runStamp) continue;\n                        for(int d3=0;d3<4;d3++){\n                            int yi=xi+DX[d3], yj=xj+DY[d3];\n                            if(yi<0||yi>=H||yj<0||yj>=W) continue;\n                            if(visited[ tile[yi][yj] ]!=runStamp) deg2++;\n                        }\n                    }\n                    if(deg1<bd1 || (deg1==bd1 && deg2<bd2)){\n                        bd1=deg1; bd2=deg2;\n                        bestD=d; ni=ti; nj=tj;\n                    }\n                }\n            } else {\n                // static modes 1,2,11,12 or any dynMix\n                for(int d=0; d<4; d++){\n                    int ti=ci+DX[d], tj=cj+DY[d];\n                    if(ti<0||ti>=H||tj<0||tj>=W) continue;\n                    int tid=tile[ti][tj];\n                    if(visited[tid]==runStamp) continue;\n                    int deg=0;\n                    for(int d2=0;d2<4;d2++){\n                        int xi=ti+DX[d2], xj=tj+DY[d2];\n                        if(xi<0||xi>=H||xj<0||xj>=W) continue;\n                        if(visited[ tile[xi][xj] ]!=runStamp) deg++;\n                    }\n                    long long w;\n                    if(dynMix){\n                        w = deg*degScale + 1LL*pval[ti][tj]*valScale + (rng()&15);\n                    } else {\n                        w = 1LL*deg*WD + 1LL*pval[ti][tj]*WP;\n                    }\n                    if(w>bestW){\n                        bestW=w; bestD=d; ni=ti; nj=tj;\n                    }\n                }\n            }\n\n            if(bestD<0) break;\n            ci=ni; cj=nj; steps++;\n            visited[ tile[ci][cj] ] = runStamp;\n            curScore += pval[ci][cj];\n            curPath.push_back( DC[bestD] );\n        }\n\n        if(curScore > bestScore){\n            bestScore = curScore;\n            bestPath  = curPath;\n            if(dynMix){\n                bestWD = WD;\n                bestWP = WP;\n            }\n        }\n    }\n\n    // output\n    for(char c: bestPath) cout << c;\n    cout << \"\\n\";\n    return 0;\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nstatic constexpr int N = 30, V = N*N;\n// initial guess\nstatic constexpr double INITW = 5000.0;\n// decaying schedules\nstatic constexpr double ALPHA0    = 0.35;   // start learning\u2010rate\nstatic constexpr double ALPHA_MIN = 0.005;  // end learning\u2010rate\nstatic constexpr double EXPL0     = 400.0;  // start exploration bonus\nstatic constexpr double SM0       = 0.15;   // start smoothing\nstatic constexpr double SM1       = 0.005;  // end smoothing\n\nint dr[4]   = {-1, +1,  0,  0};\nint dc[4]   = { 0,  0, -1, +1};\nchar dch[4] = {'U','D','L','R'};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // Edge\u2010weight estimates and visit counts\n    static double w_h[N][N-1], w_v[N-1][N];\n    static int    cnt_h[N][N-1], cnt_v[N-1][N];\n    for(int i=0;i<N;i++)\n      for(int j=0;j<N-1;j++)\n        w_h[i][j]=INITW, cnt_h[i][j]=0;\n    for(int i=0;i<N-1;i++)\n      for(int j=0;j<N;j++)\n        w_v[i][j]=INITW, cnt_v[i][j]=0;\n\n    // Dijkstra scratch\n    static double distA[V];\n    static bool   done[V];\n    static int    prevN[V];\n    static char   prevD[V];\n\n    auto idx = [&](int r,int c){ return r*N + c; };\n\n    mt19937 rng(712687126);\n\n    for(int k=0;k<1000;k++){\n        int si,sj,ti,tj;\n        if(!(cin>>si>>sj>>ti>>tj)) break;\n\n        // progress fraction\n        double f = double(k)/999.0;\n        double alpha  = ALPHA0*(1-f) + ALPHA_MIN*f;\n        double expl   = EXPL0*(1-f);\n        double smooth = SM0*(1-f) + SM1*f;\n\n        // random neighbor order\n        array<int,4> dirs = {0,1,2,3};\n        shuffle(dirs.begin(), dirs.end(), rng);\n\n        // Dijkstra init\n        const double INF = 1e18;\n        for(int i=0;i<V;i++){\n            distA[i]=INF;\n            done[i]=false;\n        }\n        int S = idx(si,sj), T = idx(ti,tj);\n        distA[S]=0;\n        priority_queue<pair<double,int>,\n                       vector<pair<double,int>>,\n                       greater<pair<double,int>>> pq;\n        pq.push({0.0,S});\n\n        // Dijkstra with simple UCB\u2010style bonus\n        while(!pq.empty()){\n            auto [cd,u] = pq.top(); pq.pop();\n            if(done[u]) continue;\n            done[u]=true;\n            if(u==T) break;\n            int ur=u/N, uc=u%N;\n            for(int d:dirs){\n                int vr=ur+dr[d], vc=uc+dc[d];\n                if(vr<0||vr>=N||vc<0||vc>=N) continue;\n                double we, bonus;\n                if(d==0){\n                    we    = w_v[vr][vc];\n                    bonus = expl / sqrt(double(cnt_v[vr][vc] + 1));\n                } else if(d==1){\n                    we    = w_v[ur][uc];\n                    bonus = expl / sqrt(double(cnt_v[ur][uc] + 1));\n                } else if(d==2){\n                    we    = w_h[vr][vc];\n                    bonus = expl / sqrt(double(cnt_h[vr][vc] + 1));\n                } else {\n                    we    = w_h[ur][uc];\n                    bonus = expl / sqrt(double(cnt_h[ur][uc] + 1));\n                }\n                double cost = we - bonus;\n                if(cost < 1.0) cost = 1.0;\n                int v = idx(vr,vc);\n                double nd = cd + cost;\n                if(nd < distA[v]){\n                    distA[v]   = nd;\n                    prevN[v]   = u;\n                    prevD[v]   = dch[d];\n                    pq.push({nd,v});\n                }\n            }\n        }\n\n        // Reconstruct path\n        vector<char> rev;\n        for(int cur=T; cur!=S; cur=prevN[cur])\n            rev.push_back(prevD[cur]);\n        int L = rev.size();\n        string path; path.reserve(L);\n        for(int i=L-1;i>=0;i--) path.push_back(rev[i]);\n\n        // Output & flush\n        cout<<path<<\"\\n\"<<flush;\n\n        // Read noisy length\n        int b_obs; cin>>b_obs;\n\n        // Collect edges on path and predicted sum\n        struct E{ bool h; int r,c; };\n        vector<E> edges; edges.reserve(L);\n        double s_est=0;\n        int cr=si, cc=sj;\n        for(char mv: path){\n            if(mv=='U'){\n                edges.push_back({false,cr-1,cc});\n                s_est+= w_v[cr-1][cc];\n                cr--;\n            } else if(mv=='D'){\n                edges.push_back({false,cr,cc});\n                s_est+= w_v[cr][cc];\n                cr++;\n            } else if(mv=='L'){\n                edges.push_back({true,cr,cc-1});\n                s_est+= w_h[cr][cc-1];\n                cc--;\n            } else {\n                edges.push_back({true,cr,cc});\n                s_est+= w_h[cr][cc];\n                cc++;\n            }\n        }\n\n        // Weighted\u2010residual update + per\u2010edge \u221acnt LR\n        double err = double(b_obs) - s_est;\n        if(L>0 && fabs(err)>1e-9){\n            vector<bool> touch_row(N,false), touch_col(N,false);\n            for(auto &e: edges){\n                if(e.h){\n                    touch_row[e.r] = true;\n                    double &w = w_h[e.r][e.c];\n                    int    &ct=cnt_h[e.r][e.c];\n                    ++ct;\n                    double lr = alpha / sqrt(double(ct));\n                    w += w * (err/s_est) * lr;\n                    if(w<1.0) w=1.0;\n                } else {\n                    touch_col[e.c] = true;\n                    double &w = w_v[e.r][e.c];\n                    int    &ct=cnt_v[e.r][e.c];\n                    ++ct;\n                    double lr = alpha / sqrt(double(ct));\n                    w += w * (err/s_est) * lr;\n                    if(w<1.0) w=1.0;\n                }\n            }\n\n            // Dynamic per\u2010edge smoothing toward row/col mean\n            for(int i=0;i<N;i++){\n                if(touch_row[i]){\n                    double mu=0;\n                    for(int j=0;j<N-1;j++) mu += w_h[i][j];\n                    mu /= (N-1);\n                    for(int j=0;j<N-1;j++){\n                        double s_e = smooth / sqrt(double(cnt_h[i][j] + 1));\n                        if(s_e > smooth) s_e = smooth;\n                        w_h[i][j] = w_h[i][j] * (1 - s_e) + mu * s_e;\n                    }\n                }\n                if(touch_col[i]){\n                    double mu=0;\n                    for(int r=0;r<N-1;r++) mu += w_v[r][i];\n                    mu /= (N-1);\n                    for(int r=0;r<N-1;r++){\n                        double s_e = smooth / sqrt(double(cnt_v[r][i] + 1));\n                        if(s_e > smooth) s_e = smooth;\n                        w_v[r][i] = w_v[r][i] * (1 - s_e) + mu * s_e;\n                    }\n                }\n            }\n        }\n    }\n\n    return 0;\n}","ahc004":"#pragma GCC optimize(\"Ofast,unroll-loops\")\n#include <bits/stdc++.h>\nusing namespace std;\n\n// very fast xorshift RNG\nstatic uint64_t _rng = chrono::steady_clock::now().time_since_epoch().count();\ninline uint32_t rnd32() {\n    _rng ^= _rng << 13;\n    _rng ^= _rng >> 7;\n    _rng ^= _rng << 17;\n    return (uint32_t)_rng;\n}\ninline int randInt(int l, int r){ return l + int(rnd32() % (r - l + 1)); }\ninline double rand01(){ return (rnd32() & 0xFFFFFF) / double(1<<24); }\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    cin >> N >> M;\n    const int CELL = N * N;\n\n    vector<string> S(M);\n    for(int i = 0; i < M; i++) cin >> S[i];\n\n    // convert strings to 0..7\n    vector<vector<uint8_t>> sChars(M);\n    for(int i = 0; i < M; i++){\n        sChars[i].reserve(S[i].size());\n        for(char c: S[i]) sChars[i].push_back(uint8_t(c - 'A'));\n    }\n\n    // total #placements\n    int Pn = M * 2 * N * N;\n    vector<int> siOfPid(Pn), lenOfPid(Pn);\n\n    // count how many placements require letter d at cell c\n    vector<array<int,8>> cntCL(CELL);\n    for(int c = 0; c < CELL; c++) cntCL[c].fill(0);\n\n    int pid = 0;\n    for(int si = 0; si < M; si++){\n        int L = (int)sChars[si].size();\n        for(int dir = 0; dir < 2; dir++){\n            for(int x = 0; x < N; x++){\n                for(int st = 0; st < N; st++){\n                    siOfPid[pid]  = si;\n                    lenOfPid[pid] = L;\n                    auto &sc = sChars[si];\n                    for(int p = 0; p < L; p++){\n                        int i,j;\n                        if(dir == 0){\n                            i = x; j = (st + p) % N;\n                        } else {\n                            i = (st + p) % N; j = x;\n                        }\n                        cntCL[i*N + j][ sc[p] ]++;\n                    }\n                    pid++;\n                }\n            }\n        }\n    }\n\n    // build mids: for each (cell,letter) list all pids that need that letter here\n    vector<vector<int>> mids(CELL * 8);\n    for(int c = 0; c < CELL; c++){\n        for(int d = 0; d < 8; d++){\n            mids[c*8 + d].reserve(cntCL[c][d]);\n        }\n    }\n    // refill cntCL as cursor\n    for(int c = 0; c < CELL; c++) cntCL[c].fill(0);\n\n    pid = 0;\n    for(int si = 0; si < M; si++){\n        int L = (int)sChars[si].size();\n        for(int dir = 0; dir < 2; dir++){\n            for(int x = 0; x < N; x++){\n                for(int st = 0; st < N; st++){\n                    auto &sc = sChars[si];\n                    for(int p = 0; p < L; p++){\n                        int i,j;\n                        if(dir == 0){\n                            i = x; j = (st + p) % N;\n                        } else {\n                            i = (st + p) % N; j = x;\n                        }\n                        int idx = i*N + j;\n                        mids[idx*8 + sc[p]].push_back(pid);\n                    }\n                    pid++;\n                }\n            }\n        }\n    }\n\n    // full\u2010grid evaluator\n    vector<int> matchCnt(Pn), matchStr(M);\n    auto evalGrid = [&](const vector<uint8_t> &G)->int {\n        fill(matchCnt.begin(), matchCnt.end(), 0);\n        fill(matchStr.begin(), matchStr.end(), 0);\n        int covered = 0;\n        for(int c = 0; c < CELL; c++){\n            uint8_t d = G[c];\n            auto &v = mids[c*8 + d];\n            for(int pid: v){\n                int mc = ++matchCnt[pid];\n                if(mc == lenOfPid[pid]){\n                    int si = siOfPid[pid];\n                    if(matchStr[si]++ == 0) covered++;\n                }\n            }\n        }\n        return covered;\n    };\n\n    // greedy init by per\u2010cell frequency\n    vector<uint8_t> grid(CELL), bestGrid;\n    for(int c = 0; c < CELL; c++){\n        int best = 0;\n        for(int d = 1; d < 8; d++){\n            if(cntCL[c][d] > cntCL[c][best]) best = d;\n        }\n        grid[c] = uint8_t(best);\n    }\n    int curC  = evalGrid(grid);\n    bestGrid  = grid;\n    int bestC = curC;\n\n    // single\u2010cell SA, fixed iterations\n    const int    MAX_ITER = 200000;\n    const double T0       = 2.0;\n    const double T1       = 0.02;\n\n    // rollback buffers \u2014 sized safely to 50 000\n    static int   bufPid[50000];\n    static char  bufRem[50000];\n    int bufSz = 0;\n\n    for(int it = 0; it < MAX_ITER; it++){\n        int c0   = randInt(0, CELL-1);\n        uint8_t oldL = grid[c0];\n        int r    = randInt(0, 6);\n        uint8_t newL = uint8_t(r < oldL ? r : r+1);\n\n        // collect changes\n        bufSz  = 0;\n        int newC = curC;\n\n        // losing matches\n        auto &v0 = mids[c0*8 + oldL];\n        for(int pid: v0){\n            int mc = --matchCnt[pid];\n            if(mc+1 == lenOfPid[pid]){\n                int si = siOfPid[pid];\n                if(--matchStr[si] == 0) newC--;\n            }\n            bufPid[bufSz] = pid;\n            bufRem[bufSz] = 1;\n            bufSz++;\n        }\n        // gaining matches\n        auto &v1 = mids[c0*8 + newL];\n        for(int pid: v1){\n            int mc = ++matchCnt[pid];\n            if(mc == lenOfPid[pid]){\n                int si = siOfPid[pid];\n                if(matchStr[si]++ == 0) newC++;\n            }\n            bufPid[bufSz] = pid;\n            bufRem[bufSz] = 0;\n            bufSz++;\n        }\n\n        int delta = newC - curC;\n        // linear temperature schedule\n        double T = T0 + (T1 - T0) * (double)it / (double)MAX_ITER;\n        bool accept = (delta >= 0) || (rand01() < exp(delta / T));\n\n        if(accept){\n            grid[c0] = newL;\n            curC      = newC;\n            if(curC > bestC){\n                bestC    = curC;\n                bestGrid = grid;\n            }\n        } else {\n            // revert\n            for(int z = bufSz-1; z >= 0; z--){\n                int pid0 = bufPid[z];\n                bool rem = bufRem[z];\n                int L    = lenOfPid[pid0],\n                    si   = siOfPid[pid0];\n                if(rem){\n                    // we had done --matchCnt -> revert with ++\n                    int mc = ++matchCnt[pid0];\n                    if(mc == L){\n                        // placement becomes valid again\n                        matchStr[si]++;\n                    }\n                } else {\n                    // we had done ++matchCnt -> revert with --\n                    if(matchCnt[pid0] == L){\n                        // it was valid, now invalid\n                        matchStr[si]--;\n                    }\n                    matchCnt[pid0]--;\n                }\n            }\n        }\n    }\n\n    // output\n    for(int i = 0; i < N; i++){\n        for(int j = 0; j < N; j++){\n            cout << char('A' + bestGrid[i*N + j]);\n        }\n        cout << \"\\n\";\n    }\n    return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\n\n// fast direction\ninline char dirOf(int ui,int uj,int vi,int vj){\n  if(vi==ui-1) return 'U';\n  if(vi==ui+1) return 'D';\n  if(vj==uj-1) return 'L';\n  return 'R';\n}\nstruct Node{ int d,u; };\nstruct Cmp{ bool operator()(Node const &a, Node const &b) const {\n  return a.d > b.d;\n}};\n\nint main(){\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n\n  int N, si, sj;\n  cin >> N >> si >> sj;\n  vector<string> grid(N);\n  for(int i=0;i<N;i++) cin >> grid[i];\n\n  // 1) Flatten the grid\n  vector<int> id_map(N*N, -1);\n  vector<pair<int,int>> id2pos;\n  vector<int>        id2cost;\n  id2pos.reserve(N*N);\n  id2cost.reserve(N*N);\n  int R = 0;\n  for(int i=0;i<N;i++){\n    for(int j=0;j<N;j++){\n      if(grid[i][j]=='#') continue;\n      id_map[i*N+j] = R++;\n      id2pos.emplace_back(i,j);\n      id2cost.push_back(grid[i][j]-'0');\n    }\n  }\n  if(R==0){\n    cout << \"\\n\";\n    return 0;\n  }\n  int start = id_map[si*N + sj];\n\n  // 2) Build weighted 4-nbr graph for the grid-MST: w(u,v)=cost[u]+cost[v]\n  vector<vector<pair<int,int>>> graph(R);\n  static const int di[4]={-1,1,0,0}, dj[4]={0,0,-1,1};\n  for(int u=0;u<R;u++){\n    auto [ui,uj] = id2pos[u];\n    int cu = id2cost[u];\n    for(int d=0;d<4;d++){\n      int vi=ui+di[d], vj=uj+dj[d];\n      if(vi<0||vi>=N||vj<0||vj>=N) continue;\n      int v = id_map[vi*N+vj];\n      if(v<0) continue;\n      graph[u].emplace_back(v, cu + id2cost[v]);\n    }\n  }\n\n  // 3) Prim\u2019s MST on the full grid\n  const int INF = 1e9;\n  vector<int> key(R,INF), parent(R,-1), wMST(R,0);\n  vector<char> inM(R,0);\n  priority_queue<Node,vector<Node>,Cmp> pq;\n  key[start]=0; pq.push({0,start});\n  while(!pq.empty()){\n    auto [cd,u] = pq.top(); pq.pop();\n    if(inM[u]) continue;\n    inM[u]=1;\n    wMST[u]=cd;  // = key[u]\n    for(auto &e: graph[u]){\n      int v=e.first, w=e.second;\n      if(!inM[v] && w<key[v]){\n        key[v]=w;\n        parent[v]=u;\n        pq.push({w,v});\n      }\n    }\n  }\n\n  // 4) Build MST adjacency \u21d2 detect keep-nodes\n  vector<vector<pair<int,int>>> treeAdj(R);\n  for(int v=0; v<R; v++){\n    int u=parent[v];\n    if(u<0) continue;\n    int w = wMST[v];\n    treeAdj[u].emplace_back(v,w);\n    treeAdj[v].emplace_back(u,w);\n  }\n  vector<int> deg(R);\n  for(int u=0;u<R;u++) deg[u]=treeAdj[u].size();\n  vector<char> is_turn(R,0);\n  for(int u=0;u<R;u++){\n    if(deg[u]==2){\n      int a=treeAdj[u][0].first, b=treeAdj[u][1].first;\n      auto [ui,uj]=id2pos[u];\n      auto [ai,aj]=id2pos[a];\n      auto [bi,bj]=id2pos[b];\n      bool col = (ai==ui&&bi==ui)||(aj==uj&&bj==uj);\n      if(!col) is_turn[u]=1;\n    }\n  }\n  vector<char> keep(R,0);\n  for(int u=0;u<R;u++){\n    if(u==start || deg[u]>=3 || is_turn[u]) keep[u]=1;\n  }\n\n  // 5) Build rooted children[] via parent[]\n  vector<vector<int>> children(R);\n  for(int v=0;v<R;v++){\n    int u=parent[v];\n    if(u>=0) children[u].push_back(v);\n  }\n\n  // 6) Compute hasImp[u]: does subtree(u) contain a keep-node?\n  vector<char> hasImp(R,0);\n  function<void(int)> dfsImp = [&](int u){\n    char h=keep[u];\n    for(int v: children[u]){\n      dfsImp(v);\n      if(hasImp[v]) h=1;\n    }\n    hasImp[u]=h;\n  };\n  dfsImp(start);\n\n  // 7) Collect watchers = all keep & hasImp nodes\n  vector<int> watchers;\n  watchers.reserve(R);\n  for(int u=0;u<R;u++){\n    if(keep[u] && hasImp[u]) watchers.push_back(u);\n  }\n  int K = watchers.size();\n  vector<int> invW(R,-1);\n  for(int i=0;i<K;i++) invW[watchers[i]] = i;\n  int rootW = invW[start];\n\n  // 8) Build unweighted 4-nbr list (for returns)\n  vector<vector<int>> nbr(R);\n  for(int u=0;u<R;u++){\n    auto [ui,uj]=id2pos[u];\n    for(int d=0;d<4;d++){\n      int vi=ui+di[d], vj=uj+dj[d];\n      if(vi<0||vi>=N||vj<0||vj>=N) continue;\n      int v=id_map[vi*N+vj];\n      if(v>=0) nbr[u].push_back(v);\n    }\n  }\n\n  // 9) Dijkstra from each watcher \u2192 distW + parentP\n  vector<vector<int>> distW(K, vector<int>(K, INF));\n  vector<vector<int>> parentP(K, vector<int>(R, -1));\n  vector<int> dist(R);\n  vector<char> seenW(K);\n  for(int w=0;w<K;w++){\n    fill(dist.begin(), dist.end(), INF);\n    fill(seenW.begin(), seenW.end(), 0);\n    int src = watchers[w];\n    dist[src]=0;\n    seenW[w]=1;\n    distW[w][w]=0;\n    priority_queue<Node,vector<Node>,Cmp> pq2;\n    pq2.push({0,src});\n    int found=1;\n    while(!pq2.empty() && found<K){\n      auto [cd,u]=pq2.top(); pq2.pop();\n      if(cd!=dist[u]) continue;\n      int iu = invW[u];\n      if(iu>=0 && !seenW[iu]){\n        seenW[iu]=1;\n        distW[w][iu]=cd;\n        found++;\n      }\n      for(int v: nbr[u]){\n        int nd = cd + id2cost[v];\n        if(nd<dist[v]){\n          dist[v]=nd;\n          parentP[w][v]=u;\n          pq2.push({nd,v});\n        }\n      }\n    }\n  }\n\n  //10) MST on watcher-metric (Prim O(K^2))\n  vector<int> keyW(K,INF), parW(K,-1);\n  vector<char> inMW(K,0);\n  keyW[rootW]=0;\n  for(int it=0;it<K;it++){\n    int u=-1, best=INF;\n    for(int i=0;i<K;i++){\n      if(!inMW[i] && keyW[i]<best){\n        best=keyW[i]; u=i;\n      }\n    }\n    if(u<0) break;\n    inMW[u]=1;\n    for(int v=0;v<K;v++){\n      if(!inMW[v] && distW[u][v]<keyW[v]){\n        keyW[v]=distW[u][v];\n        parW[v]=u;\n      }\n    }\n  }\n  // build MST-adj\n  vector<vector<int>> wMSTadj(K);\n  for(int i=0;i<K;i++){\n    int p=parW[i];\n    if(p>=0){\n      wMSTadj[i].push_back(p);\n      wMSTadj[p].push_back(i);\n    }\n  }\n\n  //11) Greedy match odd-degree watchers\n  vector<int> odd;\n  for(int i=0;i<K;i++){\n    if((wMSTadj[i].size() & 1) == 1) odd.push_back(i);\n  }\n  vector<char> usedO(K,0);\n  vector<pair<int,int>> matches;\n  matches.reserve(odd.size()/2);\n  for(int u: odd){\n    if(usedO[u]) continue;\n    int bestd=INF, bestv=-1;\n    for(int v: odd){\n      if(u!=v && !usedO[v] && distW[u][v]<bestd){\n        bestd=distW[u][v];\n        bestv=v;\n      }\n    }\n    if(bestv>=0){\n      usedO[u]=usedO[bestv]=1;\n      matches.emplace_back(u,bestv);\n    }\n  }\n\n  //12) Build Eulerian multigraph on watchers\n  int Ecnt=0;\n  vector<vector<pair<int,int>>> eAdj(K);\n  // MST edges\n  for(int i=0;i<K;i++){\n    for(int j: wMSTadj[i]){\n      if(j>i){\n        eAdj[i].emplace_back(j,Ecnt);\n        eAdj[j].emplace_back(i,Ecnt);\n        Ecnt++;\n      }\n    }\n  }\n  // matching edges\n  for(auto &m: matches){\n    int u=m.first, v=m.second;\n    eAdj[u].emplace_back(v,Ecnt);\n    eAdj[v].emplace_back(u,Ecnt);\n    Ecnt++;\n  }\n  vector<char> usedE(Ecnt,0);\n\n  //13) Hierholzer\u2019s algorithm\n  vector<int> stack_, circuit;\n  stack_.reserve(Ecnt);\n  circuit.reserve(Ecnt+1);\n  stack_.push_back(rootW);\n  vector<int> idx(K,0);\n  while(!stack_.empty()){\n    int u = stack_.back();\n    auto &ad = eAdj[u];\n    while(idx[u] < (int)ad.size() && usedE[ad[idx[u]].second]) idx[u]++;\n    if(idx[u] == (int)ad.size()){\n      circuit.push_back(u);\n      stack_.pop_back();\n    } else {\n      auto [v,eid] = ad[idx[u]++];\n      usedE[eid]=1;\n      stack_.push_back(v);\n    }\n  }\n  // circuit is the Euler tour in reverse\n  reverse(circuit.begin(), circuit.end());\n\n  //14) Shortcut to a Hamiltonian cycle (skip repeats)\n  vector<char> seenH(K,0);\n  vector<int> seqW;\n  seqW.reserve(K+1);\n  for(int w: circuit){\n    if(!seenH[w]){\n      seenH[w]=1;\n      seqW.push_back(w);\n    }\n  }\n  // ensure we return to rootW\n  if(seqW.back()!=rootW) seqW.push_back(rootW);\n\n  //15) 2-opt on seqW\n  int M = seqW.size();\n  bool improved=true;\n  for(int pass=0; pass<3 && improved; pass++){\n    improved=false;\n    for(int i=1;i<M-2 && !improved;i++){\n      for(int j=i+1;j<M-1;j++){\n        int A=seqW[i-1], B=seqW[i],\n            C=seqW[j],   D=seqW[j+1];\n        int before = distW[A][B] + distW[C][D];\n        int after  = distW[A][C] + distW[B][D];\n        if(after < before){\n          reverse(seqW.begin()+i, seqW.begin()+j+1);\n          improved=true;\n          break;\n        }\n      }\n    }\n  }\n\n  //16) Splice into the real grid\n  string ans;\n  ans.reserve(R*3);\n  for(int i=1;i<(int)seqW.size();i++){\n    int uW = seqW[i-1], vW = seqW[i];\n    int u = watchers[uW], v = watchers[vW];\n    // backtrack v\u2192\u2026\u2192u via parentP[uW]\n    vector<int> path;\n    for(int x=v; x!=u; x = parentP[uW][x]){\n      path.push_back(x);\n    }\n    path.push_back(u);\n    reverse(path.begin(), path.end());\n    for(int k=1;k<(int)path.size();k++){\n      auto [ui,uj]=id2pos[path[k-1]];\n      auto [vi,vj]=id2pos[path[k]];\n      ans.push_back(dirOf(ui,uj,vi,vj));\n    }\n  }\n\n  cout << ans << \"\\n\";\n  return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// Static thresholds for backlog\u2010driven weighting\nstatic const int  CAND_RATIO = 15;\nstatic const ll  TW_HIGH    = 13000;\nstatic const ll  RW_LOW     = 1000;\nstatic const ll  TW_LOW     =  8000;\nstatic const ll  RW_HIGH    = 3000;\nstatic const ll  TW_MID     = 10000;\nstatic const ll  RW_MID     = 2000;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N,M,K,R;\n    cin >> N >> M >> K >> R;\n\n    // 1) Read task difficulties\n    vector<vector<int>> d(N, vector<int>(K));\n    for(int i=0;i<N;i++)\n      for(int j=0;j<K;j++)\n        cin >> d[i][j];\n\n    // 2) Read DAG\n    vector<vector<int>> adj(N);\n    vector<int> indeg(N,0);\n    for(int i=0;i<R;i++){\n      int u,v; cin>>u>>v; --u;--v;\n      adj[u].push_back(v);\n      indeg[v]++;\n    }\n\n    // 3) sum of difficulties & static critical\u2010path rank\n    vector<int> sumd(N, 0);\n    for(int i=0;i<N;i++)\n      for(int x: d[i])\n        sumd[i] += x;\n\n    vector<ll> rankv(N,0);\n    // edges only go u<v, so we can do backwards\n    for(int i=N-1;i>=0;i--){\n      ll mx=0;\n      for(int nx: adj[i])\n        mx = max(mx, rankv[nx]);\n      rankv[i] = sumd[i] + mx;\n    }\n\n    // 4) initial ready list\n    vector<int> ready;\n    ready.reserve(N);\n    for(int i=0;i<N;i++)\n      if(indeg[i]==0)\n        ready.push_back(i);\n\n    // 5) scheduler state\n    vector<char> started(N,0), done(N,0);\n    vector<int>  assigned(M,-1), start_day(M,0);\n    vector<int>  free_list(M);\n    iota(free_list.begin(), free_list.end(), 0);\n\n    // 6) skill lower bounds per worker\n    vector<vector<int>> s_est(M, vector<int>(K,0));\n\n    int day = 1;\n    while(true){\n      // gather truly ready & unstarted tasks\n      vector<int> cand;\n      cand.reserve(ready.size());\n      for(int t: ready)\n        if(!started[t] && !done[t])\n          cand.push_back(t);\n\n      // trim to top M*15 by rank\n      int C = M * CAND_RATIO;\n      if((int)cand.size() > C){\n        nth_element(\n          cand.begin(), cand.begin()+C, cand.end(),\n          [&](int a,int b){ return rankv[a] > rankv[b]; }\n        );\n        cand.resize(C);\n      }\n\n      // backlog ratio = tasks per free worker\n      int F = free_list.size();\n      ll TIME_W, RANK_W;\n      if(F>0 && (int)cand.size()/F > 12){\n        TIME_W = TW_HIGH;  RANK_W = RW_LOW;\n      } else if(F>0 && (int)cand.size()/F < 3){\n        TIME_W = TW_LOW;   RANK_W = RW_HIGH;\n      } else {\n        TIME_W = TW_MID;   RANK_W = RW_MID;\n      }\n\n      // global greedy min\u2010cost matching\n      // cost(w,t) = TIME_W*pred_t - RANK_W*rankv[t]\n      // pred_t = deficit>0 ? deficit+1 : 1\n      vector<pair<int,int>> out;\n      out.reserve(M);\n\n      while(!free_list.empty() && !cand.empty()){\n        ll best_cost = LLONG_MAX;\n        int bi=-1, bj=-1;\n        for(int i=0;i<(int)free_list.size();i++){\n          int w = free_list[i];\n          auto &se = s_est[w];\n          for(int j=0;j<(int)cand.size();j++){\n            int t = cand[j];\n            int def=0;\n            for(int k2=0;k2<K;k2++){\n              int delta = d[t][k2] - se[k2];\n              if(delta>0) def += delta;\n            }\n            ll pred_t = def>0 ? (ll)def+1 : 1LL;\n            ll cost   = pred_t*TIME_W - rankv[t]*RANK_W;\n            if(cost < best_cost){\n              best_cost = cost;\n              bi = i; bj = j;\n            }\n          }\n        }\n        if(bi<0) break;\n        int w = free_list[bi], t = cand[bj];\n        // assign\n        started[t]     = 1;\n        assigned[w]    = t;\n        start_day[w]   = day;\n        out.emplace_back(w+1, t+1);\n        free_list.erase(free_list.begin()+bi);\n        cand      .erase(cand.begin()+bj);\n      }\n\n      // output\n      cout << out.size();\n      for(auto &pr: out)\n        cout << ' ' << pr.first << ' ' << pr.second;\n      cout << \"\\n\" << flush;\n\n      // read completions\n      int Cc;\n      if(!(cin>>Cc) || Cc<0) break;\n      for(int _=0;_<Cc;_++){\n        int f; cin>>f;\n        int w = f-1, t = assigned[w];\n        int took   = day - start_day[w] + 1;\n        int w_est  = max(0, took - 1);\n        // robust update **on every** completion\n        if(t>=0){\n          for(int k2=0;k2<K;k2++){\n            int lb = d[t][k2] - w_est;\n            if(lb > s_est[w][k2])\n              s_est[w][k2] = lb;\n          }\n        }\n        // free worker\n        assigned[w] = -1;\n        free_list.push_back(w);\n\n        // mark done & unlock\n        if(t>=0 && !done[t]){\n          done[t] = 1;\n          for(int nx: adj[t]){\n            if(--indeg[nx]==0)\n              ready.push_back(nx);\n          }\n        }\n      }\n      day++;\n    }\n\n    return 0;\n}","ahc006":"#include <bits/stdc++.h>\n#include <chrono>\nusing namespace std;\nusing ll = long long;\n\n// Manhattan distance\nstatic inline int manh(int x1,int y1,int x2,int y2){\n    return abs(x1-x2)+abs(y1-y2);\n}\n\n// Order struct\nstruct Order {\n    int a,b,c,d,dist;\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // 1) Read 1000 orders\n    vector<Order> ord(1000);\n    for(int i=0;i<1000;i++){\n        cin>>ord[i].a>>ord[i].b>>ord[i].c>>ord[i].d;\n        ord[i].dist = manh(ord[i].a,ord[i].b, ord[i].c,ord[i].d);\n    }\n\n    // Global timer\n    auto T0 = chrono::steady_clock::now();\n    auto elapsed = [&](){\n        return chrono::duration<double>(\n            chrono::steady_clock::now() - T0\n        ).count();\n    };\n    const double TL_TOTAL = 1.97;\n\n    // 2) Pick 50 orders with smallest internal distance\n    vector<int> initial_sel(1000);\n    iota(initial_sel.begin(), initial_sel.end(), 0);\n    nth_element(\n        initial_sel.begin(),\n        initial_sel.begin()+50,\n        initial_sel.end(),\n        [&](int i,int j){ return ord[i].dist < ord[j].dist; }\n    );\n    initial_sel.resize(50);\n    const int M = 50;\n\n    // 3) Build condensed graph on these M\n    vector<int> px(M),py(M),dx(M),dy(M), start_cost(M), end_cost(M);\n    for(int i=0;i<M;i++){\n        auto &o = ord[ initial_sel[i] ];\n        px[i]=o.a;  py[i]=o.b;\n        dx[i]=o.c;  dy[i]=o.d;\n        start_cost[i] = manh(400,400, px[i],py[i]);\n        end_cost[i]   = manh(dx[i],dy[i], 400,400);\n    }\n    static int trans0[50][50];\n    for(int i=0;i<M;i++){\n        for(int j=0;j<M;j++){\n            trans0[i][j] = manh(dx[i],dy[i], px[j],py[j]);\n        }\n    }\n\n    // 4) Multi\u2010start greedy NN: 10 pure + 22 semi\u2010random\n    vector<int> order_by_start(M);\n    iota(order_by_start.begin(), order_by_start.end(), 0);\n    sort(order_by_start.begin(), order_by_start.end(),\n         [&](int i,int j){ return start_cost[i]<start_cost[j]; });\n\n    const int K = min(M,32), K_PURE=10, RAND_K=5;\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    vector<pair<ll,vector<int>>> seeds;\n    seeds.reserve(K);\n\n    for(int ss=0; ss<K && elapsed()<0.50; ss++){\n        int s = order_by_start[ss];\n        vector<char> used(M,false);\n        vector<int> path; path.reserve(M);\n        path.push_back(s); used[s]=1;\n        int cur=s;\n        for(int t=1;t<M;t++){\n            int nxt=-1;\n            if(ss<K_PURE){\n                int bestc=INT_MAX;\n                for(int j=0;j<M;j++) if(!used[j]){\n                    int c=trans0[cur][j];\n                    if(c<bestc){ bestc=c; nxt=j; }\n                }\n            } else {\n                vector<pair<int,int>> cand; cand.reserve(M);\n                for(int j=0;j<M;j++) if(!used[j]){\n                    cand.emplace_back(trans0[cur][j], j);\n                }\n                int k = min(RAND_K, (int)cand.size());\n                nth_element(cand.begin(), cand.begin()+k, cand.end());\n                uniform_int_distribution<int> pick(0,k-1);\n                nxt = cand[pick(rng)].second;\n            }\n            path.push_back(nxt);\n            used[nxt]=1;\n            cur = nxt;\n        }\n        ll csum = start_cost[path[0]];\n        for(int i=0;i+1<M;i++) csum += trans0[path[i]][path[i+1]];\n        csum += end_cost[path[M-1]];\n        seeds.emplace_back(csum, move(path));\n    }\n    if(seeds.empty()){\n        vector<int> p(M);\n        iota(p.begin(),p.end(),0);\n        ll c = start_cost[0]+end_cost[0];\n        for(int i=0;i+1<M;i++) c+=trans0[i][i+1];\n        seeds.emplace_back(c,p);\n    }\n    sort(seeds.begin(), seeds.end(),\n         [&](auto &A,auto &B){ return A.first < B.first; });\n\n    // 4.5) Optional OX1 crossover between top\u20102 seeds\n    if(seeds.size()>1 && elapsed()<0.45){\n        auto &A = seeds[0].second;\n        auto &B = seeds[1].second;\n        vector<int> C(M, -1), used2(M,0);\n        int cut = 1 + int(rng()%(M-2));\n        for(int i=0;i<cut;i++){\n            C[i]=A[i];\n            used2[A[i]]=1;\n        }\n        int pos=cut;\n        for(int i=0;i<M && pos<M;i++){\n            if(!used2[B[i]]){\n                C[pos++]=B[i];\n            }\n        }\n        ll csum = start_cost[C[0]];\n        for(int i=0;i+1<M;i++) csum += trans0[C[i]][C[i+1]];\n        csum += end_cost[C[M-1]];\n        seeds.emplace_back(csum, move(C));\n        sort(seeds.begin(), seeds.end(),\n             [&](auto &A,auto &B){ return A.first < B.first; });\n    }\n\n    // 5) Phase\u20091: directed\u20102opt on top\u20103 seeds until ~1.20s\n    const double TL1 = 1.20;\n    ll best_cost = seeds[0].first;\n    vector<int> best_path = seeds[0].second;\n    int T_OPT = min((int)seeds.size(), 3);\n\n    for(int ti=0; ti<T_OPT && elapsed()<TL1; ti++){\n        ll cur_cost = seeds[ti].first;\n        auto P = seeds[ti].second;\n        static ll prefix[50];\n        while(elapsed()<TL1){\n            bool improved=false;\n            prefix[0] = (ll)trans0[P[1]][P[0]] - trans0[P[0]][P[1]];\n            for(int k=1;k<M-1;k++){\n                prefix[k] = prefix[k-1]\n                           + ((ll)trans0[P[k+1]][P[k]] - trans0[P[k]][P[k+1]]);\n            }\n            for(int i=1;i<M-1 && !improved;i++){\n                int A=P[i-1], B=P[i];\n                ll o1=trans0[A][B], bef=prefix[i-1];\n                for(int j=i+1;j<M && !improved;j++){\n                    int Cn=P[j];\n                    bool endsg=(j==M-1);\n                    ll o2 = endsg ? end_cost[Cn] : trans0[Cn][P[j+1]];\n                    ll n1 = trans0[A][Cn];\n                    ll n2 = endsg ? end_cost[B] : trans0[B][P[j+1]];\n                    ll interior = prefix[j-1] - bef;\n                    ll delta = (n1+n2) - (o1+o2) + interior;\n                    if(delta<0){\n                        reverse(P.begin()+i, P.begin()+j+1);\n                        cur_cost += delta;\n                        improved=true;\n                    }\n                }\n            }\n            if(!improved) break;\n        }\n        if(cur_cost < best_cost){\n            best_cost = cur_cost;\n            best_path = move(P);\n        }\n    }\n\n    // 6) Phase\u20092: explicit route + swap\u2010out/in until ~1.60s\n    vector<int> cur_sel_ids(M);\n    for(int i=0;i<M;i++){\n        cur_sel_ids[i] = initial_sel[ best_path[i] ];\n    }\n    vector<pair<int,int>> route;\n    route.reserve(2*M+2);\n    route.emplace_back(400,400);\n    for(int k=0;k<M;k++){\n        auto &o=ord[cur_sel_ids[k]];\n        route.emplace_back(o.a,o.b);\n        route.emplace_back(o.c,o.d);\n    }\n    route.emplace_back(400,400);\n\n    // build outside\u2010pool = top 200 unused\n    static bool in_sel[1000];\n    memset(in_sel,0,sizeof(in_sel));\n    for(int x:cur_sel_ids) in_sel[x]=1;\n    vector<pair<int,int>> outv; outv.reserve(1000);\n    for(int i=0;i<1000;i++){\n        if(!in_sel[i]) outv.emplace_back(ord[i].dist, i);\n    }\n    sort(outv.begin(), outv.end());\n    const int K_OUT = 200;\n    if((int)outv.size()>K_OUT) outv.resize(K_OUT);\n    vector<int> outside; outside.reserve(K_OUT);\n    for(auto &p: outv) outside.push_back(p.second);\n\n    while(elapsed()<1.60){\n        // best removal\n        ll best_rem=LLONG_MIN; int rem_i=-1;\n        for(int k=0;k<M;k++){\n            int rp=2*k+1;\n            auto &L=route[rp-1], &Pp=route[rp],\n                  &D=route[rp+1], &R=route[rp+2];\n            ll bef = manh(L.first,L.second,Pp.first,Pp.second)\n                   + manh(Pp.first,Pp.second,D.first,D.second)\n                   + manh(D.first,D.second,R.first,R.second);\n            ll aft = manh(L.first,L.second,R.first,R.second);\n            ll d   = bef - aft;\n            if(d>best_rem){ best_rem=d; rem_i=k; }\n        }\n        if(best_rem<=0) break;\n\n        // best insertion\n        ll best_ins=LLONG_MAX; int ins_j=-1, ins_pos=0;\n        for(int j=0;j<(int)outside.size();j++){\n            auto &o=ord[outside[j]];\n            ll bestj=LLONG_MAX; int bp=0;\n            for(int ip=0;ip<=M;ip++){\n                int rp=2*ip;\n                auto &A=route[rp], &B=route[rp+1];\n                ll cb=manh(A.first,A.second,B.first,B.second);\n                ll ca=manh(A.first,A.second,o.a,o.b)\n                      +manh(o.a,o.b,o.c,o.d)\n                      +manh(o.c,o.d,B.first,B.second);\n                ll d=ca-cb;\n                if(d<bestj){ bestj=d; bp=ip; }\n            }\n            if(bestj<best_ins){\n                best_ins=bestj; ins_j=j; ins_pos=bp;\n            }\n        }\n        if(ins_j<0 || best_ins>=best_rem) break;\n\n        // apply swap\u2010out/in\n        int old_id=cur_sel_ids[rem_i],\n            new_id=outside[ins_j];\n        int rp=2*rem_i+1;\n        route.erase(route.begin()+rp, route.begin()+rp+2);\n        cur_sel_ids.erase(cur_sel_ids.begin()+rem_i);\n\n        int np=ins_pos;\n        if(ins_pos>rem_i) np=ins_pos-1;\n        cur_sel_ids.insert(cur_sel_ids.begin()+np, new_id);\n        int ip=2*np+1;\n        route.insert(route.begin()+ip,   {ord[new_id].a, ord[new_id].b});\n        route.insert(route.begin()+ip+1, {ord[new_id].c, ord[new_id].d});\n\n        outside[ins_j] = old_id;\n    }\n\n    // 7) Phase\u20093: SA on the 50-block tour until TL_TOTAL\n    // rebuild block\u2010graph\n    vector<int> px2(M),py2(M),dx2(M),dy2(M), st2(M), en2(M);\n    for(int i=0;i<M;i++){\n        auto &o=ord[cur_sel_ids[i]];\n        px2[i]=o.a;  py2[i]=o.b;\n        dx2[i]=o.c;  dy2[i]=o.d;\n        st2[i]=manh(400,400,px2[i],py2[i]);\n        en2[i]=manh(dx2[i],dy2[i],400,400);\n    }\n    static int trans2[50][50];\n    for(int i=0;i<M;i++){\n        for(int j=0;j<M;j++){\n            trans2[i][j] = manh(dx2[i],dy2[i], px2[j],py2[j]);\n        }\n    }\n    vector<int> P2(M);\n    iota(P2.begin(),P2.end(),0);\n    ll cost2 = st2[P2[0]];\n    for(int i=0;i+1<M;i++) cost2 += trans2[P2[i]][P2[i+1]];\n    cost2 += en2[P2[M-1]];\n\n    auto computeCost = [&](auto &Q){\n        ll c = st2[Q[0]];\n        for(int i=0;i+1<M;i++) c += trans2[Q[i]][Q[i+1]];\n        c += en2[Q[M-1]];\n        return c;\n    };\n\n    ll best_cost2 = cost2;\n    vector<int> Pbest2 = P2;\n    const double T_init = 1000.0;\n    uniform_real_distribution<double> U01(0.0,1.0);\n    int sa_iter=0;\n\n    while(elapsed()<TL_TOTAL){\n        double T = T_init * (1.0 - elapsed()/TL_TOTAL);\n        int which = rng()%3;\n        vector<int> Q;\n        if(which==0){\n            // relocation: pick i\u2208[0..M-1], remove, then reinsert at j\u2208[0..M-1]\n            int i = rng() % M;\n            Q = P2;\n            int v = Q[i];\n            Q.erase(Q.begin()+i);\n            int j = rng() % M;  // <-- CORRECTED BOUND\n            Q.insert(Q.begin()+j, v);\n        }\n        else if(which==1){\n            // block\u2010swap\n            Q = P2;\n            int i = rng()%M, j = rng()%M;\n            if(i!=j) swap(Q[i],Q[j]);\n        }\n        else {\n            // double\u2010bridge\n            int a = uniform_int_distribution<int>(0,M-5)(rng);\n            int b = uniform_int_distribution<int>(a+1,M-4)(rng);\n            int c = uniform_int_distribution<int>(b+1,M-3)(rng);\n            int d = uniform_int_distribution<int>(c+1,M-2)(rng);\n            Q.reserve(M);\n            for(int x=0;x<=a;x++)    Q.push_back(P2[x]);\n            for(int x=c+1;x<=d;x++)  Q.push_back(P2[x]);\n            for(int x=b+1;x<=c;x++)  Q.push_back(P2[x]);\n            for(int x=a+1;x<=b;x++)  Q.push_back(P2[x]);\n            for(int x=d+1;x<M;x++)   Q.push_back(P2[x]);\n        }\n        ll costQ = computeCost(Q);\n        ll delta = costQ - cost2;\n        if(delta<0 || (T>0 && U01(rng) < exp(-delta/T))){\n            P2 = move(Q);\n            cost2 = costQ;\n            if(cost2 < best_cost2){\n                best_cost2 = cost2;\n                Pbest2 = P2;\n            }\n        }\n        if((++sa_iter & 63)==0 && elapsed()>=TL_TOTAL) break;\n    }\n    P2 = move(Pbest2);\n\n    // 8) Build final_sel & final_route\n    vector<int> final_sel(M);\n    for(int i=0;i<M;i++){\n        final_sel[i] = cur_sel_ids[ P2[i] ];\n    }\n    vector<pair<int,int>> final_route;\n    final_route.reserve(2*M+2);\n    final_route.emplace_back(400,400);\n    for(int i=0;i<M;i++){\n        auto &o=ord[ final_sel[i] ];\n        final_route.emplace_back(o.a,o.b);\n        final_route.emplace_back(o.c,o.d);\n    }\n    final_route.emplace_back(400,400);\n\n    // 9) Output\n    cout<<M;\n    for(int id: final_sel) cout<<' '<<(id+1);\n    cout<<\"\\n\";\n    cout<<final_route.size();\n    for(auto &p: final_route){\n        cout<<\" \"<<p.first<<\" \"<<p.second;\n    }\n    cout<<\"\\n\";\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\n// DSU with path\u2010compression + union\u2010by\u2010rank\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n): p(n), r(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 N = 400, M = 1995, LOG;\n// MST-adjacency for LCA\nvector<vector<pair<int,int>>> adj;\nvector<int> depth;\nvector<vector<int>> up, maxd;\n\n// build depth[], up[0][], maxd[0][] with a dfs\nvoid dfs(int v,int p,int pd){\n    up[0][v]   = (p<0 ? v : p);\n    maxd[0][v] = pd;\n    for(auto &ed: adj[v]){\n        int w = ed.first, d = ed.second;\n        if(w==p) continue;\n        depth[w] = depth[v]+1;\n        dfs(w, v, d);\n    }\n}\n\n// query the maximum d-weight on the MST-path u\u2194v\nint query_max(int u,int v){\n    if(depth[u]<depth[v]) swap(u,v);\n    int res = 0;\n    int diff = depth[u] - depth[v];\n    for(int k=0; k<=LOG; k++){\n        if(diff>>k & 1){\n            res = max(res, maxd[k][u]);\n            u = up[k][u];\n        }\n    }\n    if(u==v) return res;\n    for(int k=LOG; k>=0; k--){\n        if(up[k][u]!=up[k][v]){\n            res = max(res, maxd[k][u]);\n            res = max(res, maxd[k][v]);\n            u = up[k][u];\n            v = up[k][v];\n        }\n    }\n    // one more step to LCA\n    res = max(res, maxd[0][u]);\n    res = max(res, maxd[0][v]);\n    return res;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    vector<pair<int,int>> coord(N);\n    for(int i=0;i<N;i++){\n        cin>>coord[i].first>>coord[i].second;\n    }\n\n    struct E{ int u,v,id,d; };\n    vector<E> EL; EL.reserve(M);\n    vector<int> U(M), V(M), D(M);\n\n    // read static edges, compute d_i\n    for(int i=0;i<M;i++){\n        int u,v; cin>>u>>v;\n        U[i]=u; V[i]=v;\n        long long dx = coord[u].first - coord[v].first;\n        long long dy = coord[u].second - coord[v].second;\n        int di = int(llround(sqrt(double(dx*dx + dy*dy))));\n        D[i] = di;\n        EL.push_back({u,v,i,di});\n    }\n\n    // 1) Kruskal MST on d_i\n    sort(EL.begin(), EL.end(),\n         [&](auto &a, auto &b){ return a.d < b.d; });\n    DSU dsu0(N);\n    vector<char> isMST(M,0);\n    adj.assign(N,{});\n    int used = 0;\n    for(auto &e : EL){\n        if(dsu0.unite(e.u,e.v)){\n            isMST[e.id] = 1;\n            used++;\n            adj[e.u].push_back({e.v,e.d});\n            adj[e.v].push_back({e.u,e.d});\n            if(used==N-1) break;\n        }\n    }\n\n    // 2) Build LCA + max-edge table on the MST\n    LOG = 0; while((1<<LOG) <= N) LOG++;\n    depth.assign(N,0);\n    up.assign(LOG+1, vector<int>(N,0));\n    maxd.assign(LOG+1, vector<int>(N,0));\n    dfs(0,-1,0);\n    for(int k=1;k<=LOG;k++){\n        for(int v=0;v<N;v++){\n            int p = up[k-1][v];\n            up[k][v]   = up[k-1][p];\n            maxd[k][v] = max(maxd[k-1][v], maxd[k-1][p]);\n        }\n    }\n\n    // 3) Online: DSU over *accepted* edges\n    DSU ds(N);\n    int accepted = 0;\n\n    for(int i=0;i<M;i++){\n        int l; cin>>l;\n        int u = U[i], v = V[i];\n        bool take = false;\n\n        if(ds.find(u) != ds.find(v)){\n            if(isMST[i]){\n                // guaranteed fallback\n                take = true;\n            } else {\n                // dynamic threshold on the cut's worst nominal\n                int rem_merge = (N-1) - accepted;\n                int rem_inp   = M - i;\n                int md = query_max(u,v);\n                // accept if l*rem_inp <= md*(rem_inp + 2*rem_merge)\n                long long LHS = (long long)l * rem_inp;\n                long long RHS = (long long)md * (rem_inp + 2LL*rem_merge);\n                if(LHS <= RHS) take = true;\n            }\n        }\n\n        if(take){\n            cout<<\"1\\n\";\n            ds.unite(u,v);\n            accepted++;\n        } else {\n            cout<<\"0\\n\";\n        }\n        cout.flush();\n    }\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Global maps for this turn\nstatic bool petAt[30][30], humanAt[30][30], impWall[30][30], builtThis[30][30];\n\n// 4\u2010direction helpers\nint dx4[4] = {-1,0,1,0}, dy4[4] = {0,1,0,-1};\nchar buildC[4] = {'u','r','d','l'};\nint buildDirIdx(char c){\n  if(c=='u') return 0;\n  if(c=='r') return 1;\n  if(c=='d') return 2;\n  if(c=='l') return 3;\n  return -1;\n}\nvoid moveDelta(char c,int& dx,int& dy){\n  if(c=='U'){ dx=-1; dy=0; }\n  else if(c=='D'){ dx= 1; dy=0; }\n  else if(c=='L'){ dx= 0; dy=-1;}\n  else if(c=='R'){ dx= 0; dy= 1;}\n  else dx=dy=0;\n}\n\n// Can we legally build at (bx,by) right now?\nbool canBuildAt(int bx,int by){\n  if(bx<0||bx>=30||by<0||by>=30) return false;\n  if(petAt[bx][by] || humanAt[bx][by]) return false;\n  for(int d=0; d<4; d++){\n    int ax=bx+dx4[d], ay=by+dy4[d];\n    if(ax>=0&&ax<30&&ay>=0&&ay<30 && petAt[ax][ay])\n      return false;\n  }\n  return true;\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<int> ppx(N), ppy(N), pt(N);\n  for(int i=0;i<N;i++){\n    cin>>ppx[i]>>ppy[i]>>pt[i];\n    --ppx[i]; --ppy[i];\n  }\n  int M; cin>>M;\n  vector<int> hx(M), hy(M);\n  for(int i=0;i<M;i++){\n    cin>>hx[i]>>hy[i];\n    --hx[i]; --hy[i];\n  }\n\n  // 1) Initialize petAt\n  memset(petAt,0,sizeof(petAt));\n  for(int i=0;i<N;i++){\n    petAt[ppx[i]][ppy[i]] = true;\n  }\n  // 2) Initialize humanAt & current positions\n  memset(humanAt,0,sizeof(humanAt));\n  vector<int> cx = hx, cy = hy;\n  for(int i=0;i<M;i++){\n    humanAt[cx[i]][cy[i]] = true;\n  }\n  // 3) Initialize wall map\n  memset(impWall,0,sizeof(impWall));\n\n  // 4) Sort humans by hy to assign vertical stripes\n  vector<pair<int,int>> order;\n  order.reserve(M);\n  for(int i=0;i<M;i++) order.emplace_back(hy[i], i);\n  sort(order.begin(), order.end());\n\n  // 5) Partition columns [0..29] into M nearly equal stripes\n  vector<int> width(M), L(M), R(M);\n  int baseW = 30 / M, rem = 30 % M;\n  for(int k=0;k<M;k++){\n    width[k] = baseW + (k<rem);\n  }\n  {\n    int cur=0;\n    for(int k=0;k<M;k++){\n      L[k] = cur;\n      R[k] = cur + width[k] - 1;\n      cur += width[k];\n    }\n  }\n\n  // 6) Compute for each human i:\n  //    - its assigned stripe k\n  //    - a chosen startRow (0 or 29) nearest\n  //    - relocationCost = |hx[i]-startRow| + |hy[i]-R[k]|\n  //    - for stripe\u2010builders k<M-1, schedule startTime = max(relocCost[i], relocCost[nextBuilder])\n  vector<int> stripeOf(M), startRow(M), relocCost(M), startTime(M,0);\n  for(int k=0;k<M;k++){\n    int i = order[k].second;\n    stripeOf[i] = k;\n    // choose nearest horizontal fence end\n    int upDist = abs(hx[i]-0), dnDist = abs(hx[i]-29);\n    startRow[i] = (upDist <= dnDist ? 0 : 29);\n    // relocation is to (startRow, R[k])\n    relocCost[i] = abs(hx[i]-startRow[i]) + abs(hy[i] - R[k]);\n  }\n  // schedule each barrier builder to wait for its immediate neighbor\n  for(int k=0;k<M-1;k++){\n    int i = order[k].second;\n    int j = order[k+1].second;\n    startTime[i] = max(relocCost[i], relocCost[j]);\n  }\n  // the last stripe builder never builds a fence; but\n  // we still give it startTime = relocCost so its relocation is done\n  {\n    int i = order[M-1].second;\n    startTime[i] = relocCost[i];\n  }\n\n  // 7) Construct the 300\u2010turn plan for each human\n  const int TURNS = 300;\n  vector< array<char,TURNS> > plan(M);\n  for(int i=0;i<M;i++){\n    plan[i].fill('.');\n    int k = stripeOf[i];\n    // a) vertical relocation\n    int p = 0;\n    char vmove = (startRow[i]==0 ? 'U' : 'D');\n    int stepsV = abs(hx[i] - startRow[i]);\n    for(int z=0; z<stepsV && p<TURNS; z++){\n      plan[i][p++] = vmove;\n    }\n    // b) horizontal relocation\n    int dy = R[k] - hy[i];\n    char hmove = (dy>0 ? 'R' : 'L');\n    for(int z=0; z<abs(dy) && p<TURNS; z++){\n      plan[i][p++] = hmove;\n    }\n    // c) pad with dots until startTime\n    int pad = startTime[i] - relocCost[i];\n    for(int z=0; z<pad && p<TURNS; z++){\n      plan[i][p++] = '.';\n    }\n    // d) if k<M-1, build a vertical fence of height 30 at col=R[k]+1\n    if(k < M-1){\n      char bld = 'r';               // build right\n      char walkVert = (startRow[i]==0 ? 'D' : 'U');\n      // for 29 segments: build then move\n      for(int s=0; s<29 && p<TURNS; s++){\n        plan[i][p++] = bld;\n        if(p<TURNS) plan[i][p++] = walkVert;\n      }\n      // last build\n      if(p<TURNS) plan[i][p++] = bld;\n    }\n    // remaining turns stay '.'\n  }\n\n  // 8) Interactive execution with stall\u2010and\u2010retry per turn\n  vector<int> ptr(M,0);\n  string out(M, '.');\n\n  for(int turn=0; turn<TURNS; turn++){\n    // a) clear this\u2010turn built mask\n    memset(builtThis,0,sizeof(builtThis));\n    vector<bool> isBuild(M,false), isMove(M,false);\n\n    // b) pre\u2010scan which builds would be legal\n    for(int i=0;i<M;i++){\n      if(ptr[i]>=TURNS) continue;\n      char c = plan[i][ptr[i]];\n      int d = buildDirIdx(c);\n      if(d>=0){\n        int bx = cx[i] + dx4[d], by = cy[i] + dy4[d];\n        if(canBuildAt(bx,by)){\n          isBuild[i] = true;\n          builtThis[bx][by] = true;\n        }\n      }\n    }\n    // c) scan which moves would be legal (walls only)\n    for(int i=0;i<M;i++){\n      if(ptr[i]>=TURNS) continue;\n      char c = plan[i][ptr[i]];\n      if(c=='U'||c=='D'||c=='L'||c=='R'){\n        int dx,dy; moveDelta(c,dx,dy);\n        int tx = cx[i]+dx, ty = cy[i]+dy;\n        if(tx>=0 && tx<30 && ty>=0 && ty<30\n           && !impWall[tx][ty] && !builtThis[tx][ty]){\n          isMove[i] = true;\n        }\n      }\n    }\n    // d) finalize this turn's actions\n    for(int i=0;i<M;i++){\n      if(isBuild[i] || isMove[i])\n        out[i] = plan[i][ptr[i]];\n      else\n        out[i] = '.';\n    }\n    // e) advance ptr only on success or on a no\u2010op dot\n    for(int i=0;i<M;i++){\n      if(ptr[i]>=TURNS) continue;\n      char c = plan[i][ptr[i]];\n      int d = buildDirIdx(c);\n      if(d>=0){\n        if(isBuild[i]) ptr[i]++;\n      }\n      else if(c=='U'||c=='D'||c=='L'||c=='R'){\n        if(isMove[i]) ptr[i]++;\n      }\n      else {\n        // dot\n        ptr[i]++;\n      }\n    }\n    // f) apply builds to the global wall map\n    for(int i=0;i<M;i++){\n      if(isBuild[i]){\n        int d = buildDirIdx(out[i]);\n        int bx = cx[i] + dx4[d], by = cy[i] + dy4[d];\n        if(bx>=0&&bx<30&&by>=0&&by<30)\n          impWall[bx][by] = true;\n      }\n    }\n    // g) apply moves to humanAt and update cx,cy\n    for(int i=0;i<M;i++){\n      humanAt[cx[i]][cy[i]] = false;\n    }\n    for(int i=0;i<M;i++){\n      if(isMove[i]){\n        int dx,dy; moveDelta(out[i],dx,dy);\n        cx[i] += dx; cy[i] += dy;\n      }\n    }\n    for(int i=0;i<M;i++){\n      humanAt[cx[i]][cy[i]] = true;\n    }\n\n    // h) output and flush\n    cout << out << \"\\n\" << flush;\n\n    // i) read pet movements, rebuild petAt\n    vector<string> mv(N);\n    for(int i=0;i<N;i++){\n      cin >> mv[i];\n    }\n    memset(petAt,0,sizeof(petAt));\n    for(int i=0;i<N;i++){\n      if(mv[i]!=\".\"){\n        for(char c: mv[i]){\n          int dx,dy; moveDelta(c,dx,dy);\n          ppx[i] += dx; ppy[i] += dy;\n        }\n      }\n      int x=ppx[i], y=ppy[i];\n      if(x>=0&&x<30&&y>=0&&y<30)\n        petAt[x][y] = true;\n    }\n  }\n\n  return 0;\n}","ahc009":"#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,ti,tj;\n    double p;\n    cin >> si >> sj >> ti >> tj >> p;\n\n    // read walls\n    vector<string> h(20), v(19);\n    for(int i=0;i<20;i++) cin >> h[i];\n    for(int i=0;i<19;i++) cin >> v[i];\n\n    // Precompute for each cell (i,j) the list of valid neighbor\u2010directions,\n    // sorted by manhattan distance to target ascending.\n    static vector<int> nbr[20][20];\n    int dx[4]={-1,1,0,0}, dy[4]={0,0,-1,1};\n    char dc[4]={'U','D','L','R'};\n    for(int i=0;i<20;i++){\n        for(int j=0;j<20;j++){\n            nbr[i][j].clear();\n            for(int d=0;d<4;d++){\n                int ni=i+dx[d], nj=j+dy[d];\n                bool ok=false;\n                if(d==0){ if(i>=1   && v[i-1][j]=='0') ok=true; }\n                if(d==1){ if(i<=18  && v[i][j]=='0')   ok=true; }\n                if(d==2){ if(j>=1   && h[i][j-1]=='0') ok=true; }\n                if(d==3){ if(j<=18  && h[i][j]=='0')   ok=true; }\n                if(ok){\n                    nbr[i][j].push_back(d);\n                }\n            }\n            // sort by manhattan distance of the neighbor to (ti,tj)\n            sort(nbr[i][j].begin(), nbr[i][j].end(),\n                 [&](int d1,int d2){\n                     int ni1=i+dx[d1], nj1=j+dy[d1];\n                     int ni2=i+dx[d2], nj2=j+dy[d2];\n                     int md1=abs(ni1-ti)+abs(nj1-tj);\n                     int md2=abs(ni2-ti)+abs(nj2-tj);\n                     return md1<md2;\n                 });\n        }\n    }\n\n    // BFS to find the shortest path in the union\u2010of\u2010trees graph\n    static int dist[20][20], pi_[20][20], pj_[20][20];\n    static char pm_[20][20];\n    const int INF = 1e9;\n    for(int i=0;i<20;i++)\n      for(int j=0;j<20;j++)\n        dist[i][j]=INF;\n\n    queue<pair<int,int>> q;\n    dist[si][sj]=0;\n    q.push({si,sj});\n    while(!q.empty()){\n        auto [i,j]=q.front(); q.pop();\n        if(i==ti && j==tj) break;\n        for(int d: nbr[i][j]){\n            int ni=i+dx[d], nj=j+dy[d];\n            if(dist[ni][nj] > dist[i][j]+1){\n                dist[ni][nj]=dist[i][j]+1;\n                pi_[ni][nj]=i; pj_[ni][nj]=j;\n                pm_[ni][nj]=dc[d];\n                q.push({ni,nj});\n            }\n        }\n    }\n\n    // Reconstruct the move sequence\n    vector<char> path;\n    if(dist[ti][tj]<INF){\n        int ci=ti, cj=tj;\n        while(!(ci==si && cj==sj)){\n            char c = pm_[ci][cj];\n            path.push_back(c);\n            int pi=pi_[ci][cj], pj=pj_[ci][cj];\n            ci=pi; cj=pj;\n        }\n        reverse(path.begin(), path.end());\n    }\n    int D = (int)path.size();\n    if(D==0){\n        // either already at office (rare) or no path\n        cout<<\"\\n\";\n        return 0;\n    }\n\n    // We will pick a uniform block\u2010size k, B = floor(200/k) full blocks,\n    // then distribute any rem = 200 - B*k extra instructions across\n    // the last rem blocks (1 each).\n    int k_cap = 200 / D;\n    if(k_cap < 1) k_cap = 1;\n    // precompute p^k\n    vector<double> ppow(k_cap+2, 1.0);\n    for(int i=1;i<=k_cap;i++) ppow[i] = ppow[i-1] * p;\n\n    // Negative\u2010Binomial enumeration to choose best k\n    double bestE = -1.0;\n    int best_k = 1, best_B = D;\n    for(int k=1;k<=k_cap;k++){\n        double pk = ppow[k];\n        double q  = 1.0 - pk;\n        int B = 200 / k;\n        if(B < D) continue;\n        // failures allowed in full\u2010block NB until the Dth success\n        int rmax = B - D;\n        // P_j = Prob exactly j failures before the Dth success (i.e. finish in block D+j)\n        // P_0 = q^D\n        double Pj = pow(q, D);\n        double E = Pj * (401.0 - k*(D+0));\n        for(int j=1;j<=rmax;j++){\n            // NB recurrence\n            Pj = Pj * ((D + j - 1.0)/ j) * (1.0 - q);\n            E += Pj * (401.0 - k*(D + j));\n        }\n        if(E > bestE){\n            bestE = E;\n            best_k = k;\n            best_B = B;\n        }\n    }\n\n    // Now build the actual instruction string of length exactly 200:\n    // give best_B blocks, each block = best_k or best_k+1 reps\n    // (we distribute rem = 200 - best_B*best_k across the last rem blocks)\n    int rem = 200 - best_B * best_k;\n    string out;\n    out.reserve(200);\n    for(int b=0;b<best_B;b++){\n        int blk = best_k + (b >= best_B - rem ? 1 : 0);\n        char c = path[b % D];\n        for(int t=0;t<blk;t++){\n            out.push_back(c);\n        }\n    }\n    // safety check (should be exactly 200)\n    if((int)out.size() > 200) out.resize(200);\n\n    cout << out << \"\\n\";\n    return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Grid dimensions\nstatic constexpr int H = 30, W = 30;\n// Directions: 0=left,1=up,2=right,3=down\nint di[4]={0,-1,0,1}, dj[4]={-1,0,1,0};\ninline int opp(int d){ return (d+2)&3; }\n\n// to_dir[s][d]: exit side if entering tile\u2010state s from side d, or -1\nstatic const int to_dir[8][4]={\n  { 1, 0,-1,-1},\n  { 3,-1,-1, 0},\n  {-1,-1, 3, 2},\n  {-1, 2, 1,-1},\n  { 1, 0, 3, 2},\n  { 3, 2, 1, 0},\n  { 2,-1, 0,-1},\n  {-1, 3,-1, 1}\n};\n\n// Rotate original tile\u2010state s by r\u00d790\u00b0 CCW\ninline int rotateState(int s,int r){\n  if(s<4)       return (s+r)&3;\n  else if(r&1)  return s^1;\n  else          return s;\n}\n\n// splitmix64 RNG\nstatic uint64_t rnd_state;\ninline uint64_t splitmix64(){\n  uint64_t z=(rnd_state+=0x9e3779b97f4a7c15ULL);\n  z=(z^(z>>30))*0xbf58476d1ce4e5b9ULL;\n  z=(z^(z>>27))*0x94d049bb133111ebULL;\n  return z ^ (z>>31);\n}\ninline double rnd01(){\n  return (splitmix64()>>11)*(1.0/9007199254740992.0);\n}\n\nint main(){\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n\n  rnd_state = chrono::steady_clock::now().time_since_epoch().count();\n\n  // Read input\n  static int orig[H][W];\n  for(int i=0;i<H;i++){\n    string s; cin>>s;\n    for(int j=0;j<W;j++){\n      orig[i][j]=s[j]-'0';\n    }\n  }\n\n  // Precompute open\u2010side masks\n  int openMask[8];\n  for(int s=0;s<8;s++){\n    int m=0;\n    for(int d=0;d<4;d++) if(to_dir[s][d]!=-1) m|=1<<d;\n    openMask[s]=m;\n  }\n\n  auto now = chrono::steady_clock::now;\n  auto t0  = now();\n  const double TOTAL_TIME  = 1.90;\n  const double GREEDY_TIME = 0.20;\n  const double SA_TIME     = TOTAL_TIME - GREEDY_TIME - 0.12; \n  // leave ~0.12s for final hill climb\n\n  static int rot[H][W], bestRot[H][W], curMask[H][W];\n\n  // True\u2010score: product of two longest loops\n  auto computeTrue = [&](){\n    static bool used[H][W][4];\n    memset(used,0,sizeof(used));\n    static int st[H][W];\n    for(int i=0;i<H;i++)for(int j=0;j<W;j++)\n      st[i][j] = rotateState(orig[i][j], rot[i][j]);\n\n    vector<int> loops; loops.reserve(H*W);\n    for(int i=0;i<H;i++)for(int j=0;j<W;j++){\n      for(int d=0;d<4;d++){\n        if(used[i][j][d]) continue;\n        int ex = to_dir[st[i][j]][d];\n        if(ex<0) continue;\n        int ni=i+di[ex], nj=j+dj[ex];\n        if(ni<0||ni>=H||nj<0||nj>=W) continue;\n        if(to_dir[st[ni][nj]][opp(ex)]<0) continue;\n        int si=i,sj=j,sd=d,ci=i,cj=j,cd=d,len=0;\n        while(true){\n          used[ci][cj][cd]=true;\n          int ed=to_dir[st[ci][cj]][cd];\n          if(ed<0) break;\n          int nci=ci+di[ed], ncj=cj+dj[ed];\n          if(nci<0||nci>=H||ncj<0||ncj>=W) break;\n          ci=nci; cj=ncj; cd=opp(ed); len++;\n          if(ci==si&&cj==sj&&cd==sd){\n            loops.push_back(len);\n            break;\n          }\n        }\n      }\n    }\n    if(loops.size()<2) return 0;\n    nth_element(loops.begin(),loops.begin()+1,loops.end(),greater<int>());\n    return loops[0]*loops[1];\n  };\n\n  // Proxy\u2010score: matched edges +2, boundary \u22121\n  auto computeProxy = [&](){\n    int S=0;\n    for(int i=0;i<H;i++)for(int j=0;j<W;j++){\n      int s = rotateState(orig[i][j], rot[i][j]);\n      int m = openMask[s];\n      for(int d=0;d<4;d++) if(m&(1<<d)){\n        int ni=i+di[d], nj=j+dj[d];\n        if(ni>=0&&ni<H&&nj>=0&&nj<W){\n          int s2=rotateState(orig[ni][nj], rot[ni][nj]);\n          if(openMask[s2]&(1<<opp(d))) S+=2;\n        } else {\n          S-=1;\n        }\n      }\n    }\n    return S;\n  };\n\n  // One greedy sweep\n  auto greedy=[&](){\n    for(int i=0;i<H;i++)for(int j=0;j<W;j++){\n      int cur=rot[i][j], bestR=cur, bestSc=INT_MIN;\n      for(int r=0;r<4;r++){\n        int s=rotateState(orig[i][j],r);\n        int m=openMask[s], sc=0;\n        for(int d=0;d<4;d++) if(m&(1<<d)){\n          int ni=i+di[d], nj=j+dj[d];\n          if(ni>=0&&ni<H&&nj>=0&&nj<W){\n            int s2=rotateState(orig[ni][nj],rot[ni][nj]);\n            if(openMask[s2]&(1<<opp(d))) sc+=2;\n          } else sc-=1;\n        }\n        if(sc>bestSc){ bestSc=sc; bestR=r; }\n      }\n      rot[i][j]=bestR;\n    }\n  };\n\n  // 1) Multi\u2010start greedy, seed by true\u2010score\n  int bestTrue=0;\n  int starts=0;\n  while(true){\n    if(starts>0 && chrono::duration<double>(now()-t0).count()>GREEDY_TIME)\n      break;\n    for(int i=0;i<H;i++)for(int j=0;j<W;j++)\n      rot[i][j] = int(splitmix64()&3);\n    greedy(); greedy(); greedy();\n    int ts = computeTrue();\n    if(ts>bestTrue){\n      bestTrue=ts;\n      for(int i=0;i<H;i++)for(int j=0;j<W;j++)\n        bestRot[i][j]=rot[i][j];\n    }\n    if(++starts>=12) break;\n  }\n\n  // 2) Simulated annealing on proxy\n  for(int i=0;i<H;i++)for(int j=0;j<W;j++){\n    rot[i][j]=bestRot[i][j];\n    int s=rotateState(orig[i][j], rot[i][j]);\n    curMask[i][j]=openMask[s];\n  }\n  int curProxy = computeProxy();\n\n  const double T0=3.0, T1=0.1;\n  auto saEnd = t0 + chrono::duration<double>(SA_TIME);\n  uint64_t iter=0, PROBE=(1<<11), CHECK=(1<<9);\n\n  while(true){\n    if((iter& (CHECK-1))==0 && now()>saEnd) break;\n    iter++;\n\n    double frac = min(1.0, chrono::duration<double>(now()-t0).count()/(TOTAL_TIME-GREEDY_TIME));\n    double T = T0*(1-frac)+T1*frac;\n\n    int i=int(splitmix64()%H), j=int(splitmix64()%W);\n    int oldR=rot[i][j];\n    int newR = ((splitmix64()&15)<12\n                ? (oldR + ((splitmix64()&1)?1:3))&3\n                : int(splitmix64()&3));\n    if(newR!=oldR){\n      int oldM=curMask[i][j];\n      int newM=openMask[rotateState(orig[i][j],newR)];\n      int delta=0;\n      for(int d=0;d<4;d++){\n        int oH=(oldM>>d)&1, nH=(newM>>d)&1;\n        int ni=i+di[d], nj=j+dj[d];\n        if(ni>=0&&ni<H&&nj>=0&&nj<W){\n          int nh=(curMask[ni][nj]>>opp(d))&1;\n          if(nh) delta+=2*(nH-oH);\n        } else delta+=(oH-nH);\n      }\n      if(delta>=0 || rnd01()<exp(-double(-delta)/T)){\n        rot[i][j]=newR;\n        curMask[i][j]=newM;\n        curProxy+=delta;\n      }\n    }\n\n    if((iter & (PROBE-1))==0){\n      int ts = computeTrue();\n      if(ts>bestTrue){\n        bestTrue=ts;\n        for(int x=0;x<H;x++)for(int y=0;y<W;y++)\n          bestRot[x][y]=rot[x][y];\n      }\n    }\n  }\n\n  // 3) Final true\u2010score hill\u2010climb (~0.12s)\n  // Copy to rot and hill-climb on true score\n  for(int i=0;i<H;i++)for(int j=0;j<W;j++) rot[i][j]=bestRot[i][j];\n  int curTrue = bestTrue;\n  auto hillEnd = t0 + chrono::duration<double>(TOTAL_TIME);\n  while(chrono::duration<double>(now()-t0).count() < TOTAL_TIME){\n    int i=int(splitmix64()%H), j=int(splitmix64()%W);\n    int oldR=rot[i][j];\n    int newR=int(splitmix64()&3);\n    if(newR==oldR) continue;\n    rot[i][j]=newR;\n    int ts = computeTrue();\n    if(ts > curTrue){\n      curTrue=ts;\n      bestTrue=ts;\n      for(int x=0;x<H;x++)for(int y=0;y<W;y++)\n        bestRot[x][y]=rot[x][y];\n    } else {\n      rot[i][j]=oldR;\n    }\n  }\n\n  // Output bestRot\n  string out; out.reserve(H*W);\n  for(int i=0;i<H;i++){\n    for(int j=0;j<W;j++){\n      out.push_back(char('0'+bestRot[i][j]));\n    }\n  }\n  cout<<out<<\"\\n\";\n  return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\nusing ull = unsigned long long;\n\n// Max N=10 \u21d2 NN\u2264100\nstatic int G0[100], G[100], bestG[100];\nint N, NN, T;\n\n// Directions: U,D,L,R\nstatic const int  dx[4]   = {-1, +1,  0,  0};\nstatic const int  dy[4]   = { 0,  0, -1, +1};\nstatic const char DIRC[4] = {'U','D','L','R'};\nstatic const int  rev[4]  = {1,0,3,2};\n\n// BFS\u2010neighbors for tree\u2010size (no DSU)\nstruct BFSNei { uint8_t to, mu, mv; };\nstatic BFSNei bfs_nei[100][4];\nstatic uint8_t degBE[100];\n\n// Slide\u2010neighbors for the empty\u2010tile\nstruct Slide { uint8_t d,to; };\nstatic Slide slide_nei[100][4];\nstatic uint8_t degSN[100];\n\n// Tiny xorshift RNG\nstatic ull rng_state;\ninline ull xorshift64(){\n    ull x=rng_state;\n    x^=x<<13; x^=x>>7; x^=x<<17;\n    return rng_state=x;\n}\n\n// Compute S = size of largest acyclic component (excluding empty_pos)\ninline int compute_best_tree(int empty_pos){\n    static bool vis[100];\n    memset(vis,0,NN);\n    int best=0, Q[100], qh, qt;\n    for(int i=0;i<NN;i++){\n        if(i==empty_pos||G[i]==0||vis[i]) continue;\n        vis[i]=true; qh=0; qt=0; Q[qt++]=i;\n        int nodes=0, edge2=0;\n        while(qh<qt){\n            int u=Q[qh++];\n            nodes++;\n            for(int k=0;k<degBE[u];k++){\n                auto &e=bfs_nei[u][k];\n                int v=e.to;\n                if((G[u]&e.mu)&&(G[v]&e.mv)){\n                    edge2++;\n                    if(!vis[v]){\n                        vis[v]=true;\n                        Q[qt++]=v;\n                    }\n                }\n            }\n        }\n        int edges = edge2>>1;\n        if(edges==nodes-1) best = max(best,nodes);\n    }\n    return best;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin>>N>>T;\n    NN=N*N;\n    int empty0=-1;\n    for(int i=0;i<N;i++){\n        string s; cin>>s;\n        for(int j=0;j<N;j++){\n            char c=s[j];\n            int v = (c<='9'?c-'0':c-'a'+10);\n            int idx=i*N+j;\n            G0[idx]=v;\n            if(v==0) empty0=idx;\n        }\n    }\n\n    // Precompute BFS\u2010neighbors (up/down/left/right)\n    for(int pos=0;pos<NN;pos++){\n        int r=pos/N, c=pos%N, cnt=0;\n        if(r>0)     bfs_nei[pos][cnt++]={uint8_t(pos-N),   2,8};\n        if(r+1<N)   bfs_nei[pos][cnt++]={uint8_t(pos+N),   8,2};\n        if(c>0)     bfs_nei[pos][cnt++]={uint8_t(pos-1),   1,4};\n        if(c+1<N)   bfs_nei[pos][cnt++]={uint8_t(pos+1),   4,1};\n        degBE[pos]=cnt;\n    }\n    // Precompute slide\u2010neighbors for empty\u2010tile\n    for(int pos=0;pos<NN;pos++){\n        int r=pos/N, c=pos%N, cnt=0;\n        if(r>0)     slide_nei[pos][cnt++]={0, uint8_t(pos-N)};\n        if(r+1<N)   slide_nei[pos][cnt++]={1, uint8_t(pos+N)};\n        if(c>0)     slide_nei[pos][cnt++]={2, uint8_t(pos-1)};\n        if(c+1<N)   slide_nei[pos][cnt++]={3, uint8_t(pos+1)};\n        degSN[pos]=cnt;\n    }\n\n    // Seed RNG\n    rng_state = (ull)chrono::steady_clock::now()\n                  .time_since_epoch().count();\n\n    // Compute original score\n    memcpy(G,G0,NN*sizeof(int));\n    int origS = compute_best_tree(empty0);\n\n    // Best\u2010ever globals\n    int bestS = origS, bestEmpty = empty0;\n    memcpy(bestG, G0, NN*sizeof(int));\n    string bestMoves=\"\";\n\n    // Timer\n    auto T0 = chrono::steady_clock::now();\n    auto elapsed = [&](){\n        return chrono::duration<double,milli>(\n            chrono::steady_clock::now() - T0\n        ).count();\n    };\n    const double TL = 2950.0;\n    const double NEG_START = 0.30, NEG_END = 0.01;\n\n    // Multi\u2010restart: greedy1 + greedy2 + SA\n    while(elapsed() < TL){\n        memcpy(G,G0,NN*sizeof(int));\n        int epos = empty0, curS = origS;\n        string curMoves; curMoves.reserve(T);\n\n        // GREEDY 1\u2010STEP\n        while(elapsed()<TL && curMoves.size()< (size_t)T){\n            int bS=curS, bD=-1, bTo=-1;\n            int dcount=degSN[epos];\n            for(int i=0;i<dcount;i++){\n                auto &mv=slide_nei[epos][i];\n                int d=mv.d, to=mv.to;\n                swap(G[epos],G[to]);\n                int s2=compute_best_tree(to);\n                swap(G[epos],G[to]);\n                if(s2>bS){\n                    bS=s2; bD=d; bTo=to;\n                }\n            }\n            if(bD<0) break;\n            swap(G[epos],G[bTo]);\n            epos=bTo; curMoves.push_back(DIRC[bD]);\n            curS=bS;\n            if(curS>bestS){\n                bestS=curS; bestEmpty=epos;\n                bestMoves=curMoves;\n                memcpy(bestG,G,NN*sizeof(int));\n                if(bestS==NN-1) break;\n            }\n        }\n        if(bestS==NN-1) break;\n\n        // GREEDY 2\u2010STEP\n        while(elapsed()<TL && curMoves.size()+2 <= (size_t)T){\n            int bS=curS, bd1=-1, bd2=-1, t1=-1, t2=-1;\n            int dcount1=degSN[epos];\n            for(int i1=0;i1<dcount1;i1++){\n                auto &mv1=slide_nei[epos][i1];\n                int d1=mv1.d, to1=mv1.to;\n                swap(G[epos],G[to1]);\n                int dcount2=degSN[to1];\n                for(int i2=0;i2<dcount2;i2++){\n                    auto &mv2=slide_nei[to1][i2];\n                    int d2=mv2.d, to2=mv2.to;\n                    if(d2==rev[d1]) continue;\n                    swap(G[to1],G[to2]);\n                    int s3=compute_best_tree(to2);\n                    swap(G[to1],G[to2]);\n                    if(s3>bS){\n                        bS=s3; bd1=d1; bd2=d2; t1=to1; t2=to2;\n                    }\n                }\n                swap(G[epos],G[to1]);\n            }\n            if(bd1<0) break;\n            swap(G[epos],G[t1]);\n            epos=t1; curMoves.push_back(DIRC[bd1]);\n            swap(G[epos],G[t2]);\n            epos=t2; curMoves.push_back(DIRC[bd2]);\n            curS=bS;\n            if(curS>bestS){\n                bestS=curS; bestEmpty=epos;\n                bestMoves=curMoves;\n                memcpy(bestG,G,NN*sizeof(int));\n                if(bestS==NN-1) break;\n            }\n        }\n        if(bestS==NN-1) break;\n\n        // SIMULATED ANNEALING\n        int used=(int)curMoves.size(), remain=T-used;\n        int acceptedCnt=0, last_dir=-1;\n        for(int iter=0; acceptedCnt<remain && elapsed()<TL; iter++){\n            int d,to;\n            int dcount=degSN[epos];\n            do{\n                int idx=int(xorshift64()%dcount);\n                d = slide_nei[epos][idx].d;\n                to= slide_nei[epos][idx].to;\n            }while(d==rev[last_dir]);\n            swap(G[epos],G[to]);\n            int s2=compute_best_tree(to), delta=s2-curS;\n            bool ac=false;\n            if(delta>=0){\n                ac=true;\n            } else {\n                double tfrac=elapsed()/TL;\n                double p = NEG_START*(1-tfrac)+NEG_END*tfrac;\n                if(int(xorshift64()%1000) < int(p*1000)) ac=true;\n            }\n            if(ac){\n                epos=to; curS=s2;\n                curMoves.push_back(DIRC[d]);\n                last_dir=d; acceptedCnt++;\n                if(curS>bestS){\n                    bestS=curS; bestEmpty=epos;\n                    bestMoves=curMoves;\n                    memcpy(bestG,G,NN*sizeof(int));\n                    if(bestS==NN-1) break;\n                }\n            } else {\n                swap(G[epos],G[to]);\n            }\n        }\n        if(bestS==NN-1) break;\n    }\n\n    // FINAL POLISH on best ever\n    {\n        memcpy(G,bestG,NN*sizeof(int));\n        int epos=bestEmpty, curS=bestS;\n        string curMoves=bestMoves;\n\n        // greedy1\n        while(curMoves.size()<T && elapsed()<TL){\n            int bS=curS, bD=-1, bTo=-1;\n            int dcount=degSN[epos];\n            for(int i=0;i<dcount;i++){\n                auto &mv=slide_nei[epos][i];\n                int d=mv.d, to=mv.to;\n                swap(G[epos],G[to]);\n                int s2=compute_best_tree(to);\n                swap(G[epos],G[to]);\n                if(s2>bS){\n                    bS=s2; bD=d; bTo=to;\n                }\n            }\n            if(bD<0) break;\n            swap(G[epos],G[bTo]);\n            epos=bTo; curMoves.push_back(DIRC[bD]);\n            curS=bS;\n        }\n\n        // greedy2\n        while(curMoves.size()+2<=T && elapsed()<TL){\n            int bS=curS, bd1=-1, bd2=-1, t1=-1, t2=-1;\n            int dcount1=degSN[epos];\n            for(int i1=0;i1<dcount1;i1++){\n                auto &mv1=slide_nei[epos][i1];\n                int d1=mv1.d, to1=mv1.to;\n                swap(G[epos],G[to1]);\n                int dcount2=degSN[to1];\n                for(int i2=0;i2<dcount2;i2++){\n                    auto &mv2=slide_nei[to1][i2];\n                    int d2=mv2.d, to2=mv2.to;\n                    if(d2==rev[d1]) continue;\n                    swap(G[to1],G[to2]);\n                    int s3=compute_best_tree(to2);\n                    swap(G[to1],G[to2]);\n                    if(s3>bS){\n                        bS=s3; bd1=d1; bd2=d2; t1=to1; t2=to2;\n                    }\n                }\n                swap(G[epos],G[to1]);\n            }\n            if(bd1<0) break;\n            swap(G[epos],G[t1]);\n            epos=t1; curMoves.push_back(DIRC[bd1]);\n            swap(G[epos],G[t2]);\n            epos=t2; curMoves.push_back(DIRC[bd2]);\n            curS=bS;\n        }\n\n        if(curS>bestS){\n            bestMoves = curMoves;\n        }\n    }\n\n    // truncate just in case\n    if((int)bestMoves.size()>T)\n        bestMoves.resize(T);\n    cout<<bestMoves<<\"\\n\";\n    return 0;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstatic const int OFF      = 10000;\nstatic const int D1_OFF   = 20000;  // for x+y and x\u2212y\nstatic const int D3_OFF   = 30000;  // for y\u22122x\nstatic const int D4_OFF   = 30000;  // for 2y+x\nstatic const int MAX_CAND = 80;\n\nstruct Straw { int x, y, d1, d2, d3, d4; };\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, K;\n    cin >> N >> K;\n    vector<int> a(11);\n    for(int d = 1; d <= 10; d++) cin >> a[d];\n\n    // 1) Read strawberries, build marks & sorted coord\u2010lists\n    vector<Straw> P(N);\n    vector<int> xs(N), ys(N), ds1(N), ds2(N), ds3(N), ds4(N);\n    vector<bool> xmark(2*OFF+1,false),  ymark(2*OFF+1,false),\n                 d1mark(2*D1_OFF+1,false), d2mark(2*D1_OFF+1,false),\n                 d3mark(2*D3_OFF+1,false), d4mark(2*D4_OFF+1,false);\n    for(int i = 0; i < N; i++){\n        int x, y;\n        cin >> x >> y;\n        int d1 = x + y;\n        int d2 = x - y;\n        int d3 = y - 2*x;\n        int d4 = 2*y + x;\n        P[i] = {x,y,d1,d2,d3,d4};\n        xs[i] = x; ys[i] = y;\n        ds1[i]=d1; ds2[i]=d2;\n        ds3[i]=d3; ds4[i]=d4;\n        if(-OFF<=x&&x<=OFF)       xmark[x+OFF]=true;\n        if(-OFF<=y&&y<=OFF)       ymark[y+OFF]=true;\n        if(-D1_OFF<=d1&&d1<=D1_OFF) d1mark[d1+D1_OFF]=true;\n        if(-D1_OFF<=d2&&d2<=D1_OFF) d2mark[d2+D1_OFF]=true;\n        if(-D3_OFF<=d3&&d3<=D3_OFF) d3mark[d3+D3_OFF]=true;\n        if(-D4_OFF<=d4&&d4<=D4_OFF) d4mark[d4+D4_OFF]=true;\n    }\n    sort(xs.begin(), xs.end());\n    sort(ys.begin(), ys.end());\n    sort(ds1.begin(), ds1.end());\n    sort(ds2.begin(), ds2.end());\n    sort(ds3.begin(), ds3.end());\n    sort(ds4.begin(), ds4.end());\n\n    // find a \u201csafe\u201d integer not slicing through any strawberry\n    auto find_safe = [&](int tgt, const vector<bool>& mark, int off){\n        for(int d=0; d<=2*off; d++){\n            int c1 = tgt - d;\n            if(c1>=-off && c1<=off && !mark[c1+off]) return c1;\n            int c2 = tgt + d;\n            if(c2>=-off && c2<=off && !mark[c2+off]) return c2;\n        }\n        return tgt;\n    };\n\n    // 2) Poisson\u2010approx over all (v,h) with v+h\u2264K, v,h\u22651\n    struct Cand{ double sc; int v,h; };\n    vector<Cand> approx;\n    approx.reserve(K*K/2);\n    for(int v = 1; v < K; v++){\n        int hmax = K - v;\n        for(int h = 1; h <= hmax; h++){\n            int M = (v+1)*(h+1);\n            double lam = double(N)/double(M);\n            double p0 = exp(-lam), pd = p0, sc = 0;\n            for(int d = 1; d <= 10; d++){\n                pd *= lam/d;           // Poisson P(d;lam)\n                sc += min<double>(a[d], pd * M);\n            }\n            approx.push_back({sc,v,h});\n        }\n    }\n    if((int)approx.size() > MAX_CAND){\n        nth_element(\n            approx.begin(), approx.begin()+MAX_CAND, approx.end(),\n            [](auto &A, auto &B){ return A.sc > B.sc; }\n        );\n        approx.resize(MAX_CAND);\n    }\n    sort(approx.begin(), approx.end(),\n         [](auto &A, auto &B){ return A.sc > B.sc; }\n    );\n\n    // 3) Precompute quantile\u2010cuts on each of the six axes\n    vector<vector<int>> qvx(K+1), qvy(K+1),\n                       qd1(K+1), qd2(K+1),\n                       qd3(K+1), qd4(K+1);\n    for(int v = 1; v <= K; v++){\n        if(v+1 > N) break;\n        qvx[v].reserve(v);\n        qd1[v].reserve(v);\n        qd3[v].reserve(v);\n        for(int j = 1; j <= v; j++){\n            int idx = j*N/(v+1);\n            // x\n            {\n                int lx=xs[idx-1], hx=xs[idx];\n                qvx[v].push_back(find_safe((lx+hx)/2, xmark, OFF));\n            }\n            // x+y\n            {\n                int l1=ds1[idx-1], h1=ds1[idx];\n                qd1[v].push_back(find_safe((l1+h1)/2, d1mark, D1_OFF));\n            }\n            // y\u22122x\n            {\n                int l3=ds3[idx-1], h3=ds3[idx];\n                qd3[v].push_back(find_safe((l3+h3)/2, d3mark, D3_OFF));\n            }\n        }\n        sort(qvx[v].begin(), qvx[v].end());\n        sort(qd1[v].begin(), qd1[v].end());\n        sort(qd3[v].begin(), qd3[v].end());\n    }\n    for(int h = 1; h <= K; h++){\n        if(h+1 > N) break;\n        qvy[h].reserve(h);\n        qd2[h].reserve(h);\n        qd4[h].reserve(h);\n        for(int j = 1; j <= h; j++){\n            int idx = j*N/(h+1);\n            // y\n            {\n                int ly=ys[idx-1], hy=ys[idx];\n                qvy[h].push_back(find_safe((ly+hy)/2, ymark, OFF));\n            }\n            // x\u2212y\n            {\n                int l2=ds2[idx-1], h2=ds2[idx];\n                qd2[h].push_back(find_safe((l2+h2)/2, d2mark, D1_OFF));\n            }\n            // 2y+x\n            {\n                int l4=ds4[idx-1], h4=ds4[idx];\n                qd4[h].push_back(find_safe((l4+h4)/2, d4mark, D4_OFF));\n            }\n        }\n        sort(qvy[h].begin(), qvy[h].end());\n        sort(qd2[h].begin(), qd2[h].end());\n        sort(qd4[h].begin(), qd4[h].end());\n    }\n\n    // 4) Precompute uniform\u2010spaced cuts on each axis\n    auto build_uniform = [&](int steps,\n                             const vector<bool>& mark,\n                             int off){\n        vector<int> out;\n        if(steps <= 1) return out;\n        out.reserve(steps-1);\n        for(int j = 1; j < steps; j++){\n            double raw = -double(off) + (2.0*off*j)/double(steps);\n            int tgt = int(round(raw));\n            out.push_back(find_safe(tgt, mark, off));\n        }\n        sort(out.begin(), out.end());\n        return out;\n    };\n    vector<vector<int>> uvx(K+1), uvy(K+1),\n                        uvd1(K+1), uvd2(K+1),\n                        uvd3(K+1), uvd4(K+1);\n    for(int i = 0; i <= K; i++){\n        uvx[i]  = build_uniform(i+1, xmark,  OFF);\n        uvy[i]  = build_uniform(i+1, ymark,  OFF);\n        uvd1[i] = build_uniform(i+1, d1mark, D1_OFF);\n        uvd2[i] = build_uniform(i+1, d2mark, D1_OFF);\n        uvd3[i] = build_uniform(i+1, d3mark, D3_OFF);\n        uvd4[i] = build_uniform(i+1, d4mark, D4_OFF);\n    }\n\n    // 5) Exact\u2010evaluation routines\n    vector<int> cnt;\n    auto eval_cart = [&](int v,int h,\n                         const vector<int>& vx,\n                         const vector<int>& vy){\n        int C=v+1, R=h+1, M=C*R;\n        cnt.assign(M,0);\n        for(auto &s: P){\n            int cx = int(lower_bound(vx.begin(),vx.end(), s.x) - vx.begin());\n            int cy = int(lower_bound(vy.begin(),vy.end(), s.y) - vy.begin());\n            cnt[cy*C + cx]++;\n        }\n        ll sum = 0;\n        int bd[11]={};\n        for(int i=0;i<M;i++){\n            int c = cnt[i];\n            if(1<=c&&c<=10) bd[c]++;\n        }\n        for(int d=1; d<=10; d++) sum += min<ll>(a[d], bd[d]);\n        return sum;\n    };\n    auto eval_diag45 = [&](int v,int h,\n                           const vector<int>& c1,\n                           const vector<int>& c2){\n        int C=v+1, R=h+1, M=C*R;\n        cnt.assign(M,0);\n        for(auto &s: P){\n            int d1 = s.x + s.y;\n            int d2 = s.x - s.y;\n            int cx = int(lower_bound(c1.begin(),c1.end(),d1)-c1.begin());\n            int cy = int(lower_bound(c2.begin(),c2.end(),d2)-c2.begin());\n            cnt[cy*C + cx]++;\n        }\n        ll sum=0; int bd[11]={};\n        for(int i=0;i<M;i++){\n            int c=cnt[i];\n            if(1<=c&&c<=10) bd[c]++;\n        }\n        for(int d=1; d<=10; d++) sum += min<ll>(a[d], bd[d]);\n        return sum;\n    };\n    auto eval_diag63 = [&](int v,int h,\n                           const vector<int>& c3,\n                           const vector<int>& c4){\n        int C=v+1, R=h+1, M=C*R;\n        cnt.assign(M,0);\n        for(auto &s: P){\n            int d3 = s.y - 2*s.x;\n            int d4 = 2*s.y + s.x;\n            int cx = int(lower_bound(c3.begin(),c3.end(),d3)-c3.begin());\n            int cy = int(lower_bound(c4.begin(),c4.end(),d4)-c4.begin());\n            cnt[cy*C + cx]++;\n        }\n        ll sum=0; int bd[11]={};\n        for(int i=0;i<M;i++){\n            int c=cnt[i];\n            if(1<=c&&c<=10) bd[c]++;\n        }\n        for(int d=1; d<=10; d++) sum += min<ll>(a[d], bd[d]);\n        return sum;\n    };\n\n    // 6) Scan top MAX_CAND candidates under **6** layouts:\n    //    U\u00d7U, Q\u00d7Q, Q\u00d7U, U\u00d7Q, diag45(Q\u00d7Q), diag63(Q\u00d7Q)\n    ll bestSum = -1;\n    int bestV = 1, bestH = 1, bestMode = 0;\n    vector<int> bestX, bestY;\n\n    for(auto &C: approx){\n        int v = C.v, h = C.h;\n        auto &ux = uvx[v], &uy = uvy[h];\n        auto &u1 = uvd1[v],&u2 = uvd2[h];\n        auto &qX = qvx[v], &qY = qvy[h];\n        auto &qD1= qd1[v], &qD2= qd2[h];\n        auto &q3 = qd3[v], &q4 = qd4[h];\n        bool cQx = (int)qX.size()==v;\n        bool cQy = (int)qY.size()==h;\n        bool can45 = cQx&&cQy && (int)qD1.size()==v && (int)qD2.size()==h;\n        bool can63 = cQx&&cQy && (int)q3.size()==v && (int)q4.size()==h;\n\n        // 0) Uniform\u00d7Uniform\n        {\n            ll s = eval_cart(v,h, ux,uy);\n            if(s>bestSum){\n                bestSum=s; bestMode=0; bestV=v; bestH=h;\n                bestX=ux; bestY=uy;\n            }\n        }\n        // 1) Quantile\u00d7Quantile\n        if(cQx&&cQy){\n            ll s = eval_cart(v,h, qX,qY);\n            if(s>bestSum){\n                bestSum=s; bestMode=1;\n                bestX=qX; bestY=qY;\n            }\n        }\n        // 2) Quantile(x)\u00d7Uniform(y)\n        if(cQx){\n            ll s = eval_cart(v,h, qX,uy);\n            if(s>bestSum){\n                bestSum=s; bestMode=2;\n                bestX=qX; bestY=uy;\n            }\n        }\n        // 3) Uniform(x)\u00d7Quantile(y)\n        if(cQy){\n            ll s = eval_cart(v,h, ux,qY);\n            if(s>bestSum){\n                bestSum=s; bestMode=3;\n                bestX=ux; bestY=qY;\n            }\n        }\n        // 4) diag45 quantile\u00d7quantile\n        if(can45){\n            ll s = eval_diag45(v,h, qD1,qD2);\n            if(s>bestSum){\n                bestSum=s; bestMode=4;\n                bestX=qD1; bestY=qD2;\n            }\n        }\n        // 5) diag63 quantile\u00d7quantile\n        if(can63){\n            ll s = eval_diag63(v,h, q3,q4);\n            if(s>bestSum){\n                bestSum=s; bestMode=5;\n                bestX=q3; bestY=q4;\n            }\n        }\n    }\n\n    // 7) Local (v\u00b11,h\u22131),(v\u00b12,h\u22132) tweak **for that single bestMode**\n    for(int dV = -2; dV <= 2; dV++){\n        if(dV==0) continue;\n        int v2 = bestV + dV;\n        int h2 = bestH - dV;\n        if(v2 < 1 || h2 < 1 || v2 + h2 > K) continue;\n\n        auto &ux2 = uvx[v2], &uy2 = uvy[h2];\n        auto &qX2 = qvx[v2], &qY2 = qvy[h2];\n        auto &qD12= qd1[v2],&qD22= qd2[h2];\n        auto &q32 = qd3[v2], &q42 = qd4[h2];\n        bool cQx2 = (int)qX2.size()==v2;\n        bool cQy2 = (int)qY2.size()==h2;\n        bool can452 = cQx2&&cQy2 && (int)qD12.size()==v2 && (int)qD22.size()==h2;\n        bool can632 = cQx2&&cQy2 && (int)q32.size()==v2 && (int)q42.size()==h2;\n\n        ll s = -1;\n        switch(bestMode){\n        case 0:  s = eval_cart(v2,h2, ux2,uy2); break;\n        case 1:  if(cQx2&&cQy2) s = eval_cart(v2,h2, qX2,qY2); break;\n        case 2:  if(cQx2)       s = eval_cart(v2,h2, qX2,uy2); break;\n        case 3:  if(cQy2)       s = eval_cart(v2,h2, ux2,qY2); break;\n        case 4:  if(can452)     s = eval_diag45(v2,h2,qD12,qD22); break;\n        case 5:  if(can632)     s = eval_diag63(v2,h2,   q32,  q42); break;\n        }\n        if(s > bestSum){\n            bestSum = s;\n            bestV = v2;\n            bestH = h2;\n            switch(bestMode){\n            case 0:\n                bestX = ux2;  bestY = uy2;  break;\n            case 1:\n                bestX = qX2;  bestY = qY2;  break;\n            case 2:\n                bestX = qX2;  bestY = uy2;  break;\n            case 3:\n                bestX = ux2;  bestY = qY2;  break;\n            case 4:\n                bestX = qD12; bestY = qD22; break;\n            case 5:\n                bestX = q32;  bestY = q42;  break;\n            }\n        }\n    }\n\n    // 8) Emit up to K cuts (two integer endpoints each)\n    int printed = 0;\n    if(bestMode < 4){\n        // axis\u2010aligned x=c and y=c\n        int total = bestX.size() + bestY.size();\n        int k = min(total, K);\n        cout << k << \"\\n\";\n        for(int c: bestX){\n            if(printed>=k) break;\n            cout << c << \" \" << -2*OFF << \"   \"\n                 << c << \" \" <<  2*OFF << \"\\n\";\n            printed++;\n        }\n        for(int c: bestY){\n            if(printed>=k) break;\n            cout << -2*OFF << \" \" << c << \"   \"\n                 <<  2*OFF << \" \" << c << \"\\n\";\n            printed++;\n        }\n    } else if(bestMode == 4){\n        // diagonal 45\u00b0: x+y=c and x\u2212y=c\n        int total = bestX.size() + bestY.size();\n        int k = min(total, K);\n        cout << k << \"\\n\";\n        const ll S = 2LL*OFF;\n        for(int c: bestX){\n            if(printed>=k) break;\n            cout << (c+S) << \" \" << -S << \"   \"\n                 << -S      << \" \" << (c+S) << \"\\n\";\n            printed++;\n        }\n        for(int c: bestY){\n            if(printed>=k) break;\n            cout << (c+S) << \" \" <<  S << \"   \"\n                 << (c-S) << \" \" << -S << \"\\n\";\n            printed++;\n        }\n    } else {\n        // diagonal 63\u00b0: y-2x=c and 2y+x=c\n        int total = bestX.size() + bestY.size();\n        int k = min(total, K);\n        cout << k << \"\\n\";\n        for(int c: bestX){\n            if(printed>=k) break;\n            // y-2x=c  => (0,c)-(1,c+2)\n            cout << 0 << \" \" << c << \"   \"\n                 << 1 << \" \" << (c+2) << \"\\n\";\n            printed++;\n        }\n        for(int c: bestY){\n            if(printed>=k) break;\n            // 2y+x=c => (c,0)-(c-2,1)\n            cout << c << \" \" << 0 << \"   \"\n                 << (c-2) << \" \" << 1 << \"\\n\";\n            printed++;\n        }\n    }\n\n    return 0;\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// One rectangle operation\nstruct Op {\n    int x1,y1, x2,y2, x3,y3, x4,y4;\n};\n\n// fast splitmix64\nstatic uint64_t rng_state;\ninline uint64_t rnd() {\n    uint64_t z = (rng_state += 0x9e3779b97f4a7c15ULL);\n    z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;\n    z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;\n    return z ^ (z >> 31);\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    cin >> N >> M;\n\n    // Read initial seeds\n    vector<pair<int,int>> seeds(M);\n    for(int i = 0; i < M; i++){\n        cin >> seeds[i].first >> seeds[i].second;\n    }\n\n    // Precompute weights w(x,y) = (x-c)^2+(y-c)^2+1\n    int C = (N-1)/2;\n    static ll wgt[62][62];\n    for(int x = 0; x < N; x++){\n        for(int y = 0; y < N; y++){\n            ll dx = x - C, dy = y - C;\n            wgt[x][y] = dx*dx + dy*dy + 1;\n        }\n    }\n\n    // Sort seeds by descending weight\n    sort(seeds.begin(), seeds.end(),\n         [&](auto &A, auto &B){\n             return wgt[A.first][A.second] > wgt[B.first][B.second];\n         });\n\n    // Build (1<<L)-1 masks\n    static uint64_t mask_len[62];\n    mask_len[0] = 0;\n    for(int i = 1; i <= N; i++){\n        mask_len[i] = (1ULL<<i) - 1;\n    }\n\n    // Occupancy & edge\u2010used masks\n    static uint64_t dot_row[62]={}, dot_col[62]={};\n    static uint64_t used_h[62]={}, used_v[62]={};\n\n    // Flatten into E_x/E_y, kept sorted by descending weight\n    static int E_x[4000], E_y[4000];\n    int Esz = M;\n    for(int i = 0; i < M; i++){\n        int x = seeds[i].first, y = seeds[i].second;\n        E_x[i] = x;  E_y[i] = y;\n        dot_row[y] |= (1ULL<<x);\n        dot_col[x] |= (1ULL<<y);\n    }\n\n    // RNG seed\n    rng_state = chrono::steady_clock::now().time_since_epoch().count();\n    const double TL = 4.8;\n    auto t0 = chrono::steady_clock::now();\n\n    vector<Op> ops;\n    ops.reserve(N*N);\n\n    while(true){\n        // time check\n        double elapsed = chrono::duration<double>(\n            chrono::steady_clock::now() - t0).count();\n        if(elapsed > TL) break;\n        if(Esz < 2) break;\n\n        // fixed number of samples\n        const int T = 2000;\n        // frontier size\n        int H = min(Esz, 600);\n\n        ll bestW = -1;\n        Op bestOp{};\n        bool timed_out = false;\n\n        for(int t = 0; t < T; t++){\n            // every so often check time\n            if((t & 255) == 0){\n                if(chrono::duration<double>(\n                   chrono::steady_clock::now() - t0).count() > TL){\n                    timed_out = true;\n                    break;\n                }\n            }\n\n            // pick corners: 50% exploit vs. 50% explore\n            int i,j;\n            if((rnd() & 1) == 0){\n                // exploit: both from top\u2010H\n                i = rnd() % H;\n                j = rnd() % H;\n            } else {\n                // explore: one from top\u2010H, one uniform\n                i = rnd() % H;\n                j = rnd() % Esz;\n            }\n            if(i == j) continue;\n\n            int x2 = E_x[i], y2 = E_y[i];\n            int x4 = E_x[j], y4 = E_y[j];\n            if(x2 == x4 || y2 == y4) continue;  // must be diagonal\n\n            // bounding box\n            int xa = min(x2,x4), xb = max(x2,x4);\n            int ya = min(y2,y4), yb = max(y2,y4);\n            int Lh = xb - xa, Lv = yb - ya;\n            uint64_t he = mask_len[Lh] << xa;\n            uint64_t hi = (Lh>1 ? mask_len[Lh-1] << (xa+1) : 0ULL);\n            uint64_t ve = mask_len[Lv] << ya;\n            uint64_t vi = (Lv>1 ? mask_len[Lv-1] << (ya+1) : 0ULL);\n\n            // OPTION 1: new=(x4,y2), opp=(x2,y4)\n            {\n                int x1 = x4, y1 = y2, x3 = x2, y3 = y4;\n                ll w = wgt[x1][y1];\n                if(w > bestW\n                && ((dot_row[y1]>>x1)&1)==0\n                && ((dot_row[y3]>>x3)&1)==1\n                && (used_h[y2]&he)==0 && (dot_row[y2]&hi)==0\n                && (used_v[x2]&ve)==0 && (dot_col[x2]&vi)==0\n                && (used_h[y4]&he)==0 && (dot_row[y4]&hi)==0\n                && (used_v[x4]&ve)==0 && (dot_col[x4]&vi)==0)\n                {\n                    bestW = w;\n                    bestOp = {x1,y1, x2,y2, x3,y3, x4,y4};\n                }\n            }\n\n            // OPTION 2: new=(x2,y4), opp=(x4,y2)\n            {\n                int x1 = x2, y1 = y4, x3 = x4, y3 = y2;\n                ll w = wgt[x1][y1];\n                if(w > bestW\n                && ((dot_row[y1]>>x1)&1)==0\n                && ((dot_row[y3]>>x3)&1)==1\n                && (used_h[y4]&he)==0 && (dot_row[y4]&hi)==0\n                && (used_v[x2]&ve)==0 && (dot_col[x2]&vi)==0\n                && (used_h[y2]&he)==0 && (dot_row[y2]&hi)==0\n                && (used_v[x4]&ve)==0 && (dot_col[x4]&vi)==0)\n                {\n                    bestW = w;\n                    bestOp = {x1,y1, x2,y2, x3,y3, x4,y4};\n                }\n            }\n        }\n        if(timed_out) break;\n        if(bestW < 0) break;\n\n        // commit bestOp\n        int x1 = bestOp.x1, y1 = bestOp.y1;\n        int x2 = bestOp.x2, y2 = bestOp.y2;\n        int x4 = bestOp.x4, y4 = bestOp.y4;\n\n        // 1) place new dot\n        dot_row[y1] |= (1ULL<<x1);\n        dot_col[x1] |= (1ULL<<y1);\n\n        // 2) insert into E_x/E_y by weight\n        ll Wnew = bestW;\n        int lo = 0, hi = Esz;\n        while(lo < hi){\n            int mid = (lo+hi)>>1;\n            if(wgt[E_x[mid]][E_y[mid]] < Wnew) hi = mid;\n            else lo = mid+1;\n        }\n        for(int k = Esz; k > lo; k--){\n            E_x[k] = E_x[k-1];\n            E_y[k] = E_y[k-1];\n        }\n        E_x[lo] = x1;  E_y[lo] = y1;\n        Esz++;\n\n        // 3) mark the four sides used\n        {\n            int xa2 = min(x2,x4), xb2 = max(x2,x4);\n            int ya2 = min(y2,y4), yb2 = max(y2,y4);\n            int Lh2 = xb2 - xa2, Lv2 = yb2 - ya2;\n            uint64_t mhe = mask_len[Lh2] << xa2;\n            uint64_t mve = mask_len[Lv2] << ya2;\n            used_h[y2] |= mhe;\n            used_h[y4] |= mhe;\n            used_v[x2] |= mve;\n            used_v[x4] |= mve;\n        }\n\n        ops.push_back(bestOp);\n    }\n\n    // output\n    cout << ops.size() << \"\\n\";\n    for(auto &o: ops){\n        cout << o.x1<<\" \"<<o.y1<<\" \"\n             << o.x2<<\" \"<<o.y2<<\" \"\n             << o.x3<<\" \"<<o.y3<<\" \"\n             << o.x4<<\" \"<<o.y4<<\"\\n\";\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\n\nstatic const int N = 10;\nstatic const int di[4] = {-1,1,0,0}, dj[4] = {0,0,-1,1};\n\n// tilt a 10\u00d710 grid in dir \u2208 {'F','B','L','R'}\ninline void tilt(const int in_[N][N], int out_[N][N], char dir){\n    static int buf[N];\n    if(dir=='F'){\n        for(int j=0;j<N;j++){\n            int m=0;\n            for(int i=0;i<N;i++) if(in_[i][j]) buf[m++]=in_[i][j];\n            for(int i=0;i<N;i++) out_[i][j] = (i<m ? buf[i] : 0);\n        }\n    } else if(dir=='B'){\n        for(int j=0;j<N;j++){\n            int m=0;\n            for(int i=N-1;i>=0;i--) if(in_[i][j]) buf[m++]=in_[i][j];\n            for(int i=N-1,k=0;i>=0;i--,k++) out_[i][j] = (k<m ? buf[k] : 0);\n        }\n    } else if(dir=='L'){\n        for(int i=0;i<N;i++){\n            int m=0;\n            for(int j=0;j<N;j++) if(in_[i][j]) buf[m++]=in_[i][j];\n            for(int j=0;j<N;j++) out_[i][j] = (j<m ? buf[j] : 0);\n        }\n    } else { // 'R'\n        for(int i=0;i<N;i++){\n            int m=0;\n            for(int j=N-1;j>=0;j--) if(in_[i][j]) buf[m++]=in_[i][j];\n            for(int j=N-1,k=0;j>=0;j--,k++) out_[i][j] = (k<m ? buf[k] : 0);\n        }\n    }\n}\n\n// compute global \u2211(component_size)^2 on g\ninline int calcConnAll(const int g[N][N]){\n    static bool vis[N][N];\n    memset(vis,0,sizeof(vis));\n    int total=0;\n    static int qx[N*N], qy[N*N];\n    for(int i=0;i<N;i++) for(int j=0;j<N;j++){\n        if(g[i][j] && !vis[i][j]){\n            int f=g[i][j], head=0, tail=0;\n            vis[i][j]=true;\n            qx[tail]=i; qy[tail]=j; tail++;\n            while(head<tail){\n                int x=qx[head], y=qy[head++];                \n                for(int d=0;d<4;d++){\n                    int nx=x+di[d], ny=y+dj[d];\n                    if(nx>=0&&nx<N&&ny>=0&&ny<N\n                       && !vis[nx][ny] && g[nx][ny]==f){\n                        vis[nx][ny]=true;\n                        qx[tail]=nx; qy[tail]=ny; tail++;\n                    }\n                }\n            }\n            total += tail*tail;\n        }\n    }\n    return total;\n}\n\n// compute both globalConn and fConn (for flavor f) on g\ninline void eval_conn(const int g[N][N], int f, int &globalConn, int &fConn){\n    static bool vis[N][N];\n    memset(vis,0,sizeof(vis));\n    globalConn = fConn = 0;\n    static int qx[N*N], qy[N*N];\n    for(int i=0;i<N;i++) for(int j=0;j<N;j++){\n        if(g[i][j] && !vis[i][j]){\n            int cf=g[i][j], head=0, tail=0;\n            vis[i][j]=true;\n            qx[tail]=i; qy[tail]=j; tail++;\n            while(head<tail){\n                int x=qx[head], y=qy[head++];                \n                for(int d=0;d<4;d++){\n                    int nx=x+di[d], ny=y+dj[d];\n                    if(nx>=0&&nx<N&&ny>=0&&ny<N\n                       && !vis[nx][ny] && g[nx][ny]==cf){\n                        vis[nx][ny]=true;\n                        qx[tail]=nx; qy[tail]=ny; tail++;\n                    }\n                }\n            }\n            int sz = tail;\n            globalConn += sz*sz;\n            if(cf==f) fConn += sz*sz;\n        }\n    }\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // read the 100 known flavors\n    int F[101];\n    for(int i=1;i<=100;i++) cin >> F[i];\n\n    // our 10\u00d710 board\n    static int grid[N][N] = {};\n\n    // default single\u2010axis tilt for stable tie\u2010breaking\n    // flavor 1\u2192L, 2\u2192R, 3\u2192F\n    char defdir[4] = {0,'L','R','F'};\n    const string allD = \"FBLR\";\n\n    // pre\u2010allocate buffers\n    static int grid0[4][N][N], grid1[N][N];\n    int global0[4], f0[4], bestNext[4];\n\n    for(int t=1;t<=100;t++){\n        int p; cin >> p;\n        // place the p-th empty\n        int cnt=0, si=0, sj=0;\n        for(int i=0;i<N;i++){\n            for(int j=0;j<N;j++){\n                if(grid[i][j]==0 && ++cnt==p){\n                    si=i; sj=j; goto PL;\n                }\n            }\n        }\n        PL:;\n        int curF = F[t];\n        grid[si][sj] = curF;\n\n        // build candidate\u2010order so index k orders defdir first\n        char cand[4];\n        cand[0] = defdir[curF];\n        int m=1;\n        for(char c: allD) if(c!=cand[0]) cand[m++] = c;\n\n        // 1) simulate each first\u2010move: get grid0[k], global0[k], f0[k]\n        for(int k=0;k<4;k++){\n            tilt(grid, grid0[k], cand[k]);\n            eval_conn(grid0[k], curF, global0[k], f0[k]);\n        }\n\n        // 2) for each k, one\u2010step\u2010ahead greedy bestNext[k]\n        for(int k=0;k<4;k++){\n            int mx=0;\n            for(int l=0;l<4;l++){\n                tilt(grid0[k], grid1, cand[l]);\n                mx = max(mx, calcConnAll(grid1));\n            }\n            bestNext[k] = mx;\n        }\n\n        // 3) combine into a single tie\u2010breaking score:\n        //    bestNext dominates, then immediate global0, then f0, then k\u2010order\n        long long bestScore = LLONG_MIN;\n        int bestk = 0;\n        for(int k=0;k<4;k++){\n            long long score =\n              (long long)bestNext[k] * 1000000LL\n            + (long long)global0[k]  *   1000LL\n            + (long long)f0[k];\n            if(score > bestScore){\n                bestScore = score;\n                bestk = k;\n            }\n        }\n\n        // 4) apply bestk\n        char out = cand[bestk];\n        static int tmp[N][N];\n        tilt(grid, tmp, out);\n        for(int i=0;i<N;i++) for(int j=0;j<N;j++)\n            grid[i][j] = tmp[i][j];\n\n        // emit\n        cout << out << \"\\n\" << flush;\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    // 1) pick minimal N so that L = N*(N-1)/2 >= M-1\n    int N = 4;\n    int L = N*(N-1)/2;\n    while(L < M-1){\n        ++N;\n        L = N*(N-1)/2;\n    }\n    cout << N << \"\\n\";\n\n    // 2) precompute the lex\u2010order edge list edges[b] = (i,j)\n    vector<pair<int,int>> edges;\n    edges.reserve(L);\n    for(int i=0;i<N;i++){\n        for(int j=i+1;j<N;j++){\n            edges.emplace_back(i,j);\n        }\n    }\n\n    // 3) emit G_k as first k edges = '1', rest '0'\n    //    also build degG[k] = sorted degree\u2010vector of G_k\n    vector<vector<int>> degG(M, vector<int>(N, 0));\n    for(int k=0;k<M;k++){\n        // output bitstring\n        int ones = min(k, L);\n        cout << string(ones, '1') << string(L - ones, '0') << \"\\n\";\n        // build degree vector incrementally\n        if(k>0){\n            degG[k] = degG[k-1];\n            if(k-1 < L){\n                auto [u,v] = edges[k-1];\n                degG[k][u]++;\n                degG[k][v]++;\n            }\n        }\n        // for k=0 already zeroed\n    }\n    cout << flush;\n\n    // sort each prototype's degree\u2010vector\n    for(int k=0;k<M;k++){\n        sort(degG[k].begin(), degG[k].end());\n    }\n\n    // 4) answer 100 queries\n    const int W = 3;  // window around raw estimate\n    for(int qi=0; qi<100; qi++){\n        string H;\n        cin >> H;\n        if(!cin) break;\n        // count 1's and build H's degree\u2010vector\n        int cnt = 0;\n        vector<int> degH(N, 0);\n        for(int b=0;b<L;b++){\n            if(H[b]=='1'){\n                ++cnt;\n                auto [u,v] = edges[b];\n                degH[u]++;\n                degH[v]++;\n            }\n        }\n        // sort H's degrees\n        sort(degH.begin(), degH.end());\n\n        // 4a) raw linear inverse\n        double denom = 1.0 - 2.0*eps;\n        double kd = eps*L;\n        double x;\n        if(fabs(denom) < 1e-9){\n            x = cnt; // fallback (shouldn't happen for eps<=0.4)\n        } else {\n            x = double(cnt - kd) / denom;\n        }\n        int k0 = int(round(x));\n        k0 = max(0, min(M-1, k0));\n\n        // 4b) refine on [k0-W .. k0+W]\n        int lo = max(0, k0 - W), hi = min(M-1, k0 + W);\n        int bestK = k0;\n        long long bestCost = LLONG_MAX;\n        for(int k=lo; k<=hi; k++){\n            // L1 distance between degH and degG[k]\n            long long c = 0;\n            for(int i=0;i<N;i++){\n                c += abs(degH[i] - degG[k][i]);\n            }\n            // prefer smaller cost, tie\u2010break by closeness to k0\n            if(c < bestCost || (c==bestCost && abs(k - k0) < abs(bestK - k0))){\n                bestCost = c;\n                bestK = k;\n            }\n        }\n\n        cout << bestK << \"\\n\" << flush;\n    }\n    return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nstatic const ll INF = (ll)4e18;\n\n// super\u2010fast RNG\nstruct XorShift {\n  uint64_t x;\n  XorShift(uint64_t seed=123456789) : x(seed) {}\n  inline uint64_t next() {\n    x ^= x << 13;\n    x ^= x >> 7;\n    x ^= x << 17;\n    return x;\n  }\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N,M,D,K;\n    cin>>N>>M>>D>>K;\n    vector<int> U(M), V(M);\n    vector<ll> 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    // skip coords\n    for(int i=0;i<N;i++){\n        int x,y; cin>>x>>y;\n    }\n\n    // build incidence & degree\n    vector<vector<int>> inc(N);\n    vector<int> deg(N,0);\n    for(int e=0;e<M;e++){\n        inc[U[e]].push_back(e);\n        inc[V[e]].push_back(e);\n        deg[U[e]]++;\n        deg[V[e]]++;\n    }\n\n    // 1) select B=50 sources: half top\u2010deg, half random\n    int B = min(N, 50);\n    vector<int> vids(N);\n    iota(vids.begin(), vids.end(), 0);\n    nth_element(vids.begin(), vids.begin()+B/2, vids.end(),\n                [&](int a,int b){ return deg[a] > deg[b]; });\n    vector<int> srcs;\n    srcs.reserve(B);\n    for(int i=0;i<B/2;i++) srcs.push_back(vids[i]);\n\n    XorShift rng((uint64_t)chrono::high_resolution_clock::now()\n                 .time_since_epoch().count());\n    // shuffle vids\n    for(int i=N-1;i>0;i--){\n        int j = rng.next() % (i+1);\n        swap(vids[i], vids[j]);\n    }\n    for(int i=0; (int)srcs.size()<B; i++){\n        srcs.push_back(vids[i]);\n    }\n\n    // 2) approximate edge\u2010betweenness (Brandes)\n    vector<double> central(M,0.0);\n    vector<ll> dist(N);\n    vector<double> sigma(N), delta(N);\n    vector<vector<pair<int,int>>> pred(N);\n    vector<int> stol(N);\n\n    for(int s: srcs){\n        fill(dist.begin(), dist.end(), INF);\n        fill(sigma.begin(), sigma.end(), 0.0);\n        for(auto &v: pred) v.clear();\n        dist[s]=0; sigma[s]=1.0;\n        int top=0;\n        // Dijkstra\n        using pli = pair<ll,int>;\n        priority_queue<pli,vector<pli>,greater<pli>> pq;\n        pq.push({0,s});\n        while(!pq.empty()){\n            auto [d,u] = pq.top(); pq.pop();\n            if(d!=dist[u]) continue;\n            stol[top++]=u;\n            for(int e: inc[u]){\n                int v = U[e]^V[e]^u;\n                ll nd = d + W[e];\n                if(nd < dist[v]){\n                    dist[v]=nd;\n                    sigma[v]=sigma[u];\n                    pred[v].clear();\n                    pred[v].push_back({u,e});\n                    pq.push({nd,v});\n                } else if(nd==dist[v]){\n                    sigma[v]+=sigma[u];\n                    pred[v].push_back({u,e});\n                }\n            }\n        }\n        fill(delta.begin(), delta.end(), 0.0);\n        for(int idx=top-1; idx>=0; idx--){\n            int w = stol[idx];\n            for(auto &pe: pred[w]){\n                int v = pe.first, e = pe.second;\n                double c = (sigma[v]/sigma[w])*(1.0+delta[w]);\n                delta[v] += c;\n                central[e] += c;\n            }\n        }\n    }\n\n    // 3) weighted\u2010score & lex\u2010LPT initial assignment\n    vector<double> wscore(M);\n    for(int e=0;e<M;e++){\n        wscore[e] = central[e] * (double)W[e];\n    }\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(),\n         [&](int a,int b){ return wscore[a] > wscore[b]; });\n\n    vector<int> ans(M,0), daycnt(D+1,0), pos(M,-1);\n    vector<double> daysum(D+1,0.0);\n    vector<vector<int>> vday(N, vector<int>(D+1,0)),\n                        dayEdges(D+1);\n\n    for(int e: order){\n        int u=U[e], v=V[e];\n        int bestD=1, bestC=INT_MAX;\n        double bestL=1e300;\n        // minimize (conflicts, load)\n        for(int d=1; d<=D; d++){\n            if(daycnt[d]>=K) continue;\n            int c = vday[u][d] + vday[v][d];\n            if(c>bestC) continue;\n            double L = daysum[d];\n            if(c<bestC || (c==bestC && L<bestL)){\n                bestC=c; bestL=L; bestD=d;\n            }\n        }\n        ans[e]=bestD;\n        daycnt[bestD]++;\n        daysum[bestD]+=wscore[e];\n        vday[u][bestD]++;\n        vday[v][bestD]++;\n    }\n    for(int e=0;e<M;e++){\n        int d=ans[e];\n        pos[e] = dayEdges[d].size();\n        dayEdges[d].push_back(e);\n    }\n\n    // 4) fixed\u2010count hill\u2010climb: 1 000 000 iters\n    const int MAX_IT = 1000000;\n    for(int it=0; it<MAX_IT; it++){\n        // find extremes\n        int dmax=1, dmin=1;\n        for(int d=2; d<=D; d++){\n            if(daysum[d]>daysum[dmax]) dmax=d;\n            if(daysum[d]<daysum[dmin]) dmin=d;\n        }\n        double oldMax = daysum[dmax], oldMin = daysum[dmin];\n\n        uint64_t r = rng.next() & 7;  // 0..7\n        if(r==0){\n            // random single\u2010move\n            int e = rng.next()%M;\n            int d0 = ans[e];\n            int d1 = (int)(rng.next()%D) + 1;\n            if(d1!=d0 && daycnt[d1]<K){\n                int u=U[e], v=V[e];\n                if(vday[u][d1]==0 && vday[v][d1]==0){\n                    double ld0 = daysum[d0], ld1 = daysum[d1];\n                    double n0 = ld0 - wscore[e];\n                    double n1 = ld1 + wscore[e];\n                    // global max\n                    double g = max(n0,n1);\n                    for(int d=1;d<=D;d++){\n                        if(d!=d0 && d!=d1 && daysum[d]>g)\n                            g = daysum[d];\n                    }\n                    if(g + 1e-9 < oldMax){\n                        auto &A = dayEdges[d0];\n                        int ip=pos[e], bk=A.back();\n                        A[ip]=bk; pos[bk]=ip; A.pop_back();\n                        auto &B = dayEdges[d1];\n                        pos[e]=B.size(); B.push_back(e);\n                        ans[e]=d1;\n                        daycnt[d0]--; daycnt[d1]++;\n                        daysum[d0]=n0; daysum[d1]=n1;\n                        vday[u][d0]--; vday[v][d0]--;\n                        vday[u][d1]++; vday[v][d1]++;\n                    }\n                }\n            }\n        }\n        else if(r<=2){\n            // extreme single: dmax->dmin\n            auto &A = dayEdges[dmax];\n            if(!A.empty() && daycnt[dmin]<K){\n                int e = A[rng.next()%A.size()];\n                int u=U[e], v=V[e];\n                if(vday[u][dmin]==0 && vday[v][dmin]==0){\n                    double nMax = oldMax - wscore[e];\n                    double nMin = oldMin + wscore[e];\n                    if(max(nMax,nMin) + 1e-9 < max(oldMax,oldMin)){\n                        int ip=pos[e], bk=A.back();\n                        A[ip]=bk; pos[bk]=ip; A.pop_back();\n                        auto &B = dayEdges[dmin];\n                        pos[e]=B.size(); B.push_back(e);\n\n                        ans[e]=dmin;\n                        daycnt[dmax]--; daycnt[dmin]++;\n                        daysum[dmax]=nMax; daysum[dmin]=nMin;\n                        vday[u][dmax]--; vday[v][dmax]--;\n                        vday[u][dmin]++; vday[v][dmin]++;\n                    }\n                }\n            }\n        }\n        else if(r<=4){\n            // random pair\u2010swap (two random days)\n            int d1 = (int)(rng.next()%D) + 1;\n            int d2 = (int)(rng.next()%D) + 1;\n            if(d1!=d2 && !dayEdges[d1].empty() && !dayEdges[d2].empty()){\n                int e1 = dayEdges[d1][rng.next()%dayEdges[d1].size()];\n                int e2 = dayEdges[d2][rng.next()%dayEdges[d2].size()];\n                if(e1!=e2){\n                    int u1=U[e1], v1=V[e1];\n                    int u2=U[e2], v2=V[e2];\n                    // remove conflict counters\n                    vday[u1][d1]--; vday[v1][d1]--;\n                    vday[u2][d2]--; vday[v2][d2]--;\n                    if(vday[u1][d2]==0 && vday[v1][d2]==0\n                    && vday[u2][d1]==0 && vday[v2][d1]==0){\n                        double ld1=daysum[d1], ld2=daysum[d2];\n                        double nd1 = ld1 - wscore[e1] + wscore[e2];\n                        double nd2 = ld2 - wscore[e2] + wscore[e1];\n                        double g = max(nd1,nd2);\n                        for(int d=1;d<=D;d++){\n                            if(d!=d1 && d!=d2 && daysum[d]>g)\n                                g = daysum[d];\n                        }\n                        double oldG = daysum[dmax];\n                        if(g + 1e-9 < oldG){\n                            auto &A = dayEdges[d1], &B = dayEdges[d2];\n                            int i1=pos[e1], b1=A.back();\n                            A[i1]=b1; pos[b1]=i1; A.pop_back();\n                            int i2=pos[e2], b2=B.back();\n                            B[i2]=b2; pos[b2]=i2; B.pop_back();\n                            pos[e2]=A.size(); A.push_back(e2);\n                            pos[e1]=B.size(); B.push_back(e1);\n\n                            ans[e1]=d2; ans[e2]=d1;\n                            daysum[d1]=nd1; daysum[d2]=nd2;\n                            vday[u1][d2]++; vday[v1][d2]++;\n                            vday[u2][d1]++; vday[v2][d1]++;\n                        } else {\n                            // revert\n                            vday[u1][d1]++; vday[v1][d1]++;\n                            vday[u2][d2]++; vday[v2][d2]++;\n                        }\n                    } else {\n                        // revert\n                        vday[u1][d1]++; vday[v1][d1]++;\n                        vday[u2][d2]++; vday[v2][d2]++;\n                    }\n                }\n            }\n        }\n        else {\n            // extreme pair\u2010swap between dmax<->dmin\n            auto &A = dayEdges[dmax], &B = dayEdges[dmin];\n            if(!A.empty() && !B.empty()){\n                int e1 = A[rng.next()%A.size()];\n                int e2 = B[rng.next()%B.size()];\n                if(e1!=e2){\n                    int u1=U[e1], v1=V[e1];\n                    int u2=U[e2], v2=V[e2];\n                    vday[u1][dmax]--; vday[v1][dmax]--;\n                    vday[u2][dmin]--; vday[v2][dmin]--;\n                    if(vday[u1][dmin]==0 && vday[v1][dmin]==0\n                    && vday[u2][dmax]==0 && vday[v2][dmax]==0){\n                        double ndMax = daysum[dmax] - wscore[e1] + wscore[e2];\n                        double ndMin = daysum[dmin] - wscore[e2] + wscore[e1];\n                        if(max(ndMax,ndMin)+1e-9 < max(oldMax,oldMin)){\n                            int i1=pos[e1], b1=A.back();\n                            A[i1]=b1; pos[b1]=i1; A.pop_back();\n                            int i2=pos[e2], b2=B.back();\n                            B[i2]=b2; pos[b2]=i2; B.pop_back();\n                            pos[e2]=A.size(); A.push_back(e2);\n                            pos[e1]=B.size(); B.push_back(e1);\n\n                            ans[e1]=dmin; ans[e2]=dmax;\n                            daysum[dmax]=ndMax; daysum[dmin]=ndMin;\n                            vday[u1][dmin]++; vday[v1][dmin]++;\n                            vday[u2][dmax]++; vday[v2][dmax]++;\n                        } else {\n                            vday[u1][dmax]++; vday[v1][dmax]++;\n                            vday[u2][dmin]++; vday[v2][dmin]++;\n                        }\n                    } else {\n                        vday[u1][dmax]++; vday[v1][dmax]++;\n                        vday[u2][dmin]++; vday[v2][dmin]++;\n                    }\n                }\n            }\n        }\n    }\n\n    // 5) output\n    for(int i=0;i<M;i++){\n        cout<<ans[i]<<(i+1<M?' ':'\\n');\n    }\n    return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\n// DSU for Kruskal\nstruct DSU {\n    vector<int> p, r;\n    DSU(int n): p(n,-1), r(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\n    int D;\n    cin >> D;\n    vector<string> f1(D), r1(D), f2(D), r2(D);\n    for(int i=0;i<D;i++) cin>>f1[i];\n    for(int i=0;i<D;i++) cin>>r1[i];\n    for(int i=0;i<D;i++) cin>>f2[i];\n    for(int i=0;i<D;i++) cin>>r2[i];\n\n    int N = D*D*D;\n    auto idx = [&](int x,int y,int z){\n        return x*D*D + y*D + z;\n    };\n    // 1) Precompute per\u2010slice x/y lists\n    vector<vector<int>> X1(D), Y1(D), X2(D), Y2(D);\n    for(int z=0;z<D;z++){\n        for(int x=0;x<D;x++){\n            if(f1[z][x]=='1') X1[z].push_back(x);\n            if(f2[z][x]=='1') X2[z].push_back(x);\n        }\n        for(int y=0;y<D;y++){\n            if(r1[z][y]=='1') Y1[z].push_back(y);\n            if(r2[z][y]=='1') Y2[z].push_back(y);\n        }\n    }\n\n    // 2) Build per\u2010slice *minimal* edge\u2010covers, planting as many common edges first\n    vector<char> need1(N,0), need2(N,0), inS(N,0);\n    for(int z=0;z<D;z++){\n        auto &A1=X1[z], &B1=Y1[z], &A2=X2[z], &B2=Y2[z];\n        sort(A1.begin(),A1.end());\n        sort(B1.begin(),B1.end());\n        sort(A2.begin(),A2.end());\n        sort(B2.begin(),B2.end());\n        // mark inS = silhouette\u2010intersection footprint\n        for(int x:A1) for(int y:B1){\n            int i=idx(x,y,z);\n            if(f2[z][x]=='1' && r2[z][y]=='1')\n                inS[i]=1;\n        }\n\n        // compute intersection coords Ux, Uy\n        vector<int> Ux, Uy;\n        { int i=0,j=0;\n          while(i<(int)A1.size()&&j<(int)A2.size()){\n            if(A1[i]<A2[j]) i++;\n            else if(A2[j]<A1[i]) j++;\n            else{ Ux.push_back(A1[i]); i++; j++; }\n          }\n        }\n        { int i=0,j=0;\n          while(i<(int)B1.size()&&j<(int)B2.size()){\n            if(B1[i]<B2[j]) i++;\n            else if(B2[j]<B1[i]) j++;\n            else{ Uy.push_back(B1[i]); i++; j++; }\n          }\n        }\n        int k = min((int)Ux.size(), (int)Uy.size());\n\n        // coverage flags\n        vector<char> cA1(D,0), cB1(D,0), cA2(D,0), cB2(D,0);\n\n        // 2a) plant k common edges\n        for(int i=0;i<k;i++){\n            int x=Ux[i], y=Uy[i], I=idx(x,y,z);\n            need1[I]=need2[I]=1;\n            cA1[x]=cA2[x]=1;\n            cB1[y]=cB2[y]=1;\n        }\n\n        // 2b) complete shape1 minimal edge\u2010cover\n        int m1 = min((int)A1.size(),(int)B1.size());\n        vector<int> rA1, rB1;\n        for(int x:A1) if(!cA1[x]) rA1.push_back(x);\n        for(int y:B1) if(!cB1[y]) rB1.push_back(y);\n        int match1 = m1 - k;\n        for(int i=0;i<match1;i++){\n            int x=rA1[i], y=rB1[i];\n            need1[idx(x,y,z)] = 1;\n            cA1[x]=cB1[y]=1;\n        }\n        if(A1.size()>B1.size()){\n            int y0=B1[0];\n            for(int i=match1;i<(int)rA1.size();i++){\n                int x=rA1[i];\n                need1[idx(x,y0,z)]=1;\n                cA1[x]=cB1[y0]=1;\n            }\n        } else {\n            int x0=A1[0];\n            for(int i=match1;i<(int)rB1.size();i++){\n                int y=rB1[i];\n                need1[idx(x0,y,z)]=1;\n                cA1[x0]=cB1[y]=1;\n            }\n        }\n\n        // 2c) complete shape2 minimal edge\u2010cover\n        int m2 = min((int)A2.size(),(int)B2.size());\n        vector<int> rA2, rB2;\n        for(int x:A2) if(!cA2[x]) rA2.push_back(x);\n        for(int y:B2) if(!cB2[y]) rB2.push_back(y);\n        int match2 = m2 - k;\n        for(int i=0;i<match2;i++){\n            int x=rA2[i], y=rB2[i];\n            need2[idx(x,y,z)] = 1;\n            cA2[x]=cB2[y]=1;\n        }\n        if(A2.size()>B2.size()){\n            int y0=B2[0];\n            for(int i=match2;i<(int)rA2.size();i++){\n                int x=rA2[i];\n                need2[idx(x,y0,z)]=1;\n                cA2[x]=cB2[y0]=1;\n            }\n        } else {\n            int x0=A2[0];\n            for(int i=match2;i<(int)rB2.size();i++){\n                int y=rB2[i];\n                need2[idx(x0,y,z)]=1;\n                cA2[x0]=cB2[y]=1;\n            }\n        }\n    }\n\n    // 3) Extract initial shared\u2010voxels CCs\n    vector<int> comp_id(N,-1), vis(N,0);\n    vector<vector<int>> comps;\n    const int dx[6]={1,-1,0,0,0,0},\n              dy[6]={0,0,1,-1,0,0},\n              dz[6]={0,0,0,0,1,-1};\n\n    for(int I=0;I<N;I++){\n        if(comp_id[I]==-1 && need1[I] && need2[I]){\n            int cid = (int)comps.size();\n            comps.emplace_back();\n            queue<int>q;\n            q.push(I);\n            comp_id[I]=cid;\n            while(!q.empty()){\n                int u=q.front();q.pop();\n                comps[cid].push_back(u);\n                int ux=u/(D*D), ry=(u%(D*D))/D, uz=u%D;\n                for(int d=0;d<6;d++){\n                    int nx=ux+dx[d], ny=ry+dy[d], nz=uz+dz[d];\n                    if(nx<0||nx>=D||ny<0||ny>=D||nz<0||nz>=D) continue;\n                    int v=idx(nx,ny,nz);\n                    if(comp_id[v]==-1 && need1[v] && need2[v]){\n                        comp_id[v]=cid;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n    }\n\n    int C = (int)comps.size();\n    if(C>1){\n        // 4) Build complete graph of CCs with edge\u2010weights = BFS\u2010dist over inS\n        const int INF = 1e9;\n        vector<vector<int>> dist(C, vector<int>(C,INF));\n        for(int i=0;i<C;i++){\n            // multi\u2010source BFS from all nodes in comps[i]\n            vector<int> dnode(N,-1);\n            queue<int> q;\n            for(int u:comps[i]){\n                dnode[u]=0;\n                q.push(u);\n            }\n            while(!q.empty()){\n                int u=q.front();q.pop();\n                int ux=u/(D*D), ry=(u%(D*D))/D, uz=u%D;\n                int du=dnode[u];\n                int cid_u = comp_id[u];\n                // record distances when we first hit another comp\n                if(cid_u>=0 && cid_u!=i && dist[i][cid_u]==INF){\n                    dist[i][cid_u]=du;\n                }\n                for(int d=0;d<6;d++){\n                    int nx=ux+dx[d], ny=ry+dy[d], nz=uz+dz[d];\n                    if(nx<0||nx>=D||ny<0||ny>=D||nz<0||nz>=D) continue;\n                    int v=idx(nx,ny,nz);\n                    if(dnode[v]==-1 && inS[v]){\n                        dnode[v]=du+1;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n        // 5) MST on the CC graph\n        struct E{int w,i,j;};\n        vector<E> edges;\n        edges.reserve(C*(C-1)/2);\n        for(int i=0;i<C;i++){\n            for(int j=i+1;j<C;j++){\n                if(dist[i][j]<INF) edges.push_back({dist[i][j],i,j});\n            }\n        }\n        sort(edges.begin(),edges.end(),[](auto &a,auto &b){\n            return a.w < b.w;\n        });\n        DSU dsu(C);\n        vector<pair<int,int>> mst;\n        for(auto &e: edges){\n            if(dsu.unite(e.i,e.j)){\n                mst.emplace_back(e.i,e.j);\n                if((int)mst.size()==C-1) break;\n            }\n        }\n\n        // 6) For each MST edge, BFS+parent to reconstruct shortest path and add bridging voxels\n        for(auto &pr: mst){\n            int s = pr.first, t = pr.second;\n            vector<int> parent(N,-2), used(N,0);\n            queue<int> q;\n            for(int u: comps[s]){\n                parent[u] = -1;\n                used[u]=1;\n                q.push(u);\n            }\n            int meet = -1;\n            while(!q.empty() && meet<0){\n                int u=q.front();q.pop();\n                int ux=u/(D*D), ry=(u%(D*D))/D, uz=u%D;\n                if(comp_id[u]==t){ meet=u; break; }\n                for(int d=0;d<6;d++){\n                    int nx=ux+dx[d], ny=ry+dy[d], nz=uz+dz[d];\n                    if(nx<0||nx>=D||ny<0||ny>=D||nz<0||nz>=D) continue;\n                    int v=idx(nx,ny,nz);\n                    if(!used[v] && inS[v]){\n                        used[v]=1;\n                        parent[v]=u;\n                        q.push(v);\n                    }\n                }\n            }\n            if(meet<0) continue;\n            // reconstruct path\n            vector<int> path;\n            for(int v=meet; v>=0; v=parent[v]) path.push_back(v);\n            reverse(path.begin(), path.end());\n            // add all interior nodes\n            for(int k=1;k+1<(int)path.size();k++){\n                int w = path[k];\n                if(!need1[w] || !need2[w]){\n                    need1[w]=need2[w]=1;\n                    // note: inS[w] guaranteed by BFS\n                }\n            }\n            // after bridging, we could union comps in DSU, but final CC\u2010merge will regroup\n        }\n    }\n\n    // 7) Final 6\u2010CC\u2010merge of (need1 & need2) into shared blocks\n    fill(vis.begin(),vis.end(),0);\n    vector<int> b1(N,0), b2(N,0);\n    int block_id=0;\n    for(int I=0;I<N;I++){\n        if(!vis[I] && need1[I] && need2[I]){\n            ++block_id;\n            queue<int> q;\n            q.push(I);\n            vis[I]=1;\n            b1[I]=b2[I]=block_id;\n            while(!q.empty()){\n                int u=q.front();q.pop();\n                int ux=u/(D*D), ry=(u%(D*D))/D, uz=u%D;\n                for(int d=0;d<6;d++){\n                    int nx=ux+dx[d], ny=ry+dy[d], nz=uz+dz[d];\n                    if(nx<0||nx>=D||ny<0||ny>=D||nz<0||nz>=D) continue;\n                    int v=idx(nx,ny,nz);\n                    if(!vis[v] && need1[v] && need2[v]){\n                        vis[v]=1;\n                        b1[v]=b2[v]=block_id;\n                        q.push(v);\n                    }\n                }\n            }\n        }\n    }\n\n    // 8) Unique\u2010voxel blocks\n    for(int I=0;I<N;I++){\n        if(need1[I] && !need2[I]){\n            b1[I] = ++block_id;\n        }\n    }\n    for(int I=0;I<N;I++){\n        if(need2[I] && !need1[I]){\n            b2[I] = ++block_id;\n        }\n    }\n\n    // 9) Output\n    cout<<block_id<<\"\\n\";\n    for(int i=0;i<N;i++){\n        cout<<b1[i]<<(i+1==N?'\\n':' ');\n    }\n    for(int i=0;i<N;i++){\n        cout<<b2[i]<<(i+1==N?'\\n':' ');\n    }\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll INF = (1LL<<60);\n\nint N,M,K;\nvector<vector<pair<int,pair<ll,int>>>> g;\ninline int CeilSqrt(ll d2){\n    ll s = (ll)floor(sqrt((long double)d2));\n    while(s*s<d2) s++;\n    while(s>0&&(s-1)*(s-1)>=d2) s--;\n    return (int)s;\n}\nstruct DSU{\n    vector<int> p,r;\n    DSU(int n):p(n),r(n){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; if(r[a]==r[b]) r[a]++;\n        return true;\n    }\n};\nstruct SteinerInfo{\n    vector<int> terms;\n    vector<pair<int,int>> pairs;\n    vector<ll> wts;\n    vector<int> B;\n    ll cableCost;\n};\n\n// build 2-approx Steiner by MST-on-metric and SPH\nSteinerInfo buildSteiner(\n    const vector<int>& terms,\n    const vector<vector<ll>>& distS,\n    const vector<vector<vector<int>>>& pathE\n){\n    int T=terms.size();\n    struct CE{ ll w; int i,j; };\n    vector<CE> cands; cands.reserve(T*(T-1)/2);\n    for(int i=0;i<T;i++) for(int j=i+1;j<T;j++){\n        cands.push_back({distS[terms[i]][terms[j]],i,j});\n    }\n    sort(cands.begin(),cands.end(),[](auto &A,auto &B){return A.w<B.w;});\n    DSU d1(T);\n    vector<pair<int,int>> P1;\n    vector<ll> W1;\n    ll c1=0;\n    for(auto &e:cands){\n        if(d1.unite(e.i,e.j)){\n            P1.emplace_back(e.i,e.j);\n            W1.push_back(e.w);\n            c1+=e.w;\n            if((int)P1.size()==T-1) break;\n        }\n    }\n    vector<int> B1(M,0);\n    for(int k=0;k<(int)P1.size();k++){\n        int u=terms[P1[k].first], v=terms[P1[k].second];\n        for(int eid:pathE[u][v]) B1[eid]=1;\n    }\n    // SPH\n    vector<bool> inT(T,false); inT[0]=true; int added=1;\n    vector<pair<int,int>> P2; vector<ll> W2; vector<int> B2(M,0);\n    ll c2=0;\n    while(added<T){\n        ll bestw=INF; int bu=-1,bv=-1;\n        for(int u=0;u<T;u++) if(inT[u])\n            for(int v=0;v<T;v++) if(!inT[v]){\n                ll d=distS[terms[u]][terms[v]];\n                if(d<bestw){bestw=d;bu=u;bv=v;}\n            }\n        if(bu<0) break;\n        inT[bv]=true; added++;\n        P2.emplace_back(bu,bv); W2.push_back(bestw); c2+=bestw;\n        int u0=terms[bu], v0=terms[bv];\n        for(int eid:pathE[u0][v0]) B2[eid]=1;\n    }\n    if(c1<=c2) return {terms,P1,W1,B1,c1};\n    else         return {terms,P2,W2,B2,c2};\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    using Clock=chrono::steady_clock;\n    auto t0=Clock::now();\n\n    cin>>N>>M>>K;\n    vector<ll> xs(N), ys(N);\n    for(int i=0;i<N;i++) cin>>xs[i]>>ys[i];\n\n    vector<int> EU(M), EV(M);\n    vector<ll> EW(M);\n    g.assign(N,{});\n    for(int j=0;j<M;j++){\n        int u,v; ll w;\n        cin>>u>>v>>w; --u;--v;\n        EU[j]=u; EV[j]=v; EW[j]=w;\n        g[u].push_back({v,{w,j}});\n        g[v].push_back({u,{w,j}});\n    }\n    vector<ll> aa(K), bb(K);\n    for(int i=0;i<K;i++) cin>>aa[i]>>bb[i];\n\n    // 1) APSP + exact path edges\n    vector<vector<ll>> distS(N,vector<ll>(N,INF));\n    vector<vector<int>> pE(N,vector<int>(N,-1)), pN(N,vector<int>(N,-1));\n    for(int s=0;s<N;s++){\n        auto &d=distS[s];\n        d[s]=0;\n        priority_queue<pair<ll,int>,\n          vector<pair<ll,int>>,greater<>>pq;\n        pq.push({0,s});\n        while(!pq.empty()){\n            auto [cd,u]=pq.top();pq.pop();\n            if(cd>d[u]) continue;\n            for(auto &ed:g[u]){\n                int v=ed.first, id=ed.second.second;\n                ll w=ed.second.first, nd=cd+w;\n                if(nd<d[v]){\n                    d[v]=nd; pE[s][v]=id; pN[s][v]=u;\n                    pq.push({nd,v});\n                }\n            }\n        }\n    }\n    vector<vector<vector<int>>> pathE(N,vector<vector<int>>(N));\n    for(int s=0;s<N;s++){\n        for(int t=0;t<N;t++){\n            if(s==t) continue;\n            int cur=t;\n            while(cur!=s){\n                int id=pE[s][cur];\n                pathE[s][t].push_back(id);\n                cur=pN[s][cur];\n            }\n        }\n    }\n\n    // 2) nearest\u20103 stations per resident\n    vector<array<pair<ll,int>,3>> near3(K);\n    for(int r=0;r<K;r++){\n        array<pair<ll,int>,3> bst = {\n            make_pair(INF,-1),\n            make_pair(INF,-1),\n            make_pair(INF,-1)\n        };\n        for(int i=0;i<N;i++){\n            ll dx=xs[i]-aa[r], dy=ys[i]-bb[r], d2=dx*dx+dy*dy;\n            if(d2<bst[0].first){\n                bst[2]=bst[1]; bst[1]=bst[0]; bst[0]={d2,i};\n            } else if(d2<bst[1].first){\n                bst[2]=bst[1]; bst[1]={d2,i};\n            } else if(d2<bst[2].first){\n                bst[2]={d2,i};\n            }\n        }\n        near3[r]=bst;\n    }\n\n    // 3) initial nearest\u2010station assignment\n    vector<vector<int>> assigned(N);\n    vector<int> res2station(K);\n    for(int r=0;r<K;r++){\n        int s=near3[r][0].second;\n        assigned[s].push_back(r);\n        res2station[r]=s;\n    }\n\n    // best\u2010so\u2010far\n    vector<int> bestP(N), bestB(M);\n    vector<int> bestRes2=res2station;\n    vector<vector<int>> bestAssigned=assigned;\n    ll bestCost=INF;\n\n    const int MAX_ITERS=200, DROP_LIMIT=5;\n    vector<ll> maxd2(N);\n    vector<int> P(N);\n\n    // local\u2010search with tight uphill acceptance\n    auto localSearch=[&](int ITERS){\n        for(int iter=0;iter<ITERS;iter++){\n            if(chrono::duration<double>(Clock::now()-t0).count()>1.9) return;\n            // recompute P\n            fill(maxd2.begin(),maxd2.end(),0LL);\n            for(int i=0;i<N;i++)\n            for(int r:assigned[i]){\n                ll dx=xs[i]-aa[r], dy=ys[i]-bb[r], d2=dx*dx+dy*dy;\n                maxd2[i]=max(maxd2[i],d2);\n            }\n            for(int i=0;i<N;i++) P[i]=(maxd2[i]>0?CeilSqrt(maxd2[i]):0);\n            // terminals\n            vector<int> terms; terms.reserve(N);\n            terms.push_back(0);\n            for(int i=1;i<N;i++) if(P[i]>0) terms.push_back(i);\n            if(terms.size()<=1) break;\n            // Steiner\n            auto info=buildSteiner(terms,distS,pathE);\n            // evaluate\n            ll cable=info.cableCost, pw=0;\n            for(int i=0;i<N;i++) pw+= (ll)P[i]*P[i];\n            ll tot=cable+pw;\n            if(tot<bestCost){\n                bestCost=tot;\n                bestP=P;\n                bestB=info.B;\n                bestRes2=res2station;\n                bestAssigned=assigned;\n            }\n            // find best positive and best negative moves\n            ll bestPos=0, bestNeg=LLONG_MIN;\n            int bi=-1,br=-1,bj=-1, ni=-1,nr=-1,nj=-1;\n            // broadcast\u2010only moves\n            for(int i=0;i<N;i++){\n                int sz=assigned[i].size();\n                if(sz<2) continue;\n                ll m1=-1,m2=-1; int r1=-1,r2=-1;\n                for(int r:assigned[i]){\n                    ll dx=xs[i]-aa[r], dy=ys[i]-bb[r], d2=dx*dx+dy*dy;\n                    if(d2>m1){m2=m1;r2=r1;m1=d2;r1=r;}\n                    else if(d2>m2){m2=d2;r2=r;}\n                }\n                for(int pass=0;pass<2;pass++){\n                    int r=(pass==0?r1:r2);\n                    if(r<0) continue;\n                    int c=-1; ll d2c=0;\n                    for(auto &pr:near3[r]){\n                        if(pr.second!=i){\n                            c=pr.second; d2c=pr.first; break;\n                        }\n                    }\n                    if(c<0) continue;\n                    ll oldPi=P[i], newPi=CeilSqrt(pass==0?m2:m1);\n                    ll oldPj=P[c], newPj=CeilSqrt(max(maxd2[c],d2c));\n                    ll delta=(oldPi*oldPi+oldPj*oldPj)\n                            - (newPi*newPi+newPj*newPj);\n                    if(delta>bestPos){\n                        bestPos=delta; bi=i;br=r;bj=c;\n                    } else if(delta<0 && delta>bestNeg){\n                        bestNeg=delta; ni=i;nr=r;nj=c;\n                    }\n                }\n            }\n            // drop\u2010leaf moves\n            int T=terms.size();\n            vector<int> idx(N,-1);\n            for(int t=0;t<T;t++) idx[terms[t]]=t;\n            ll bestPosD=0, bestNegD=LLONG_MIN;\n            int di=-1;\n            for(int i=1;i<N;i++){\n                int cnt=assigned[i].size();\n                if(cnt==0 || cnt>DROP_LIMIT) continue;\n                int si=idx[i];\n                ll saveC=0;\n                for(int k=0;k<(int)info.pairs.size();k++){\n                    auto &pp=info.pairs[k];\n                    if(pp.first==si||pp.second==si)\n                        saveC+=info.wts[k];\n                }\n                unordered_map<int,ll> more; more.reserve(cnt);\n                for(int r:assigned[i]){\n                    int c=-1; ll d2c=0;\n                    for(auto &pr:near3[r]){\n                        if(pr.second!=i){\n                            c=pr.second; d2c=pr.first; break;\n                        }\n                    }\n                    if(c<0) continue;\n                    more[c]=max(more[c],d2c);\n                }\n                ll incB=0;\n                for(auto &pr:more){\n                    int j=pr.first; ll d2n=pr.second;\n                    ll m2=max(maxd2[j],d2n);\n                    ll oldP=P[j], newP=CeilSqrt(m2);\n                    incB += (newP*newP - oldP*oldP);\n                }\n                ll delta=saveC + (ll)P[i]*P[i] - incB;\n                if(delta>bestPosD){\n                    bestPosD=delta; di=i;\n                } else if(delta<0 && delta>bestNegD){\n                    bestNegD=delta;\n                }\n            }\n            // apply move\n            bool moved=false;\n            if(bestPos>0){\n                auto &A=assigned[bi];\n                A.erase(find(A.begin(),A.end(),br));\n                assigned[bj].push_back(br);\n                res2station[br]=bj;\n                moved=true;\n            }\n            else if(bestPosD>0){\n                auto who=assigned[di];\n                assigned[di].clear();\n                for(int r:who){\n                    for(auto &pr:near3[r]){\n                        if(pr.second!=di){\n                            assigned[pr.second].push_back(r);\n                            res2station[r]=pr.second;\n                            break;\n                        }\n                    }\n                }\n                moved=true;\n            }\n            else if(iter<ITERS/2 && bestNeg>-1000){\n                auto &A=assigned[ni];\n                A.erase(find(A.begin(),A.end(),nr));\n                assigned[nj].push_back(nr);\n                res2station[nr]=nj;\n                moved=true;\n            }\n            else if(iter<ITERS/2 && bestNegD>-1000){\n                auto who=assigned[di];\n                assigned[di].clear();\n                for(int r:who){\n                    for(auto &pr:near3[r]){\n                        if(pr.second!=di){\n                            assigned[pr.second].push_back(r);\n                            res2station[r]=pr.second;\n                            break;\n                        }\n                    }\n                }\n                moved=true;\n            }\n            if(moved) continue;\n            else break;\n        }\n    };\n\n    // 4) initial deep search\n    localSearch(MAX_ITERS);\n\n    // 5) multi\u2010shake & short polish\n    mt19937_64 rng((unsigned)Clock::now().time_since_epoch().count());\n    const int SHAKES=50;\n    for(int rep=0;rep<3;rep++){\n        if(chrono::duration<double>(Clock::now()-t0).count()>1.9) break;\n        res2station=bestRes2;\n        assigned=bestAssigned;\n        for(int s=0;s<SHAKES;s++){\n            int r=rng()%K;\n            int old=res2station[r];\n            int idx=1+(rng()%2);\n            int ns=near3[r][idx].second;\n            if(ns==old) continue;\n            auto &A=assigned[old];\n            A.erase(find(A.begin(),A.end(),r));\n            assigned[ns].push_back(r);\n            res2station[r]=ns;\n        }\n        localSearch(MAX_ITERS/2);\n    }\n\n    // 6) reverse\u2010delete prune\n    vector<int> B=bestB;\n    vector<bool> isT(N,false);\n    for(int i=0;i<N;i++) if(bestP[i]>0||i==0) isT[i]=1;\n    vector<int> ord;\n    for(int j=0;j<M;j++) if(B[j]) ord.push_back(j);\n    sort(ord.begin(),ord.end(),\n         [&](int a,int b){return EW[a]>EW[b];});\n    vector<vector<int>> cadj(N);\n    for(int j:ord){\n        B[j]=0;\n        for(int i=0;i<N;i++) cadj[i].clear();\n        for(int k=0;k<M;k++) if(B[k]){\n            cadj[EU[k]].push_back(EV[k]);\n            cadj[EV[k]].push_back(EU[k]);\n        }\n        vector<char> vis(N,0);\n        queue<int>q; q.push(0); vis[0]=1;\n        while(!q.empty()){\n            int u=q.front();q.pop();\n            for(int v:cadj[u]) if(!vis[v]){\n                vis[v]=1; q.push(v);\n            }\n        }\n        bool ok=true;\n        for(int i=0;i<N;i++){\n            if(isT[i] && !vis[i]){ok=false;break;}\n        }\n        if(!ok) B[j]=1;\n    }\n    bestB=B;\n\n    // output\n    for(int i=0;i<N;i++){\n        cout<<bestP[i]<<(i+1<N?' ':'\\n');\n    }\n    for(int j=0;j<M;j++){\n        cout<<bestB[j]<<(j+1<M?' ':'\\n');\n    }\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\n\nstatic const int N = 30;\nstatic const int M = N*(N+1)/2;  // 465\n\nstruct Move { int x1,y1,x2,y2; };\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // 1) Read the initial permutation\n    vector<int> posBall(M), curPos(M);\n    for(int x=0, idx=0; x<N; x++){\n        for(int y=0; y<=x; y++, idx++){\n            int b; \n            cin >> b;\n            posBall[idx] = b;\n            curPos[b] = idx;\n        }\n    }\n\n    // 2) id <-> (x,y) mappings\n    static int id2x[M], id2y[M];\n    auto xy2id = [&](int x,int y){ return x*(x+1)/2 + y; };\n    for(int x=0, idx=0; x<N; x++){\n        for(int y=0; y<=x; y++, idx++){\n            id2x[idx]=x;\n            id2y[idx]=y;\n        }\n    }\n\n    // 3) Build the 6\u2010neighbor adjacency on the triangular grid\n    static vector<int> adj[M];\n    for(int u=0; u<M; u++){\n        auto X = id2x[u], Y = id2y[u];\n        adj[u].clear();\n        if(X>0 && Y>0)      adj[u].push_back(xy2id(X-1,Y-1));\n        if(X>0 && Y<=X-1)   adj[u].push_back(xy2id(X-1,Y));\n        if(Y>0)             adj[u].push_back(xy2id(X  ,Y-1));\n        if(Y< X)            adj[u].push_back(xy2id(X  ,Y+1));\n        if(X+1< N){\n            adj[u].push_back(xy2id(X+1,Y));\n            adj[u].push_back(xy2id(X+1,Y+1));\n        }\n    }\n\n    // 4) Precompute all\u2010pairs shortest\u2010path distances distAll[u][v]\n    static int distAll[M][M];\n    static int Qtmp[M];\n    for(int s=0; s<M; s++){\n        auto dist = distAll[s];\n        // initialize\n        for(int i=0;i<M;i++) dist[i]=INT_MAX;\n        int qh=0, qt=0;\n        dist[s]=0;\n        Qtmp[qt++]=s;\n        while(qh<qt){\n            int u=Qtmp[qh++], du=dist[u];\n            for(int v: adj[u]){\n                if(dist[v] > du+1){\n                    dist[v]=du+1;\n                    Qtmp[qt++]=v;\n                }\n            }\n        }\n    }\n\n    // 5) We'll collect our swaps here\n    vector<Move> moves;\n    moves.reserve(M*8);\n\n    // 6) Prepare scratch space for the per\u2010ball BFS\n    static bool seen[M];\n    static int parentArr[M], Q[M], path[M];\n\n    // 7) Place balls in ascending label L=0..464\n    //    But skip L in the bottom row (no children, no E\u2010impact)\n    for(int L=0; L<M-N; L++){\n        int s = curPos[L], t = L;\n        if(s==t) continue;\n\n        // BFS on the subgraph { id>=L }, which is guaranteed connected\n        memset(seen, 0, sizeof(seen));\n        int qh=0, qt=0;\n        seen[s]=true;\n        parentArr[s]=-1;\n        Q[qt++]=s;\n\n        bool found=false;\n        while(qh<qt && !found){\n            int u = Q[qh++];\n            // gather up to 6 neighbors in a tiny array\n            int nbCnt=0;\n            static int nbV[6], nbD[6];\n            for(int v: adj[u]){\n                if(v < L) continue;      // locked prefix\n                if(seen[v]) continue;\n                seen[v]=true;\n                parentArr[v]=u;\n                // record for sorting\n                nbV[nbCnt] = v;\n                nbD[nbCnt] = distAll[v][t];\n                nbCnt++;\n            }\n            // insertion\u2010sort nbV[0..nbCnt) by nbD ascending\n            for(int i=1;i<nbCnt;i++){\n                int dv = nbD[i], vv=nbV[i], j=i;\n                while(j>0 && nbD[j-1] > dv){\n                    nbD[j]=nbD[j-1];\n                    nbV[j]=nbV[j-1];\n                    --j;\n                }\n                nbD[j]=dv; \n                nbV[j]=vv;\n            }\n            // enqueue in that \u201cbest\u2010first\u201d order\n            for(int i=0;i<nbCnt;i++){\n                int v=nbV[i];\n                Q[qt++]=v;\n                if(v==t){ found=true; break; }\n            }\n        }\n        // Reconstruct the path s -> \u2026 -> t\n        int plen=0;\n        for(int cur=t; cur!=-1; cur=parentArr[cur]){\n            path[plen++]=cur;\n        }\n        // path[] is in reverse (t\u2192\u2026\u2192s), so reverse it\n        for(int i=0;i<plen/2;i++){\n            swap(path[i], path[plen-1-i]);\n        }\n        // \u201cBubble\u201d L along that path\n        for(int i=1;i<plen;i++){\n            int u0=path[i-1], v0=path[i];\n            int A=posBall[u0], B=posBall[v0];\n            // swap in our model\n            posBall[u0]=B;  posBall[v0]=A;\n            curPos[A]=v0;   curPos[B]=u0;\n            // record the move\n            moves.push_back({\n                id2x[u0], id2y[u0],\n                id2x[v0], id2y[v0]\n            });\n        }\n    }\n\n    // 8) One final linear pass to strip out immediate \u201cundo\u201d swaps\n    vector<Move> clean;\n    clean.reserve(moves.size());\n    int K = (int)moves.size();\n    for(int i=0; i<K; i++){\n        if(i+1<K){\n            auto &a=moves[i], &b=moves[i+1];\n            bool same = (a.x1==b.x1 && a.y1==b.y1 && a.x2==b.x2 && a.y2==b.y2);\n            bool rev  = (a.x1==b.x2 && a.y1==b.y2 && a.x2==b.x1 && a.y2==b.y1);\n            if(same||rev){\n                i++; // skip both\n                continue;\n            }\n        }\n        clean.push_back(moves[i]);\n    }\n\n    // 9) Output\n    cout << clean.size() << \"\\n\";\n    for(auto &m: clean){\n        cout << m.x1 << \" \" << m.y1 << \" \"\n             << m.x2 << \" \" << m.y2 << \"\\n\";\n    }\n    return 0;\n}","toyota2023summer-final":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Grid fixed at 9\u00d79\nstatic const int MAXD = 9;\nint D, N, C;\n\n// Obstacles + static BFS\u2010distance from entrance\nbool isObs[MAXD][MAXD];\nint dist0[MAXD][MAXD];\n\n// Occupancy: -1=obs, 0=free, 1=occ\nint occ[MAXD][MAXD];\n// tag stored at (i,j)\nint posT[MAXD][MAXD];\n// global \u201crank\u201d of each cell\nint cellRank[MAXD][MAXD];\n// static degree (# free neighbors ignoring containers)\nint deg0[MAXD][MAXD];\n\n// entrance\nint ex, ey;\n// 4\u2010dirs\nint dx[4]={1,-1,0,0}, dy[4]={0,0,1,-1};\n\n// id mapping\ninline int ID(int i,int j){ return i*D + j; }\n\n// static all\u2010pairs dist ignoring containers\nint distAll[MAXD*MAXD][MAXD*MAXD];\n\n// small struct + queue\nstruct P{ int x,y; };\nstatic P Q[MAXD*MAXD];\n\n// Articulation\u2010point data\nstatic bool visitedAP[MAXD*MAXD], isAP[MAXD*MAXD];\nstatic int disc[MAXD*MAXD], low[MAXD*MAXD], parentAP[MAXD*MAXD], dfsTime;\nvoid dfs_art(int u){\n    visitedAP[u]=true;\n    disc[u]=low[u]=++dfsTime;\n    int ux=u/D, uy=u%D, child=0;\n    for(int k=0;k<4;k++){\n        int vx=ux+dx[k], vy=uy+dy[k];\n        if(vx<0||vx>=D||vy<0||vy>=D) continue;\n        if(occ[vx][vy]!=0) continue;\n        int v=ID(vx,vy);\n        if(!visitedAP[v]){\n            parentAP[v]=u; ++child;\n            dfs_art(v);\n            low[u]=min(low[u],low[v]);\n            if(parentAP[u]!=-1 && low[v]>=disc[u])\n                isAP[u]=true;\n        } else if(v!=parentAP[u]){\n            low[u]=min(low[u],disc[v]);\n        }\n    }\n    if(parentAP[u]==-1 && child>1)\n        isAP[u]=true;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin>>D>>N;\n    ex=0; ey=(D-1)/2;\n    // read obstacles\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++)\n        isObs[i][j]=false;\n    for(int i=0;i<N;i++){\n        int r,c; cin>>r>>c;\n        isObs[r][c]=true;\n    }\n\n    // 1) static BFS from entrance -> dist0\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++)\n        dist0[i][j]=-1;\n    int qs=0, qe=0;\n    dist0[ex][ey]=0;\n    Q[qe++]={ex,ey};\n    while(qs<qe){\n        auto [x,y]=Q[qs++];\n        for(int k=0;k<4;k++){\n            int nx=x+dx[k], ny=y+dy[k];\n            if(nx<0||nx>=D||ny<0||ny>=D) continue;\n            if(isObs[nx][ny]||dist0[nx][ny]!=-1) continue;\n            dist0[nx][ny]=dist0[x][y]+1;\n            Q[qe++]={nx,ny};\n        }\n    }\n\n    // 2) static neighbor\u2010degree deg0\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        if(isObs[i][j]){ deg0[i][j]=0; continue; }\n        int d=0;\n        for(int k=0;k<4;k++){\n            int ni=i+dx[k], nj=j+dy[k];\n            if(ni>=0&&ni<D&&nj>=0&&nj<D && !isObs[ni][nj])\n                d++;\n        }\n        deg0[i][j]=d;\n    }\n\n    // 3) precompute distAll[u][v]\n    int NC=D*D, INF=10000;\n    for(int u=0;u<NC;u++)\n        for(int v=0;v<NC;v++)\n            distAll[u][v]=INF;\n    for(int sx=0;sx<D;sx++) for(int sy=0;sy<D;sy++){\n        if(isObs[sx][sy]) continue;\n        int su=ID(sx,sy);\n        static int dloc[MAXD*MAXD];\n        for(int v=0;v<NC;v++) dloc[v]=INF;\n        int lqs=0, lqe=0;\n        dloc[su]=0;\n        Q[lqe++]={sx,sy};\n        while(lqs<lqe){\n            auto [x,y]=Q[lqs++];\n            int cu=ID(x,y);\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(isObs[nx][ny]) continue;\n                int vu=ID(nx,ny);\n                if(dloc[vu]>dloc[cu]+1){\n                    dloc[vu]=dloc[cu]+1;\n                    Q[lqe++]={nx,ny};\n                }\n            }\n        }\n        for(int v=0;v<NC;v++)\n            distAll[su][v]=dloc[v];\n    }\n\n    // 4) build global list S sorted by (dist0 asc, deg0 desc, i, j)\n    vector<P> S;\n    S.reserve(NC);\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        if(isObs[i][j]||(i==ex&&j==ey)) continue;\n        S.push_back({i,j});\n    }\n    sort(S.begin(), S.end(), [&](auto &a, auto &b){\n        int da=dist0[a.x][a.y], db=dist0[b.x][b.y];\n        if(da!=db) return da<db;\n        int ga=deg0[a.x][a.y], gb=deg0[b.x][b.y];\n        if(ga!=gb) return ga>gb;\n        if(a.x!=b.x) return a.x<b.x;\n        return a.y<b.y;\n    });\n    for(int idx=0; idx<(int)S.size(); idx++){\n        cellRank[S[idx].x][S[idx].y]=idx;\n    }\n\n    // init occupancy\n    C = NC - 1 - N;\n    for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n        occ[i][j]   = isObs[i][j] ? -1 : 0;\n        posT[i][j] = -1;\n    }\n\n    // --- Storing (online) ---\n    for(int step=0; step<C; step++){\n        int t; cin>>t;\n\n        // a) BFS on occ==0 \u2192 vis + distCur\n        static bool vis[MAXD][MAXD];\n        static int distCur[MAXD][MAXD];\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            vis[i][j]=false;\n            distCur[i][j]=INF;\n        }\n        int rqs=0, rqe=0;\n        vis[ex][ey]=true;\n        distCur[ex][ey]=0;\n        Q[rqe++]={ex,ey};\n        while(rqs<rqe){\n            auto [x,y]=Q[rqs++];\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(vis[nx][ny]||occ[nx][ny]!=0) continue;\n                vis[nx][ny]=true;\n                distCur[nx][ny]=distCur[x][y]+1;\n                Q[rqe++]={nx,ny};\n            }\n        }\n\n        // b) mark APs\n        for(int u=0;u<NC;u++){\n            visitedAP[u]=false;\n            isAP[u]=false;\n            parentAP[u]=-1;\n        }\n        dfsTime=0;\n        dfs_art(ID(ex,ey));\n\n        // c) pick best candidate by\n        //    ( err, dynDist, staDist, -degCur, -deg0, cellRank )\n        int sx=S[t].x, sy=S[t].y, su=ID(sx,sy);\n        int bestErr=INT_MAX, bestDyn=INF, bestSta=INF;\n        int bestCur=-1, bestSt0=-1, bestR=INT_MAX;\n        int bx=-1, by=-1;\n\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            if(i==ex&&j==ey) continue;\n            if(!vis[i][j]||occ[i][j]!=0) continue;\n            int u=ID(i,j);\n            if(isAP[u]) continue;\n            int rnk = cellRank[i][j];\n            int err = abs(rnk - t);\n            int dyn = distCur[i][j];\n            int sta = distAll[su][u];\n            // dynamic degree\n            int cur=0;\n            for(int d=0;d<4;d++){\n                int nx=i+dx[d], ny=j+dy[d];\n                if(nx>=0&&nx<D&&ny>=0&&ny<D && occ[nx][ny]==0)\n                    cur++;\n            }\n            int st0 = deg0[i][j];\n            // lex compare:\n            if(err<bestErr\n            || (err==bestErr && dyn<bestDyn)\n            || (err==bestErr && dyn==bestDyn && sta<bestSta)\n            || (err==bestErr && dyn==bestDyn && sta==bestSta && cur>bestCur)\n            || (err==bestErr && dyn==bestDyn && sta==bestSta && cur==bestCur && st0>bestSt0)\n            || (err==bestErr && dyn==bestDyn && sta==bestSta && cur==bestCur && st0==bestSt0 && rnk<bestR))\n            {\n                bestErr=err; bestDyn=dyn; bestSta=sta;\n                bestCur=cur; bestSt0=st0; bestR=rnk;\n                bx=i; by=j;\n            }\n        }\n        // fallback if none\n        if(bx<0){\n            for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n                if(i==ex&&j==ey) continue;\n                if(!vis[i][j]||occ[i][j]!=0) continue;\n                int u=ID(i,j);\n                int rnk = cellRank[i][j];\n                int err = abs(rnk - t);\n                int dyn = distCur[i][j];\n                int sta = distAll[su][u];\n                int cur=0;\n                for(int d=0;d<4;d++){\n                    int nx=i+dx[d], ny=j+dy[d];\n                    if(nx>=0&&nx<D&&ny>=0&&ny<D && occ[nx][ny]==0)\n                        cur++;\n                }\n                int st0 = deg0[i][j];\n                if(err<bestErr\n                || (err==bestErr && dyn<bestDyn)\n                || (err==bestErr && dyn==bestDyn && sta<bestSta)\n                || (err==bestErr && dyn==bestDyn && sta==bestSta && cur>bestCur)\n                || (err==bestErr && dyn==bestDyn && sta==bestSta && cur==bestCur && st0>bestSt0)\n                || (err==bestErr && dyn==bestDyn && sta==bestSta && cur==bestCur && st0==bestSt0 && rnk<bestR))\n                {\n                    bestErr=err; bestDyn=dyn; bestSta=sta;\n                    bestCur=cur; bestSt0=st0; bestR=rnk;\n                    bx=i; by=j;\n                }\n            }\n        }\n\n        occ[bx][by]=1;\n        posT[bx][by]=t;\n        cout<<bx<<\" \"<<by<<\"\\n\"<<flush;\n    }\n\n    // --- Retrieval (offline) greedy by smallest\u2010tag ---\n    vector<pair<int,int>> ans;\n    ans.reserve(C);\n    for(int step=0; step<C; step++){\n        static bool vis2[MAXD][MAXD];\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++)\n            vis2[i][j]=false;\n        int rqs=0, rqe=0;\n        vis2[ex][ey]=true;\n        Q[rqe++]={ex,ey};\n        while(rqs<rqe){\n            auto [x,y]=Q[rqs++];\n            for(int k=0;k<4;k++){\n                int nx=x+dx[k], ny=y+dy[k];\n                if(nx<0||nx>=D||ny<0||ny>=D) continue;\n                if(vis2[nx][ny]||occ[nx][ny]!=0) continue;\n                vis2[nx][ny]=true;\n                Q[rqe++]={nx,ny};\n            }\n        }\n        int pickT=INT_MAX, px=-1, py=-1;\n        for(int i=0;i<D;i++) for(int j=0;j<D;j++){\n            if(occ[i][j]!=1) continue;\n            bool ok=false;\n            for(int k=0;k<4 && !ok;k++){\n                int nx=i+dx[k], ny=j+dy[k];\n                if(nx>=0&&nx<D&&ny>=0&&ny<D && vis2[nx][ny])\n                    ok=true;\n            }\n            if(!ok) continue;\n            int tt=posT[i][j];\n            if(tt<pickT){\n                pickT=tt; px=i; py=j;\n            }\n        }\n        occ[px][py]=0;\n        ans.emplace_back(px,py);\n    }\n\n    for(auto &p: ans){\n        cout<<p.first<<\" \"<<p.second<<\"\\n\";\n    }\n    cout<<flush;\n    return 0;\n}","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nstatic const int N = 50;\nstatic const int M = 100;\nstatic int c[N][N], bestD[N][N];\nstatic bool initial_adj[M+1][M+1], initial_out[M+1];\nstatic int d[N][N], color_count[M+1], adjCnt[M+1][M+1], deg[N][N];\nstatic bool seen[N][N];\nstatic pair<int,int> qbuf[N*N];\nstatic int dx[4]={-1,1,0,0}, dy[4]={0,0,-1,1};\n\n// Check if removing d[ri][rj] would disconnect its color\u2010region\ninline bool ward_conn(int ri,int rj){\n    int x=d[ri][rj], need=color_count[x]-1;\n    if(need<=0) return false;\n    int sx=-1, sy=-1;\n    for(int k=0;k<4;k++){\n        int ni=ri+dx[k], nj=rj+dy[k];\n        if(ni>=0&&ni<N&&nj>=0&&nj<N && d[ni][nj]==x){\n            sx=ni; sy=nj; break;\n        }\n    }\n    if(sx<0) return false;\n    memset(seen,0,sizeof(seen));\n    int qh=0, qt=0, cnt=1;\n    seen[sx][sy]=true; qbuf[qt++]={sx,sy};\n    while(qh<qt && cnt<need){\n        auto [i,j]=qbuf[qh++];\n        for(int k=0;k<4;k++){\n            int ni=i+dx[k], nj=j+dy[k];\n            if(ni==ri&&nj==rj) continue;\n            if(ni<0||ni>=N||nj<0||nj>=N) continue;\n            if(!seen[ni][nj] && d[ni][nj]==x){\n                seen[ni][nj]=true;\n                qbuf[qt++]={ni,nj};\n                cnt++;\n            }\n        }\n    }\n    return cnt==need;\n}\n\n// Test if we can safely paint (i,j) \u2192 0 now\ninline bool can_remove(int i,int j){\n    int x=d[i][j];\n    if(x==0) return false;\n    int zeroAdj=0;\n    int neigh[4], nc=0;\n    static int neighCnt[M+1];\n    memset(neighCnt,0,sizeof(neighCnt));\n    for(int k=0;k<4;k++){\n        int ni=i+dx[k], nj=j+dy[k];\n        if(ni<0||ni>=N||nj<0||nj>=N){\n            zeroAdj++;\n        } else {\n            int y=d[ni][nj];\n            if(y==0){\n                zeroAdj++;\n            } else if(y!=x){\n                if(neighCnt[y]==0) neigh[nc++]=y;\n                neighCnt[y]++;\n            }\n        }\n    }\n    if(zeroAdj==0) return false;\n    // preserve x\u2013y\n    for(int t=0;t<nc;t++){\n        int y=neigh[t];\n        if(initial_adj[x][y] && adjCnt[x][y] <= neighCnt[y])\n            return false;\n    }\n    // preserve x\u2013outside\n    if(initial_out[x] && adjCnt[x][0] <= zeroAdj)\n        return false;\n    // never introduce 0\u2013y for forbidden y\n    if(!initial_out[x]) return false;\n    for(int t=0;t<nc;t++){\n        int y=neigh[t];\n        if(!initial_out[y]) return false;\n    }\n    // connectivity\n    if(deg[i][j]>1 && !ward_conn(i,j)) return false;\n    return true;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n,m;\n    cin>>n>>m;  // n==50, m==100\n    for(int i=0;i<N;i++)\n        for(int j=0;j<N;j++)\n            cin>>c[i][j];\n\n    // 1) Build initial adjacency requirements from input\n    memset(initial_adj,0,sizeof(initial_adj));\n    memset(initial_out,0,sizeof(initial_out));\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            int x=c[i][j];\n            if(i==0||i==N-1||j==0||j==N-1)\n                initial_out[x]=true;\n            for(int k=0;k<4;k++){\n                int ni=i+dx[k], nj=j+dy[k];\n                if(ni<0||ni>=N||nj<0||nj>=N){\n                    initial_adj[x][0]=true;\n                } else {\n                    int y=c[ni][nj];\n                    if(y!=x) initial_adj[x][y]=true;\n                }\n            }\n        }\n    }\n\n    // timing & RNG\n    auto T0 = chrono::steady_clock::now();\n    const double TL = 1.9;\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n    // ---------------------------------------------------------\n    // Phase 1: deterministic greedy slack\u2010peel on the input map\n    // ---------------------------------------------------------\n    // init from c[][]\n    memset(color_count,0,sizeof(color_count));\n    memset(adjCnt,0,sizeof(adjCnt));\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            d[i][j]=c[i][j];\n            color_count[d[i][j]]++;\n        }\n    }\n    // build adjCnt\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            int x=d[i][j];\n            for(int k=0;k<4;k++){\n                int ni=i+dx[k], nj=j+dy[k];\n                if(ni<0||ni>=N||nj<0||nj>=N)\n                    adjCnt[x][0]++;\n                else\n                    adjCnt[x][ d[ni][nj] ]++;\n            }\n        }\n    }\n    // build deg[][]\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            int x=d[i][j], cdeg=0;\n            for(int k=0;k<4;k++){\n                int ni=i+dx[k], nj=j+dy[k];\n                if(ni>=0&&ni<N&&nj>=0&&nj<N && d[ni][nj]==x)\n                    cdeg++;\n            }\n            deg[i][j]=cdeg;\n        }\n    }\n\n    // greedy slack\u2010peel loop\n    while(true){\n        vector<pair<int,int>> cand;\n        vector<int> slack;\n        cand.reserve(N*N);\n        slack.reserve(N*N);\n\n        for(int i=0;i<N;i++){\n            for(int j=0;j<N;j++){\n                if(!can_remove(i,j)) continue;\n                int x=d[i][j];\n                int zeroAdj=0;\n                static int nCnt[M+1];\n                memset(nCnt,0,sizeof(nCnt));\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni<0||ni>=N||nj<0||nj>=N ||\n                       (ni>=0&&ni<N&&nj>=0&&nj<N && d[ni][nj]==0))\n                        zeroAdj++;\n                }\n                int minS = INT_MAX;\n                if(initial_out[x])\n                    minS = min(minS, adjCnt[x][0] - zeroAdj);\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni>=0&&ni<N&&nj>=0&&nj<N){\n                        int y=d[ni][nj];\n                        if(y>0 && y!=x && initial_adj[x][y] && !nCnt[y]){\n                            nCnt[y]=1;\n                            int e=0;\n                            for(int kk=0;kk<4;kk++){\n                                int ui=i+dx[kk], uj=j+dy[kk];\n                                if(ui>=0&&ui<N&&uj>=0&&uj<N && d[ui][uj]==y)\n                                    e++;\n                            }\n                            minS = min(minS, adjCnt[x][y] - e);\n                        }\n                    }\n                }\n                cand.emplace_back(i,j);\n                slack.push_back(minS);\n            }\n        }\n        if(cand.empty()) break;\n        int best=0;\n        for(int t=1;t<(int)cand.size();t++){\n            if(slack[t]>slack[best]) best=t;\n        }\n        auto [ri,rj] = cand[best];\n        int x=d[ri][rj];\n        d[ri][rj]=0;\n        color_count[x]--;\n        // update adjCnt & deg\n        for(int k=0;k<4;k++){\n            int ni=ri+dx[k], nj=rj+dy[k];\n            if(ni<0||ni>=N||nj<0||nj>=N){\n                adjCnt[x][0]--;\n            } else {\n                int y=d[ni][nj];\n                adjCnt[x][y]--; adjCnt[y][x]--;\n                if(y==x) deg[ni][nj]--;\n                if(y!=0) adjCnt[y][0]++;\n            }\n        }\n    }\n\n    // save initial best\n    int bestZeros=0;\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            bestD[i][j]=d[i][j];\n            if(d[i][j]==0) bestZeros++;\n        }\n    }\n\n    // ----------------------------------------------------------------\n    // Phase 2: weighted multi\u2010start peel (five peel\u2010orders, hill\u2010climb)\n    // ----------------------------------------------------------------\n    auto time_up = [&](){\n        return chrono::duration<double>(\n            chrono::steady_clock::now() - T0\n        ).count() > TL;\n    };\n\n    for(int attempt=0;;attempt++){\n        if(time_up()) break;\n        bool use_best = (attempt & 1);\n        // re\u2010init from c or bestD\n        memset(color_count,0,sizeof(color_count));\n        memset(adjCnt,0,sizeof(adjCnt));\n        for(int i=0;i<N;i++){\n            for(int j=0;j<N;j++){\n                d[i][j] = use_best ? bestD[i][j] : c[i][j];\n                color_count[d[i][j]]++;\n            }\n        }\n        // rebuild adjCnt\n        for(int i=0;i<N;i++){\n            for(int j=0;j<N;j++){\n                int x=d[i][j];\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni<0||ni>=N||nj<0||nj>=N)\n                        adjCnt[x][0]++;\n                    else\n                        adjCnt[x][ d[ni][nj] ]++;\n                }\n            }\n        }\n        // rebuild deg\n        for(int i=0;i<N;i++){\n            for(int j=0;j<N;j++){\n                int x=d[i][j], cdeg=0;\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni>=0&&ni<N&&nj>=0&&nj<N && d[ni][nj]==x)\n                        cdeg++;\n                }\n                deg[i][j]=cdeg;\n            }\n        }\n        // collect removables\n        vector<pair<int,int>> stk;\n        stk.reserve(N*N);\n        for(int i=0;i<N;i++){\n            for(int j=0;j<N;j++){\n                if(can_remove(i,j))\n                    stk.emplace_back(i,j);\n            }\n        }\n        // weighted peel order\n        int r=rng()%100, mode;\n        if(r<5)        mode=0;  // pure random\n        else if(r<40)  mode=1;  // low\u2010degree\n        else if(r<50)  mode=2;  // high\u2010degree\n        else if(r<85)  mode=3;  // low\u2010adj\u2010weight\n        else            mode=4;  // slack\u2010peel\n\n        if(mode==1){\n            sort(stk.begin(), stk.end(),\n                [&](auto &A,auto &B){\n                  return deg[A.first][A.second]\n                       < deg[B.first][B.second];\n                });\n        } else if(mode==2){\n            sort(stk.begin(), stk.end(),\n                [&](auto &A,auto &B){\n                  return deg[A.first][A.second]\n                       > deg[B.first][B.second];\n                });\n        } else if(mode==3){\n            int S=stk.size();\n            static int w[N*N];\n            for(int t=0;t<S;t++){\n                auto [i,j]=stk[t];\n                int x=d[i][j], cnt=0;\n                static bool seenY[M+1];\n                memset(seenY,0,sizeof(seenY));\n                if(initial_out[x]){\n                    bool t0=false;\n                    for(int k=0;k<4&&!t0;k++){\n                        int ni=i+dx[k], nj=j+dy[k];\n                        if(ni<0||ni>=N||nj<0||nj>=N) t0=true;\n                        else if(d[ni][nj]==0) t0=true;\n                    }\n                    if(t0){ seenY[0]=true; cnt++; }\n                }\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni>=0&&ni<N&&nj>=0&&nj<N){\n                        int y=d[ni][nj];\n                        if(y>0&&y!=x && initial_adj[x][y] && !seenY[y]){\n                            seenY[y]=true; cnt++;\n                        }\n                    }\n                }\n                w[t]=cnt;\n            }\n            vector<int> idx(S);\n            iota(idx.begin(), idx.end(), 0);\n            sort(idx.begin(), idx.end(),\n                [&](int a,int b){ return w[a]<w[b]; });\n            vector<pair<int,int>> tmp;\n            tmp.reserve(S);\n            for(int id:idx) tmp.push_back(stk[id]);\n            stk.swap(tmp);\n        } else if(mode==4){\n            int S=stk.size();\n            static int slack[N*N];\n            for(int t=0;t<S;t++){\n                auto [i,j]=stk[t];\n                int x=d[i][j];\n                int zeroAdj=0;\n                static int nCnt[M+1];\n                memset(nCnt,0,sizeof(nCnt));\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni<0||ni>=N||nj<0||nj>=N ||\n                       (ni>=0&&ni<N&&nj>=0&&nj<N && d[ni][nj]==0)){\n                        zeroAdj++;\n                    }\n                }\n                int minS=INT_MAX;\n                if(initial_out[x]){\n                    minS = min(minS, adjCnt[x][0] - zeroAdj);\n                }\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni>=0&&ni<N&&nj>=0&&nj<N){\n                        int y=d[ni][nj];\n                        if(y>0&&y!=x && initial_adj[x][y] && nCnt[y]==0){\n                            nCnt[y]=1;\n                            int e=0;\n                            for(int kk=0;kk<4;kk++){\n                                int ui=i+dx[kk], uj=j+dy[kk];\n                                if(ui>=0&&ui<N&&uj>=0&&uj<N && d[ui][uj]==y)\n                                    e++;\n                            }\n                            minS = min(minS, adjCnt[x][y] - e);\n                        }\n                    }\n                }\n                slack[t]=minS;\n            }\n            vector<int> idx(S);\n            iota(idx.begin(), idx.end(), 0);\n            sort(idx.begin(), idx.end(),\n                [&](int a,int b){ return slack[a]>slack[b]; });\n            vector<pair<int,int>> tmp;\n            tmp.reserve(S);\n            for(int id:idx) tmp.push_back(stk[id]);\n            stk.swap(tmp);\n        } else {\n            shuffle(stk.begin(), stk.end(), rng);\n        }\n\n        // peel\n        bool timeout=false;\n        int ops=0;\n        while(!stk.empty()){\n            if((++ops & 0x3FF)==0 && time_up()){\n                timeout = true; break;\n            }\n            auto [i,j] = stk.back(); stk.pop_back();\n            int x=d[i][j];\n            if(x==0 || !can_remove(i,j)) continue;\n            d[i][j]=0; color_count[x]--;\n            for(int k=0;k<4;k++){\n                int ni=i+dx[k], nj=j+dy[k];\n                if(ni<0||ni>=N||nj<0||nj>=N){\n                    adjCnt[x][0]--;\n                } else {\n                    int y=d[ni][nj];\n                    adjCnt[x][y]--; adjCnt[y][x]--;\n                    if(y==x) deg[ni][nj]--;\n                    if(y!=0) adjCnt[y][0]++;\n                }\n            }\n            for(int k=0;k<4;k++){\n                int ni=i+dx[k], nj=j+dy[k];\n                if(ni>=0&&ni<N&&nj>=0&&nj<N && d[ni][nj]!=0){\n                    if(can_remove(ni,nj))\n                        stk.emplace_back(ni,nj);\n                }\n            }\n        }\n        if(timeout) break;\n\n        // score\n        int zeros=0;\n        for(int i=0;i<N;i++)\n            for(int j=0;j<N;j++)\n                zeros += (d[i][j]==0);\n        if(zeros>bestZeros){\n            bestZeros=zeros;\n            for(int i=0;i<N;i++)\n                for(int j=0;j<N;j++)\n                    bestD[i][j]=d[i][j];\n        }\n    }\n\n    // --------------------------------------------------------\n    // Phase 3: final deterministic slack\u2010peel on bestD\n    // --------------------------------------------------------\n    if(!time_up()){\n        // re\u2010init from bestD\n        memset(color_count,0,sizeof(color_count));\n        memset(adjCnt,0,sizeof(adjCnt));\n        for(int i=0;i<N;i++){\n            for(int j=0;j<N;j++){\n                d[i][j]=bestD[i][j];\n                color_count[d[i][j]]++;\n            }\n        }\n        for(int i=0;i<N;i++){\n            for(int j=0;j<N;j++){\n                int x=d[i][j];\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni<0||ni>=N||nj<0||nj>=N)\n                        adjCnt[x][0]++;\n                    else\n                        adjCnt[x][ d[ni][nj] ]++;\n                }\n            }\n        }\n        for(int i=0;i<N;i++){\n            for(int j=0;j<N;j++){\n                int x=d[i][j], cdeg=0;\n                for(int k=0;k<4;k++){\n                    int ni=i+dx[k], nj=j+dy[k];\n                    if(ni>=0&&ni<N&&nj>=0&&nj<N && d[ni][nj]==x)\n                        cdeg++;\n                }\n                deg[i][j]=cdeg;\n            }\n        }\n\n        while(!time_up()){\n            vector<pair<int,int>> cand;\n            vector<int> slack;\n            cand.reserve(N*N);\n            slack.reserve(N*N);\n            for(int i=0;i<N;i++){\n                for(int j=0;j<N;j++){\n                    if(!can_remove(i,j)) continue;\n                    int x=d[i][j];\n                    int zeroAdj=0;\n                    static int nCnt[M+1];\n                    memset(nCnt,0,sizeof(nCnt));\n                    for(int k=0;k<4;k++){\n                        int ni=i+dx[k], nj=j+dy[k];\n                        if(ni<0||ni>=N||nj<0||nj>=N ||\n                           (ni>=0&&ni<N&&nj>=0&&nj<N && d[ni][nj]==0))\n                            zeroAdj++;\n                    }\n                    int minS=INT_MAX;\n                    if(initial_out[x])\n                        minS = min(minS, adjCnt[x][0] - zeroAdj);\n                    for(int k=0;k<4;k++){\n                        int ni=i+dx[k], nj=j+dy[k];\n                        if(ni>=0&&ni<N&&nj>=0&&nj<N){\n                            int y=d[ni][nj];\n                            if(y>0 && y!=x && initial_adj[x][y] && !nCnt[y]){\n                                nCnt[y]=1;\n                                int e=0;\n                                for(int kk=0;kk<4;kk++){\n                                    int ui=i+dx[kk], uj=j+dy[kk];\n                                    if(ui>=0&&ui<N&&uj>=0&&uj<N && d[ui][uj]==y)\n                                        e++;\n                                }\n                                minS = min(minS, adjCnt[x][y] - e);\n                            }\n                        }\n                    }\n                    cand.emplace_back(i,j);\n                    slack.push_back(minS);\n                }\n            }\n            if(cand.empty()) break;\n            int best=0;\n            for(int t=1;t<(int)cand.size();t++){\n                if(slack[t]>slack[best]) best=t;\n            }\n            auto [ri,rj] = cand[best];\n            int x=d[ri][rj];\n            d[ri][rj]=0;\n            color_count[x]--;\n            for(int k=0;k<4;k++){\n                int ni=ri+dx[k], nj=rj+dy[k];\n                if(ni<0||ni>=N||nj<0||nj>=N){\n                    adjCnt[x][0]--;\n                } else {\n                    int y=d[ni][nj];\n                    adjCnt[x][y]--; adjCnt[y][x]--;\n                    if(y==x) deg[ni][nj]--;\n                    if(y!=0) adjCnt[y][0]++;\n                }\n            }\n        }\n        // update bestD if improved\n        int zeros=0;\n        for(int i=0;i<N;i++){\n            for(int j=0;j<N;j++){\n                if(d[i][j]==0) zeros++;\n            }\n        }\n        if(zeros>bestZeros){\n            bestZeros = zeros;\n            for(int i=0;i<N;i++)\n                for(int j=0;j<N;j++)\n                    bestD[i][j] = d[i][j];\n        }\n    }\n\n    // 4) Output best map\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            cout<<bestD[i][j]<<(j+1<N?' ':'\\n');\n        }\n    }\n    return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\n//\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\n// Interactive primitives\nint N, D, Q, usedQ;\nvector<int> comp_cache;  // for mergesort\n\n// Issue exactly one balance\u2010query {i} vs {j}\nint raw_query(int i, int j){\n    cout << 1 << \" \" << 1 << \" \" << i << \" \" << j << \"\\n\" << flush;\n    char c; \n    cin >> c;\n    usedQ++;\n    if(c=='>') return +1;\n    if(c=='<') return -1;\n    return 0;\n}\n\n// Cached comparator for mergesort\nint compare_cached(int i, int j){\n    if(i==j) return 0;\n    int &c = comp_cache[i*N + j];\n    if(c != -2) return c;\n    int r = raw_query(i,j);\n    c = r;\n    comp_cache[j*N + i] = -r;\n    return r;\n}\n\n// Simple mergesort on item\u2010IDs using compare_cached\nvector<int> interactive_mergesort(const vector<int>& A){\n    int n = A.size();\n    if(n<=1) return A;\n    int m = n/2;\n    auto L = interactive_mergesort({A.begin(), A.begin()+m});\n    auto R = interactive_mergesort({A.begin()+m, A.end()});\n    vector<int> M; M.reserve(n);\n    int i=0, j=0;\n    while(i<(int)L.size() && j<(int)R.size()){\n        int v = compare_cached(L[i], R[j]);\n        if(v>0 || (v==0 && L[i]<R[j])) M.push_back(L[i++]);\n        else                           M.push_back(R[j++]);\n    }\n    while(i<(int)L.size())  M.push_back(L[i++]);\n    while(j<(int)R.size())  M.push_back(R[j++]);\n    return M;\n}\n//\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> D >> Q;\n    comp_cache.assign(N*N, -2);\n    usedQ = 0;\n\n    // cost to fully sort = N * ceil(log2 N)\n    int LG=0;\n    while((1<<LG) < N) LG++;\n    long long needSort = 1LL * N * LG;\n\n    mt19937_64 rng( chrono::steady_clock::now().time_since_epoch().count() );\n\n    vector<int> answer(N, -1);\n\n    if(Q >= needSort){\n        //------------------------------------------------------------\n        // FULL\u2010SORT BRANCH\n        //------------------------------------------------------------\n        // 1) Fully sort by comparisons\n        vector<int> ids(N);\n        iota(ids.begin(), ids.end(), 0);\n        auto sorted = interactive_mergesort(ids);\n\n        // record rank_of[id]\n        vector<int> rank_of(N);\n        for(int r=0;r<N;r++) rank_of[ sorted[r] ] = r;\n\n        // 2) start dynamic assignment of the heaviest items\n        //    we will assign sorted[0..M-1] exactly,\n        //    then tail sorted[M..N-1] by offline LPT.\n        int used0 = usedQ;\n\n        // --- seed first D bins, one each (no queries needed) ---\n        vector<vector<int>> bins(D);\n        vector<int> approx_load(D,0);\n        for(int b=0;b<D;b++){\n            int id = sorted[b];\n            answer[id] = b;\n            bins[b].push_back(id);\n            // approximate weight = N-1 - rank\n            approx_load[b] = (N-1 - rank_of[id]);\n        }\n\n        // --- build a binary tournament tree over D leaves ---\n        int P=1;\n        while(P < D) P<<=1;\n        vector<int> tree(2*P, -1);\n        // leaves\n        for(int i=0;i<P;i++){\n            tree[P + i] = (i < D ? i : -1);\n        }\n        // build internal nodes\n        for(int i=P-1;i>=1;i--){\n            int L = tree[2*i], R = tree[2*i+1];\n            if(L>=0 && R>=0){\n                // compare bins[L] vs bins[R]\n                auto &BL = bins[L], &BR = bins[R];\n                cout << BL.size() << \" \" << BR.size();\n                for(int x:BL) cout << \" \" << x;\n                for(int x:BR) cout << \" \" << x;\n                cout << \"\\n\" << flush;\n                char c; cin >> c; usedQ++;\n                if(c=='<') tree[i] = L;   // left lighter\n                else if(c=='>') tree[i] = R;\n                else tree[i] = (L<R?L:R);\n            } else {\n                tree[i] = (L>=0?L:R);\n            }\n        }\n\n        // --- we spent (D-1) queries building the tree ---\n        int used1 = usedQ - used0;  // should be D-1\n\n        // tree[1] is current lightest\u2010bin\n        int depth = 0; for(int t=P; t>1; t>>=1) depth++;\n        // how many more items can we assign exactly?\n        int Q_rem = Q - usedQ;\n        int canMore = Q_rem / depth;\n        int M = min(N, D + canMore);\n\n        // --- assign sorted[D..M-1] one by one ---\n        for(int idx=D; idx<M; idx++){\n            int id = sorted[idx];\n            int b = tree[1];  // lightest bin\n            answer[id] = b;\n            bins[b].push_back(id);\n            approx_load[b] += (N-1 - rank_of[id]);\n            // update tree on leaf b\n            int node = P + b;\n            tree[node] = b;\n            node >>= 1;\n            while(node>=1){\n                int L = tree[2*node], R = tree[2*node+1];\n                if(L>=0 && R>=0){\n                    auto &BL = bins[L], &BR = bins[R];\n                    cout << BL.size() << \" \" << BR.size();\n                    for(int x:BL) cout << \" \" << x;\n                    for(int x:BR) cout << \" \" << x;\n                    cout << \"\\n\" << flush;\n                    char c; cin >> c; usedQ++;\n                    if(c=='<') tree[node] = L;\n                    else if(c=='>') tree[node] = R;\n                    else tree[node] = (L<R?L:R);\n                } else {\n                    tree[node] = (L>=0?L:R);\n                }\n                node >>= 1;\n            }\n        }\n\n        // --- burn any leftover queries (< depth) ---\n        while(usedQ < Q){\n            // compare bin 0 vs bin 1 (both non-empty)\n            auto &B0 = bins[0], &B1 = bins[1];\n            cout << B0.size() << \" \" << B1.size();\n            for(int x:B0) cout << \" \" << x;\n            for(int x:B1) cout << \" \" << x;\n            cout << \"\\n\" << flush;\n            char c; cin >> c; usedQ++;\n        }\n\n        // --- tail: assign sorted[M..N-1] by offline LPT on approx_load ---\n        for(int idx=M; idx<N; idx++){\n            int id = sorted[idx];\n            // pick bin with minimum approx_load\n            int best = 0;\n            for(int b=1;b<D;b++){\n                if(approx_load[b] < approx_load[best]) best = b;\n            }\n            answer[id] = best;\n            approx_load[best] += (N-1 - rank_of[id]);\n        }\n    }\n    else {\n        //------------------------------------------------------------\n        // FALLBACK BRANCH (Q < needSort)\n        //------------------------------------------------------------\n        // sample win\u2010rates + LPT\n        vector<int> wins(N,0), comps(N,0);\n        int base = Q / N, rem = Q % N;\n        for(int i=0;i<N;i++){\n            comps[i] = base + (i<rem);\n            for(int k=0;k<comps[i];k++){\n                int j = rng() % (N-1);\n                if(j>=i) ++j;\n                int r = raw_query(i,j);\n                if(r>=0) wins[i]++;\n            }\n        }\n        // pseudo\u2010weights\n        vector<double> w(N);\n        for(int i=0;i<N;i++){\n            double ratio = comps[i]? double(wins[i])/comps[i] : 0.0;\n            w[i] = ratio * N + (rng()%1000)*1e-6;\n        }\n        vector<int> order(N);\n        iota(order.begin(), order.end(), 0);\n        shuffle(order.begin(), order.end(), rng);\n        stable_sort(order.begin(), order.end(),\n                    [&](int a,int b){ return w[a] > w[b]; });\n        vector<double> load(D,0.0);\n        for(int id: order){\n            int best=0;\n            for(int b=1;b<D;b++){\n                if(load[b]<load[best]) best=b;\n            }\n            answer[id]=best;\n            load[best]+=w[id];\n        }\n    }\n\n    //\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\n    // Output final assignment\n    for(int i=0;i<N;i++){\n        cout << answer[i] << (i+1==N?'\\n':' ');\n    }\n    cout << flush;\n    return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int INF = 1e9;\n    const int SPLIT_T = 16;     // threshold above which we split\n    int n,m;\n    cin >> n >> m;\n    int H = n/m;\n\n    // read stacks\n    vector<vector<int>> st(m, vector<int>(H));\n    for(int i=0;i<m;i++){\n        for(int j=0;j<H;j++){\n            cin >> st[i][j];\n        }\n    }\n\n    // home stack for each box\n    vector<int> home(n+1);\n    for(int x=1; x<=n; x++){\n        home[x] = (x-1)/H;\n    }\n\n    // current minimum in each stack\n    vector<int> minc(m, INF);\n    for(int t=0;t<m;t++){\n        for(int x: st[t])\n            minc[t] = min(minc[t], x);\n    }\n\n    // long\u2010term busy penalty\n    vector<int> busy(m,0);\n\n    vector<pair<int,int>> ops;\n    ops.reserve(2*n + 1000);\n\n    // weighted\u2010interference + clustering 5\u2010tuple\n    auto choose_best = [&](int s, int seg_min, const vector<int>& benefit){\n        ll best_if = LLONG_MAX;\n        int best_ben = -1, best_busy = INF, best_h = INF, best_mc = -1;\n        int best_t = -1;\n        for(int t=0;t<m;t++){\n            if(t==s) continue;\n            int h = st[t].size();\n            // compute weighted interference\n            ll wif = 0;\n            for(int p=0;p<h;p++){\n                if(st[t][p] < seg_min)\n                    wif += (h-p);\n            }\n            int ben = benefit[t];\n            int bu  = busy[t];\n            int mc  = minc[t];\n            // lex minimize (wif, -ben, busy, height, -minc)\n            bool better = false;\n            if(wif < best_if) better = true;\n            else if(wif == best_if){\n                if(ben > best_ben) better = true;\n                else if(ben == best_ben){\n                    if(bu < best_busy) better = true;\n                    else if(bu == best_busy){\n                        if(h < best_h) better = true;\n                        else if(h == best_h){\n                            if(mc > best_mc) better = true;\n                        }\n                    }\n                }\n            }\n            if(better){\n                best_if    = wif;\n                best_ben   = ben;\n                best_busy  = bu;\n                best_h     = h;\n                best_mc    = mc;\n                best_t     = t;\n            }\n        }\n        return best_t;\n    };\n\n    // Main loop: carry out 1..n\n    for(int v=1; v<=n; v++){\n        // locate v\n        int s=-1, d=-1;\n        for(int t=0;t<m && s<0;t++){\n            for(int p=0;p<(int)st[t].size();p++){\n                if(st[t][p]==v){\n                    s=t; d=p; break;\n                }\n            }\n        }\n        int sz = st[s].size();\n        int above = sz - (d+1);\n\n        // if blocked, handle the segment\n        if(above > 0){\n            // 1) optionally split if too large\n            if(above > SPLIT_T){\n                int idx1 = d+1 + SPLIT_T;\n                int k1   = sz - idx1;  // number to peel\n                int w1   = st[s][idx1]; // box at depth idx1\n\n                // pick an \"empty\" buffer if any\n                int dest1 = -1;\n                for(int t=0;t<m;t++){\n                    if(t!=s && st[t].empty()){\n                        dest1 = t; break;\n                    }\n                }\n                // else fallback to minimal weighted\u2010interference\n                if(dest1<0){\n                    ll best_if = LLONG_MAX;\n                    for(int t=0;t<m;t++){\n                        if(t==s) continue;\n                        int h = st[t].size();\n                        ll wif=0;\n                        for(int p=0;p<h;p++){\n                            if(st[t][p] < st[s][idx1])\n                                wif += (h-p);\n                        }\n                        if(wif < best_if){\n                            best_if = wif;\n                            dest1 = t;\n                        }\n                    }\n                }\n                // perform the peel\n                ops.emplace_back(w1, dest1+1);\n                busy[dest1]++;\n                // cut and move\n                vector<int> tmp;\n                tmp.reserve(k1);\n                for(int p=idx1; p<sz; p++) tmp.push_back(st[s][p]);\n                st[s].resize(idx1);\n                minc[s] = INF;\n                for(int x: st[s]) minc[s]=min(minc[s],x);\n                for(int x: tmp){\n                    st[dest1].push_back(x);\n                    minc[dest1]=min(minc[dest1],x);\n                }\n                // recompute above and sz\n                sz = st[s].size();\n                above = sz - (d+1);\n            }\n\n            // 2) build the remaining blocking segment\n            vector<int> seg;\n            seg.reserve(above);\n            int seg_min = INF;\n            for(int p=d+1; p<sz; p++){\n                int x = st[s][p];\n                seg.push_back(x);\n                seg_min = min(seg_min, x);\n            }\n            // compute benefit\n            vector<int> benefit(m,0);\n            for(int x: seg) benefit[ home[x] ]++;\n\n            // pick best destination via unified 5\u2010tuple\n            int best_t = choose_best(s, seg_min, benefit);\n\n            // do the move\n            int w2 = st[s][d+1];\n            ops.emplace_back(w2, best_t+1);\n            busy[best_t]++;\n            // simulate\n            st[s].resize(d+1);\n            minc[s]=INF;\n            for(int x: st[s]) minc[s]=min(minc[s],x);\n            for(int x: seg){\n                st[best_t].push_back(x);\n                minc[best_t]=min(minc[best_t],x);\n            }\n        }\n\n        // finally carry out v\n        ops.emplace_back(v, 0);\n        st[s].pop_back();\n        minc[s]=INF;\n        for(int x: st[s]) minc[s]=min(minc[s],x);\n    }\n\n    // output\n    for(auto &pr: ops){\n        cout << pr.first << \" \" << pr.second << \"\\n\";\n    }\n    return 0;\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// xorshift64 for quick randomness\nstatic uint64_t _xr = chrono::high_resolution_clock::now().time_since_epoch().count();\ninline uint64_t xor64(){\n    _xr ^= _xr << 13;\n    _xr ^= _xr >> 7;\n    _xr ^= _xr << 17;\n    return _xr;\n}\n\n// Disjoint\u2010set for MST\nstruct DSU {\n    vector<int> p;\n    DSU(int n):p(n,-1){}\n    int find(int x){ return p[x]<0?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(p[a]>p[b]) swap(a,b);\n        p[a]+=p[b];\n        p[b]=a;\n        return true;\n    }\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<string> h(N-1), v(N);\n    for(int i=0;i<N-1;i++) cin >> h[i];\n    for(int i=0;i<N;i++)   cin >> v[i];\n\n    int V = N*N;\n    auto id = [&](int i,int j){ return i*N + j; };\n\n    vector<int> dirt(V);\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            cin >> dirt[id(i,j)];\n        }\n    }\n\n    // Build adjacency + move\u2010labels\n    vector<vector<pair<int,char>>> nbr(V);\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            int u = id(i,j);\n            if(i+1<N && h[i][j]=='0'){\n                int w = id(i+1,j);\n                nbr[u].emplace_back(w,'D');\n                nbr[w].emplace_back(u,'U');\n            }\n            if(j+1<N && v[i][j]=='0'){\n                int w = id(i,j+1);\n                nbr[u].emplace_back(w,'R');\n                nbr[w].emplace_back(u,'L');\n            }\n        }\n    }\n\n    // 1) All\u2013pairs BFS \u2192 dist[src*V + x], fm[...] = first\u2010move from src towards x\n    vector<int16_t> dist(V*V, -1);\n    vector<char>   fm  (V*V,  0);\n    deque<int> Q;\n    for(int src = 0; src < V; src++){\n        int base = src * V;\n        // reset\n        for(int i = 0; i < V; i++) dist[base + i] = -1;\n        dist[base + src] = 0;\n        Q.clear();\n        Q.push_back(src);\n        while(!Q.empty()){\n            int u = Q.front(); Q.pop_front();\n            int du = dist[base + u];\n            for(auto &pc: nbr[u]){\n                int w = pc.first;\n                if(dist[base + w] != -1) continue;\n                dist[base + w] = du + 1;\n                // record first\u2010move\n                if(u == src) fm[base + w] = pc.second;\n                else         fm[base + w] = fm[base + u];\n                Q.push_back(w);\n            }\n        }\n    }\n    auto dptr = dist.data();\n\n    // 2) For 2-opt: precompute each node's K nearest neighbors by BFS-dist\n    const int K = 12;\n    vector<array<int,K>> knn(V);\n    for(int u=0; u<V; u++){\n        priority_queue<pair<int,int>> pq;\n        int base = u*V;\n        for(int w=0; w<V; w++){\n            if(w==u) continue;\n            int d0 = dptr[base + w];\n            if((int)pq.size() < K){\n                pq.emplace(d0, w);\n            } else if(d0 < pq.top().first){\n                pq.pop();\n                pq.emplace(d0, w);\n            }\n        }\n        for(int i=K-1; i>=0; i--){\n            knn[u][i] = pq.top().second;\n            pq.pop();\n        }\n    }\n\n    // 3) Build portfolio of raw orders\n    vector<vector<int>> cands;\n\n    // 3a) pure nearest-neighbor by dirt/dist\n    auto buildNN = [&](bool jitter){\n        const int TOPK = 5;\n        vector<char> used(V,0);\n        vector<int> ord; ord.reserve(V);\n        int cur = 0;\n        used[cur] = 1;\n        ord.push_back(cur);\n        vector<pair<double,int>> top; top.reserve(TOPK);\n\n        for(int step=1; step<V; step++){\n            int pick = -1, base = cur*V;\n            if(!jitter){\n                double bestS = -1;\n                for(int w=0; w<V; w++){\n                    if(used[w]) continue;\n                    double sc = (double)dirt[w] / double(dptr[base + w]);\n                    if(sc > bestS){\n                        bestS = sc;\n                        pick = w;\n                    }\n                }\n            } else {\n                top.clear();\n                for(int w=0; w<V; w++){\n                    if(used[w]) continue;\n                    double sc = (double)dirt[w] / double(dptr[base + w]);\n                    if((int)top.size() < TOPK){\n                        top.emplace_back(sc,w);\n                        if((int)top.size() == TOPK)\n                            sort(top.begin(), top.end());\n                    } else if(sc > top[0].first){\n                        top[0] = {sc,w};\n                        for(int z=0; z+1<TOPK; z++){\n                            if(top[z].first > top[z+1].first)\n                                swap(top[z], top[z+1]);\n                            else break;\n                        }\n                    }\n                }\n                pick = top[xor64() % top.size()].second;\n            }\n            used[pick] = 1;\n            ord.push_back(pick);\n            cur = pick;\n        }\n        return ord;\n    };\n\n    // add pure NN + 3 jittered NN\n    cands.push_back(buildNN(false));\n    for(int i=0;i<3;i++) cands.push_back(buildNN(true));\n\n    // 3b) greedy by pure BFS-dist (ignore dirt)\n    {\n        vector<char> used(V,0);\n        vector<int> ord; ord.reserve(V);\n        int cur = 0;\n        used[cur] = 1;\n        ord.push_back(cur);\n        for(int step=1; step<V; step++){\n            int pick=-1, bestd=INT_MAX, base=cur*V;\n            for(int w=0; w<V; w++){\n                if(used[w]) continue;\n                int dd = dptr[base + w];\n                if(dd < bestd){\n                    bestd=dd;\n                    pick=w;\n                }\n            }\n            used[pick]=1;\n            ord.push_back(pick);\n            cur=pick;\n        }\n        cands.push_back(move(ord));\n    }\n\n    // 3c) row-snake and col-snake\n    {\n        vector<int> r; r.reserve(V);\n        for(int i=0;i<N;i++){\n            if(i%2==0)\n                for(int j=0;j<N;j++) r.push_back(id(i,j));\n            else\n                for(int j=N-1;j>=0;j--) r.push_back(id(i,j));\n        }\n        cands.push_back(move(r));\n    }\n    {\n        vector<int> c; c.reserve(V);\n        for(int j=0;j<N;j++){\n            if(j%2==0)\n                for(int i=0;i<N;i++) c.push_back(id(i,j));\n            else\n                for(int i=N-1;i>=0;i--) c.push_back(id(i,j));\n        }\n        cands.push_back(move(c));\n    }\n\n    // 3d) Hilbert\u2010curve ordering\n    {\n        int B = 1; while((1<<B) < N) B++;\n        int M = 1<<B;\n        auto hilbert = [&](int x,int y){\n            int rx, ry;\n            uint32_t d = 0;\n            for(int s=M>>1; s>0; s>>=1){\n                rx = (x & s) ? 1:0;\n                ry = (y & s) ? 1:0;\n                d <<= 2;\n                d |= (rx*3) ^ ry;\n                // rotate\n                if(ry==0){\n                    if(rx==1){\n                        x = M-1 - x;\n                        y = M-1 - y;\n                    }\n                    swap(x,y);\n                }\n            }\n            return d;\n        };\n        vector<pair<uint32_t,int>> tmp; tmp.reserve(V);\n        for(int i=0;i<N;i++) for(int j=0;j<N;j++){\n            tmp.emplace_back(hilbert(i,j), id(i,j));\n        }\n        sort(tmp.begin(), tmp.end());\n        vector<int> ord; ord.reserve(V);\n        for(auto &p: tmp) ord.push_back(p.second);\n        cands.push_back(move(ord));\n    }\n\n    // 3e) outwards spiral from (0,0)\n    {\n        int r0=0, r1=N-1, c0=0, c1=N-1;\n        vector<int> ord; ord.reserve(V);\n        while(r0<=r1 && c0<=c1){\n            for(int j=c0;j<=c1;j++) ord.push_back(id(r0,j));\n            r0++;\n            for(int i=r0;i<=r1;i++) ord.push_back(id(i,c1));\n            c1--;\n            if(r0<=r1){\n                for(int j=c1;j>=c0;j--) ord.push_back(id(r1,j));\n                r1--;\n            }\n            if(c0<=c1){\n                for(int i=r1;i>=r0;i--) ord.push_back(id(i,c0));\n                c0++;\n            }\n        }\n        cands.push_back(move(ord));\n    }\n\n    // 3f) MST\u2010preorder on KNN graph\n    {\n        struct E{int u,v,w;};\n        vector<E> Elist; Elist.reserve(V*K/2);\n        for(int u=0;u<V;u++){\n            for(int w:knn[u]){\n                if(u<w) Elist.push_back({u,w,dist[u*V + w]});\n            }\n        }\n        sort(Elist.begin(), Elist.end(), [&](auto &a,auto &b){return a.w<b.w;});\n        DSU dsu(V);\n        vector<vector<int>> tadj(V);\n        int cnt=0;\n        for(auto &e:Elist){\n            if(dsu.unite(e.u,e.v)){\n                tadj[e.u].push_back(e.v);\n                tadj[e.v].push_back(e.u);\n                if(++cnt==V-1) break;\n            }\n        }\n        vector<int> ord; ord.reserve(V);\n        vector<char> vis2(V,0);\n        function<void(int)> dfs = [&](int u){\n            vis2[u]=1; ord.push_back(u);\n            for(int w:tadj[u]) if(!vis2[w]) dfs(w);\n        };\n        dfs(0);\n        cands.push_back(move(ord));\n    }\n\n    // 4) Guided 2-opt on each candidate\n    auto twoOpt = [&](vector<int> &ord){\n        int n = V;\n        vector<int> pos(n);\n        for(int i=0;i<n;i++) pos[ord[i]] = i;\n        for(int pass=0; pass<4; pass++){\n            bool improved = false;\n            for(int i=0; i<n-1 && !improved; i++){\n                int A=ord[i], B=ord[i+1];\n                for(int kk=0; kk<K; kk++){\n                    int C = knn[A][kk];\n                    int j = pos[C];\n                    if(j <= i+1) continue;\n                    int D = ord[(j+1)%n];\n                    ll oldc = ll(dptr[A*V+B]) + dptr[C*V + D];\n                    ll newc = ll(dptr[A*V+C]) + dptr[B*V + D];\n                    if(newc < oldc){\n                        reverse(ord.begin()+i+1, ord.begin()+j+1);\n                        for(int x=i+1; x<=j; x++)\n                            pos[ord[x]] = x;\n                        improved = true;\n                        break;\n                    }\n                }\n            }\n            if(!improved) break;\n        }\n    };\n    for(auto &o: cands) twoOpt(o);\n\n    // 5) Measure each tour\u2019s metric-length\n    auto tourLen = [&](const vector<int> &ord){\n        ll s=0;\n        for(int i=0;i+1<V;i++){\n            s += dptr[ ord[i]*V + ord[i+1] ];\n        }\n        s += dptr[ ord[V-1]*V + 0 ];\n        return s;\n    };\n\n    // 6) Compare to DFS-Euler baseline\n    ll bestL = 2LL*(V-1);\n    int bestIdx = -1;  // -1 => Euler\n    for(int i=0; i<(int)cands.size(); i++){\n        ll L = tourLen(cands[i]);\n        if(L < bestL){\n            bestL = L;\n            bestIdx = i;\n        }\n    }\n\n    // 7) Reconstruct the chosen cycle\n    string ans;\n    ans.reserve(bestL+10);\n\n    if(bestIdx < 0){\n        // fallback: simple DFS-Euler on the grid\n        vector<vector<bool>> vis3(N, vector<bool>(N,false));\n        static int di[4]={0,1,0,-1}, dj[4]={1,0,-1,0};\n        static char dc[4] = {'R','D','L','U'};\n        function<void(int,int)> dfs3 = [&](int i,int j){\n            vis3[i][j]=true;\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(vis3[ni][nj]) continue;\n                if(d==0 && v[i][j]!='0') continue;\n                if(d==1 && h[i][j]!='0') continue;\n                if(d==2 && v[i][nj]!='0') continue;\n                if(d==3 && h[ni][j]!='0') continue;\n                ans.push_back(dc[d]);\n                dfs3(ni,nj);\n                ans.push_back(dc[d^2]);\n            }\n        };\n        dfs3(0,0);\n    } else {\n        // stitch BFS-paths along the best TSP\u2010order\n        auto &ord = cands[bestIdx];\n        int cur = 0;\n        auto go = [&](int dst){\n            while(cur != dst){\n                char m = fm[cur*V + dst];\n                ans.push_back(m);\n                int ii = cur / N, jj = cur % N;\n                if(m=='U')    ii--;\n                else if(m=='D') ii++;\n                else if(m=='L') jj--;\n                else             jj++;\n                cur = id(ii,jj);\n            }\n        };\n        for(int x: ord) go(x);\n        go(0);\n    }\n\n    // safety cap\n    if(ans.size()>100000) ans.resize(100000);\n    cout << ans << \"\\n\";\n    return 0;\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int,int>;\nstatic const int INF = 1e9;\n\n// DP tables\nstatic int costMinSuffix[200][5][225], bestEndId[200][5][225];\nstatic int staticMinNext[225];\n// scratch for greedy\nstatic vector<int> letterPosIdx[200][5];\n// scratch for final DP\nstatic int dpPrev[225], dpCur[225], parentPtr[1005][225];\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M;\n    cin >> N >> M;\n    int si, sj;\n    cin >> si >> sj;\n\n    vector<string> A(N), t(M);\n    for(int i=0;i<N;i++) cin >> A[i];\n    for(int k=0;k<M;k++) cin >> t[k];\n\n    // flatten grid\n    int NN = N*N;\n    vector<pii> gridPos(NN);\n    for(int i=0;i<N;i++) for(int j=0;j<N;j++)\n        gridPos[i*N+j] = {i,j};\n\n    // letter -> cells\n    vector<vector<int>> posList(26);\n    for(int id=0;id<NN;id++){\n        auto [i,j]=gridPos[id];\n        posList[A[i][j]-'A'].push_back(id);\n    }\n\n    // word k, char s -> that letter's cells\n    for(int k=0;k<M;k++){\n        for(int s=0;s<5;s++){\n            letterPosIdx[k][s] = posList[t[k][s]-'A'];\n        }\n    }\n\n    // 1) Precompute costMinSuffix[k][s][p0] & bestEndId\n    for(int k=0;k<M;k++){\n        // s=4 base\n        for(int p0=0;p0<NN;p0++){\n            costMinSuffix[k][4][p0]=INF;\n            bestEndId   [k][4][p0]=-1;\n        }\n        for(int pid: letterPosIdx[k][4]){\n            auto [ci,cj]=gridPos[pid];\n            for(int p0=0;p0<NN;p0++){\n                auto [i0,j0]=gridPos[p0];\n                int d=abs(i0-ci)+abs(j0-cj);\n                if(d<costMinSuffix[k][4][p0]){\n                    costMinSuffix[k][4][p0]=d;\n                    bestEndId   [k][4][p0]=pid;\n                }\n            }\n        }\n        // s=3..0\n        for(int s=3;s>=0;s--){\n            for(int p0=0;p0<NN;p0++){\n                costMinSuffix[k][s][p0]=INF;\n                bestEndId   [k][s][p0]=-1;\n            }\n            for(int pid: letterPosIdx[k][s]){\n                int nxt=costMinSuffix[k][s+1][pid];\n                if(nxt>=INF) continue;\n                int ep=bestEndId[k][s+1][pid];\n                auto [ci,cj]=gridPos[pid];\n                for(int p0=0;p0<NN;p0++){\n                    auto [i0,j0]=gridPos[p0];\n                    int d=abs(i0-ci)+abs(j0-cj)+nxt;\n                    if(d<costMinSuffix[k][s][p0]){\n                        costMinSuffix[k][s][p0]=d;\n                        bestEndId   [k][s][p0]=ep;\n                    }\n                }\n            }\n        }\n    }\n\n    // 2) staticMinNext[p0]\n    for(int p0=0;p0<NN;p0++){\n        int mn=INF;\n        for(int k=0;k<M;k++){\n            int c=costMinSuffix[k][0][p0];\n            if(c<INF) mn=min(mn, c+5);\n        }\n        staticMinNext[p0]=mn;\n    }\n\n    // 3) Multi\u2010start randomized greedy on word\u2010order\n    mt19937_64 rng(chrono::high_resolution_clock::now()\n                   .time_since_epoch().count());\n    const int R = 50;\n    vector<bool> used(M);\n    vector<int> seq(M), bestSeq;\n    int bestTotalCost=INF;\n\n    for(int run=0;run<R;run++){\n        fill(used.begin(), used.end(), false);\n        int curId = si*N+sj;\n        string tail;\n        tail.reserve(4);\n        int totalCost=0;\n\n        for(int step=0;step<M;step++){\n            // 3.1 find bestCost\n            int bestCost=INF;\n            for(int k=0;k<M;k++){\n                if(used[k]) continue;\n                int ov=0, mxO=min((int)tail.size(),4);\n                for(int o=mxO;o>=1;o--){\n                    bool ok=true;\n                    for(int x=0;x<o;x++){\n                        if(tail[tail.size()-o+x]!=t[k][x]){\n                            ok=false;break;\n                        }\n                    }\n                    if(ok){ ov=o;break; }\n                }\n                int rem=5-ov;\n                int manh=costMinSuffix[k][ov][curId];\n                if(manh<INF) bestCost=min(bestCost, manh+rem);\n            }\n            int threshold=bestCost + int(rng()&1);\n\n            // 3.2 find bestOv\n            int bestOv=-1;\n            for(int k=0;k<M;k++){\n                if(used[k]) continue;\n                int ov=0, mxO=min((int)tail.size(),4);\n                for(int o=mxO;o>=1;o--){\n                    bool ok=true;\n                    for(int x=0;x<o;x++){\n                        if(tail[tail.size()-o+x]!=t[k][x]){\n                            ok=false;break;\n                        }\n                    }\n                    if(ok){ ov=o;break;}\n                }\n                int rem=5-ov, manh=costMinSuffix[k][ov][curId];\n                if(manh<INF && manh+rem<=threshold)\n                    bestOv=max(bestOv, ov);\n            }\n\n            // 3.3 collect candidates\n            vector<int> cands;\n            for(int k=0;k<M;k++){\n                if(used[k]) continue;\n                int ov=0, mxO=min((int)tail.size(),4);\n                for(int o=mxO;o>=1;o--){\n                    bool ok=true;\n                    for(int x=0;x<o;x++){\n                        if(tail[tail.size()-o+x]!=t[k][x]){\n                            ok=false;break;\n                        }\n                    }\n                    if(ok){ ov=o;break; }\n                }\n                if(ov!=bestOv) continue;\n                int rem=5-ov, manh=costMinSuffix[k][ov][curId];\n                if(manh<INF && manh+rem<=threshold)\n                    cands.push_back(k);\n            }\n\n            // 3.4 break ties by staticMinNext[end]\n            int bestSM=INF;\n            for(int k:cands){\n                int ov=0, mxO=min((int)tail.size(),4);\n                for(int o=mxO;o>=1;o--){\n                    bool ok=true;\n                    for(int x=0;x<o;x++){\n                        if(tail[tail.size()-o+x]!=t[k][x]){\n                            ok=false;break;\n                        }\n                    }\n                    if(ok){ ov=o;break;}\n                }\n                int ep=bestEndId[k][ov][curId];\n                if(ep>=0) bestSM=min(bestSM, staticMinNext[ep]);\n            }\n            vector<int> finalC;\n            for(int k:cands){\n                int ov=0, mxO=min((int)tail.size(),4);\n                for(int o=mxO;o>=1;o--){\n                    bool ok=true;\n                    for(int x=0;x<o;x++){\n                        if(tail[tail.size()-o+x]!=t[k][x]){\n                            ok=false;break;\n                        }\n                    }\n                    if(ok){ ov=o;break;}\n                }\n                int ep=bestEndId[k][ov][curId];\n                if(ep>=0 && staticMinNext[ep]==bestSM)\n                    finalC.push_back(k);\n            }\n\n            int pick = finalC[rng()%finalC.size()];\n            seq[step]=pick;\n            used[pick]=true;\n\n            // 3.5 update totalCost, curId, tail\n            int ov=0, mxO=min((int)tail.size(),4);\n            for(int o=mxO;o>=1;o--){\n                bool ok=true;\n                for(int x=0;x<o;x++){\n                    if(tail[tail.size()-o+x]!=t[pick][x]){\n                        ok=false;break;\n                    }\n                }\n                if(ok){ ov=o;break;}\n            }\n            int rem=5-ov, manh=costMinSuffix[pick][ov][curId];\n            totalCost += manh + rem;\n            curId = bestEndId[pick][ov][curId];\n            for(int i=ov;i<5;i++){\n                if(tail.size()==4) tail.erase(tail.begin());\n                tail.push_back(t[pick][i]);\n            }\n        }\n        if(totalCost < bestTotalCost){\n            bestTotalCost = totalCost;\n            bestSeq = seq;\n        }\n    }\n\n    // 4) Build the full letter string S of length L \u2264 1000\n    vector<char> S;\n    S.reserve(1000);\n    {\n        int curId = si*N + sj;\n        string tail; tail.reserve(4);\n        for(int pick: bestSeq){\n            int ov=0, mxO=min((int)tail.size(),4);\n            for(int o=mxO;o>=1;o--){\n                bool ok=true;\n                for(int x=0;x<o;x++){\n                    if(tail[tail.size()-o+x]!=t[pick][x]){\n                        ok=false;break;\n                    }\n                }\n                if(ok){ ov=o;break;}\n            }\n            for(int i=ov;i<5;i++){\n                S.push_back(t[pick][i]);\n            }\n            // update tail\n            for(int i=ov;i<5;i++){\n                if(tail.size()==4) tail.erase(tail.begin());\n                tail.push_back(t[pick][i]);\n            }\n        }\n    }\n\n    int L = S.size();\n    // occLists and sizes\n    static vector<int> occList[1005];\n    for(int i=0;i<L;i++){\n        occList[i].clear();\n        occList[i] = posList[S[i]-'A'];\n    }\n\n    // 5) Global DP over S\n    // i=0\n    for(int j=0;j<(int)occList[0].size();j++){\n        int pid = occList[0][j];\n        auto [pi,pj]=gridPos[pid];\n        dpPrev[j] = abs(si - pi) + abs(sj - pj) + 1;\n        parentPtr[0][j] = -1;\n    }\n    // i=1..L-1\n    for(int i=1;i<L;i++){\n        for(int v=0;v<(int)occList[i].size();v++){\n            dpCur[v] = INF;\n            parentPtr[i][v] = -1;\n        }\n        for(int u=0;u<(int)occList[i-1].size();u++){\n            int p0 = occList[i-1][u];\n            auto [x0,y0]=gridPos[p0];\n            int base = dpPrev[u];\n            for(int v=0;v<(int)occList[i].size();v++){\n                int p1 = occList[i][v];\n                auto [x1,y1]=gridPos[p1];\n                int cand = base + abs(x0-x1) + abs(y0-y1) + 1;\n                if(cand < dpCur[v]){\n                    dpCur[v] = cand;\n                    parentPtr[i][v] = u;\n                }\n            }\n        }\n        // swap\n        for(int v=0;v<(int)occList[i].size();v++){\n            dpPrev[v] = dpCur[v];\n        }\n    }\n\n    // 6) Backtrack to get the cell\u2010index sequence\n    vector<int> idx(L);\n    // find best end\n    int bestEnd = 0;\n    for(int j=1;j<(int)occList[L-1].size();j++){\n        if(dpPrev[j] < dpPrev[bestEnd]) bestEnd = j;\n    }\n    idx[L-1] = bestEnd;\n    for(int i=L-1;i>0;i--){\n        idx[i-1] = parentPtr[i][ idx[i] ];\n    }\n\n    // 7) Output the coordinates\n    for(int i=0;i<L;i++){\n        int pid = occList[i][ idx[i] ];\n        auto [r,c]=gridPos[pid];\n        cout << r << \" \" << c << \"\\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    cin >> N >> M >> eps;\n    int NN = N * N;\n\n    // 1) Read shapes\n    vector<vector<pair<int,int>>> shape(M);\n    vector<int> shape_mx_i(M), shape_mx_j(M);\n    for(int k = 0; k < M; k++){\n        int d; cin >> d;\n        int mi = 0, mj = 0;\n        shape[k].resize(d);\n        for(int i = 0; i < d; i++){\n            int ii, jj;\n            cin >> ii >> jj;\n            shape[k][i] = {ii, jj};\n            mi = max(mi, ii);\n            mj = max(mj, jj);\n        }\n        shape_mx_i[k] = mi;\n        shape_mx_j[k] = mj;\n    }\n\n    // 2) Enumerate placements and reverse\u2010map\n    vector<vector<pair<int,int>>> coverList(NN);\n    vector<vector<vector<int>>>    placement_cells(M);\n    vector<vector<char>>           alive(M);\n    vector<int>                    aliveCnt(M, 0);\n    for(int k = 0; k < M; k++){\n        for(int di = 0; di + shape_mx_i[k] < N; di++){\n            for(int dj = 0; dj + shape_mx_j[k] < N; dj++){\n                int pid = (int)placement_cells[k].size();\n                placement_cells[k].emplace_back();\n                alive[k].push_back(1);\n                aliveCnt[k]++;\n                auto &cells = placement_cells[k].back();\n                for(auto &p : shape[k]){\n                    int id = (di + p.first)*N + (dj + p.second);\n                    cells.push_back(id);\n                    coverList[id].emplace_back(k, pid);\n                }\n            }\n        }\n    }\n\n    // 3) coverCount[id] + per\u2010shape count_k[k][id]\n    vector<int> coverCount(NN, 0);\n    vector<vector<int>> count_k(M, vector<int>(NN,0));\n    for(int id = 0; id < NN; id++){\n        coverCount[id] = (int)coverList[id].size();\n        for(auto &kp : coverList[id]){\n            count_k[kp.first][id]++;\n        }\n    }\n\n    // 4) Cell state\n    //    vgrid[id] = -1 unknown, 0 zero, >0 oil\n    //    drilled[id] = whether we have drilled/logically fixed\n    vector<int>  vgrid(NN, -1);\n    vector<char> drilled(NN, 0);\n\n    // 5) Track locked\u2010in shapes\n    vector<char> shapeFixed(M, 0);\n\n    // 6) Precompute neighbors\n    static int di[4] = {1,-1,0,0}, dj[4] = {0,0,1,-1};\n    auto hasOilNeighbor = [&](int id){\n        int i = id / N, j = id % N;\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            int nid = ni*N+nj;\n            if(vgrid[nid]>0) return true;\n        }\n        return false;\n    };\n\n    // 7) PQs for even / odd\n    priority_queue<pair<int,int>> pqE, pqO;\n    vector<char> inE(NN,0), inO(NN,0);\n\n    // 8) Helpers to re\u2010enqueue after coverCount changes or new seeds\n    auto tryEnqueueEven = [&](int id){\n        if(vgrid[id]==-1 && !drilled[id] && ((id/N + id%N)&1)==0 && coverCount[id]>0 && !inE[id]){\n            inE[id]=1;\n            pqE.emplace(coverCount[id], id);\n        }\n    };\n    auto tryEnqueueOdd = [&](int id){\n        if(vgrid[id]==-1 && !drilled[id] && ((id/N + id%N)&1)==1 \n           && coverCount[id]>0 && hasOilNeighbor(id) && !inO[id]){\n            inO[id]=1;\n            pqO.emplace(coverCount[id], id);\n        }\n    };\n\n    // 9) kill one placement of shape k,pid\n    auto kill_one = [&](int k,int pid, queue<int> &q0){\n        alive[k][pid]=0;\n        aliveCnt[k]--;\n        for(int cid: placement_cells[k][pid]){\n            coverCount[cid]--;\n            count_k[k][cid]--;\n            if(vgrid[cid]==-1 && coverCount[cid]==0){\n                vgrid[cid]=0;\n                drilled[cid]=1;\n                q0.push(cid);\n            }\n        }\n    };\n\n    // 10) eliminate all placements covering a known\u2010zero cell id\n    function<void(int)> eliminate_at_zero = [&](int id){\n        queue<int> q;\n        // kill direct\n        for(auto &kp: coverList[id]){\n            int k=kp.first, pid=kp.second;\n            if(alive[k][pid]) kill_one(k,pid,q);\n        }\n        // cascade\n        while(!q.empty()){\n            int z=q.front(); q.pop();\n            for(auto &kp: coverList[z]){\n                int k=kp.first, pid=kp.second;\n                if(alive[k][pid]) kill_one(k,pid,q);\n            }\n        }\n        // inference loop\n        bool changed=true;\n        while(changed){\n            changed=false;\n            for(int k=0;k<M;k++){\n                // single\u2010placement\n                if(!shapeFixed[k] && aliveCnt[k]==1){\n                    shapeFixed[k]=1;\n                    int the_pid=-1;\n                    for(int pid=0;pid<(int)alive[k].size();pid++){\n                        if(alive[k][pid]){ the_pid=pid; break; }\n                    }\n                    if(the_pid>=0)\n                    for(int cid: placement_cells[k][the_pid]){\n                        if(vgrid[cid]==-1){\n                            vgrid[cid]=1;\n                            drilled[cid]=1;\n                            changed=true;\n                        }\n                    }\n                }\n                // intersection\n                if(aliveCnt[k]>0){\n                    for(int cid=0;cid<NN;cid++){\n                        if(vgrid[cid]==-1 && count_k[k][cid]==aliveCnt[k]){\n                            vgrid[cid]=1;\n                            drilled[cid]=1;\n                            changed=true;\n                        }\n                    }\n                }\n            }\n        }\n        // re\u2010enqueue around all changed cells\n        for(int cid=0; cid<NN; cid++){\n            if(vgrid[cid]==-1){\n                tryEnqueueEven(cid);\n                tryEnqueueOdd(cid);\n            } else if(vgrid[cid]>0){\n                // newly known oil at even\u2010cid seeds odd neighbors\n                if(((cid/N + cid%N)&1)==0){\n                    for(int d=0;d<4;d++){\n                        int ni=cid/N+di[d], nj=cid%N+dj[d];\n                        if(ni<0||ni>=N||nj<0||nj>=N) continue;\n                        tryEnqueueOdd(ni*N+nj);\n                    }\n                }\n            }\n        }\n    };\n\n    // 11) initial shape\u2010inference prior to any drilling\n    {\n        bool changed=true;\n        while(changed){\n            changed=false;\n            for(int k=0;k<M;k++){\n                if(!shapeFixed[k] && aliveCnt[k]==1){\n                    shapeFixed[k]=1;\n                    int the_pid=-1;\n                    for(int pid=0;pid<(int)alive[k].size();pid++){\n                        if(alive[k][pid]){ the_pid=pid; break; }\n                    }\n                    if(the_pid>=0){\n                        for(int cid: placement_cells[k][the_pid]){\n                            if(vgrid[cid]==-1){\n                                vgrid[cid]=1;\n                                drilled[cid]=1;\n                                changed=true;\n                            }\n                        }\n                    }\n                }\n                if(aliveCnt[k]>0){\n                    for(int cid=0;cid<NN;cid++){\n                        if(vgrid[cid]==-1 && count_k[k][cid]==aliveCnt[k]){\n                            vgrid[cid]=1;\n                            drilled[cid]=1;\n                            changed=true;\n                        }\n                    }\n                }\n            }\n        }\n        // seed odd neighbors of any even\u2010parity positives\n        for(int cid=0; cid<NN; cid++){\n            if(vgrid[cid]>0 && ((cid/N + cid%N)&1)==0){\n                for(int d=0;d<4;d++){\n                    int ni=cid/N+di[d], nj=cid%N+dj[d];\n                    if(ni<0||ni>=N||nj<0||nj>=N) continue;\n                    tryEnqueueOdd(ni*N+nj);\n                }\n            }\n        }\n    }\n\n    // 12) drill helper\n    auto drillOne = [&](int id){\n        int i=id/N, j=id%N;\n        cout << \"q 1 \" << i << \" \" << j << \"\\n\" << flush;\n        int v; if(!(cin>>v)) exit(0);\n        vgrid[id]=v;\n        drilled[id]=1;\n        if(v==0){\n            eliminate_at_zero(id);\n        } else {\n            // positive at even \u2192 seed odd neighbors\n            if(((i+j)&1)==0){\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                    tryEnqueueOdd(ni*N+nj);\n                }\n            }\n        }\n    };\n\n    // 13) initialize even\u2010parity PQ\n    for(int id=0; id<NN; id++){\n        if(((id/N + id%N)&1)==0){\n            tryEnqueueEven(id);\n        }\n    }\n\n    // 14) Phase 1: dynamic PQ on evens\n    while(!pqE.empty()){\n        auto [c,id] = pqE.top(); pqE.pop();\n        inE[id]=0;\n        if(drilled[id]) continue;\n        if(coverCount[id]!=c){\n            tryEnqueueEven(id);\n            continue;\n        }\n        if(coverCount[id]==0){\n            vgrid[id]=0;\n            drilled[id]=1;\n            eliminate_at_zero(id);\n        } else {\n            drillOne(id);\n        }\n    }\n\n    // 15) Phase 2: dynamic PQ on odds\n    while(!pqO.empty()){\n        auto [c,id] = pqO.top(); pqO.pop();\n        inO[id]=0;\n        if(drilled[id]) continue;\n        if(coverCount[id]!=c){\n            tryEnqueueOdd(id);\n            continue;\n        }\n        if(!hasOilNeighbor(id) || coverCount[id]==0){\n            vgrid[id]=0; drilled[id]=1;\n            eliminate_at_zero(id);\n        } else {\n            drillOne(id);\n        }\n    }\n\n    // 16) any unknown \u21d2 zero\n    for(int id=0; id<NN; id++){\n        if(vgrid[id]==-1) vgrid[id]=0;\n    }\n\n    // 17) output\n    vector<pair<int,int>> ans;\n    for(int id=0; id<NN; id++){\n        if(vgrid[id]>0) ans.emplace_back(id/N,id%N);\n    }\n    cout<<\"a \"<<ans.size();\n    for(auto &p: ans){\n        cout<<\" \"<<p.first<<\" \"<<p.second;\n    }\n    cout<<\"\\n\"<<flush;\n\n    int verdict; cin>>verdict;\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int W = 1000;\n    int D, N;\n    cin >> ws >> ws; // skip potential leading whitespace (safe no\u2010op)\n    // Actually the problem gives W=1000 first:\n    cin.clear();\n    cin.seekg(0);\n    int tmpW;\n    cin >> tmpW >> D >> N;\n    // tmpW should be 1000\n    vector<vector<int>> a(D, vector<int>(N));\n    for(int d = 0; d < D; d++)\n        for(int k = 0; k < N; k++)\n            cin >> a[d][k];\n\n    // For each day independently, we build w[k] \u2265 1 so as to minimize:\n    //   100*max(0, a[d][k] - 1000*w[k])  subject to sum w[k] \u2264 1000\n    // By classic \u201cmarginal\u2010benefit\u201d greedy: start w[k]=1 (used=N), then\n    // collect all positive marginals m[k][t]=min(1000, a-1000*t) for t=1..ceil(a/1000)-1,\n    // sort them descending, and take the top (W-N).\n    vector<pair<int,int>> M; \n    M.reserve(2000);\n\n    vector<int> w(N), X(N+1);\n    for(int d = 0; d < D; d++){\n        // 1) init\n        for(int k = 0; k < N; k++) w[k] = 1;\n        int used = N;\n        int rem = W - used;\n\n        // 2) build all positive marginals\n        M.clear();\n        for(int k = 0; k < N; k++){\n            int ad = a[d][k];\n            // for t=1.. until ad - 1000*t <= 0\n            // marginal of the t-th extra column (beyond the first)\n            // is min(1000, ad - 1000*t).\n            for(int t = 1; ; t++){\n                int leftover = ad - 1000 * t;\n                if(leftover <= 0) break;\n                M.emplace_back(min(1000, leftover), k);\n            }\n        }\n\n        // 3) pick the top rem marginals\n        if(!M.empty()){\n            nth_element(M.begin(), M.begin() + min(rem, (int)M.size()), M.end(),\n                        [](auto &A, auto &B){ return A.first > B.first; });\n            int take = min(rem, (int)M.size());\n            // count how many times each k appears in the top\u2010take\n            static vector<int> cnt;\n            cnt.assign(N, 0);\n            for(int i = 0; i < take; i++){\n                if(M[i].first <= 0) break;\n                cnt[M[i].second]++;\n            }\n            for(int k = 0; k < N; k++){\n                w[k] += cnt[k];\n            }\n        }\n\n        // 4) compute X\u2010coordinates\n        X[0] = 0;\n        for(int k = 0; k < N; k++){\n            X[k+1] = X[k] + w[k];\n        }\n        // 5) output this day's rectangles\n        //    rectangle k:  i0=0, j0=X[k], i1=1000, j1=X[k+1]\n        for(int k = 0; k < N; k++){\n            cout << 0 << ' ' << X[k] << ' ' << W << ' ' << X[k+1] << \"\\n\";\n        }\n    }\n\n    return 0;\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nstatic const int MOD = 998244353;\n\n// xorshift RNG\nstatic uint64_t _rnd = chrono::steady_clock::now().time_since_epoch().count();\ninline uint32_t rnd(){\n    _rnd ^= _rnd << 13;\n    _rnd ^= _rnd >> 7;\n    _rnd ^= _rnd << 17;\n    return uint32_t(_rnd);\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N,M,K;\n    cin>>N>>M>>K;\n    assert(N==9 && M==20 && K==81);\n\n    // 1) read board flattened 9\u00d79\u219281\n    static int B0[81];\n    for(int i=0;i<9;i++){\n        for(int j=0;j<9;j++){\n            ll x; cin>>x;\n            B0[i*9+j] = int(x % MOD);\n        }\n    }\n    // 2) read stamps 20\u00d7(3\u00d73\u21929)\n    static int stamps[20][9];\n    for(int m=0;m<20;m++){\n        for(int i=0;i<3;i++){\n            for(int j=0;j<3;j++){\n                ll x; cin>>x;\n                stamps[m][i*3+j] = int(x % MOD);\n            }\n        }\n    }\n\n    // 3) enumerate all 20\u00d77\u00d77=980 placements\n    static int candM[980], candP[980], candQ[980], off[980][9];\n    static int mapCI[20][9][9];\n    memset(mapCI,-1,sizeof mapCI);\n    int C=0;\n    for(int m=0;m<20;m++){\n        for(int p=0;p+2<9;p++){\n            for(int q=0;q+2<9;q++){\n                candM[C]=m; candP[C]=p; candQ[C]=q;\n                int idx=0;\n                for(int di=0;di<3;di++){\n                    for(int dj=0;dj<3;dj++){\n                        off[C][idx++] = (p+di)*9 + (q+dj);\n                    }\n                }\n                mapCI[m][p][q] = C;\n                C++;\n            }\n        }\n    }\n    const int CAND = C; // =980\n\n    // 4) build covers for hill\u2010climb\n    static vector<int> covers[81];\n    for(int i=0;i<81;i++) covers[i].clear();\n    for(int ci=0;ci<CAND;ci++){\n        for(int k=0;k<9;k++){\n            covers[ off[ci][k] ].push_back(ci);\n        }\n    }\n\n    // 5) delta\u2010only and apply helpers\n    auto delta_add = [&](const int A[81], int ci)->ll{\n        int m = candM[ci];\n        ll d=0;\n        for(int k=0;k<9;k++){\n            int v = A[ off[ci][k] ] + stamps[m][k];\n            if(v < MOD) d += stamps[m][k];\n            else        d += (ll)stamps[m][k] - MOD;\n        }\n        return d;\n    };\n    auto apply_add = [&](int A[81], int ci){\n        int m = candM[ci];\n        for(int k=0;k<9;k++){\n            int &c = A[ off[ci][k] ];\n            c += stamps[m][k];\n            if(c >= MOD) c -= MOD;\n        }\n    };\n    auto delta_rem = [&](const int A[81], int ci)->ll{\n        int m = candM[ci];\n        ll d=0;\n        for(int k=0;k<9;k++){\n            int pos = off[ci][k];\n            int ov = A[pos];\n            int nv = ov - stamps[m][k];\n            if(nv<0) nv+=MOD;\n            d += (ll)nv - ov;\n        }\n        return d;\n    };\n    auto apply_rem = [&](int A[81], int ci){\n        int m = candM[ci];\n        for(int k=0;k<9;k++){\n            int &c = A[ off[ci][k] ];\n            c -= stamps[m][k];\n            if(c<0) c += MOD;\n        }\n    };\n\n    // timer\n    auto T0 = chrono::steady_clock::now();\n\n    // ---------------------------------------------------\n    // A) HEAVY 3-step/2-step lookahead seed (\u223c5\u2009ms)\n    // ---------------------------------------------------\n    static int Bheavy[81], T1[81], T2[81], T3[81];\n    memcpy(Bheavy,B0,sizeof B0);\n    vector<array<int,3>> heavyOps;\n    heavyOps.reserve(K);\n    while((int)heavyOps.size()<K){\n        int used = heavyOps.size(), rem = K-used;\n        struct Cand2{ ll d; int ci; };\n        Cand2 b1{LLONG_MIN,-1}, b2{LLONG_MIN,-1};\n        // top\u20102 immediate\n        for(int ci=0;ci<CAND;ci++){\n            ll d = delta_add(Bheavy,ci);\n            if(d>b1.d){ b2=b1; b1={d,ci}; }\n            else if(d>b2.d){ b2={d,ci}; }\n        }\n        if(b1.d<=0) break;\n        if(rem==1){\n            apply_add(Bheavy,b1.ci);\n            heavyOps.push_back({candM[b1.ci],candP[b1.ci],candQ[b1.ci]});\n            break;\n        }\n        // branch0: b1\u2192b2_0\u2192b3_0\n        memcpy(T1,Bheavy,sizeof Bheavy);\n        apply_add(T1,b1.ci);\n        Cand2 b2_0{LLONG_MIN,-1};\n        for(int ci=0;ci<CAND;ci++){\n            ll d=delta_add(T1,ci);\n            if(d>b2_0.d) b2_0={d,ci};\n        }\n        memcpy(T2,T1,sizeof T1);\n        apply_add(T2,b2_0.ci);\n        Cand2 b3_0{LLONG_MIN,-1};\n        for(int ci=0;ci<CAND;ci++){\n            ll d=delta_add(T2,ci);\n            if(d>b3_0.d) b3_0={d,ci};\n        }\n        // branch1: b2\u2192b2_1\n        memcpy(T3,Bheavy,sizeof Bheavy);\n        apply_add(T3,b2.ci);\n        Cand2 b2_1{LLONG_MIN,-1};\n        for(int ci=0;ci<CAND;ci++){\n            ll d=delta_add(T3,ci);\n            if(d>b2_1.d) b2_1={d,ci};\n        }\n        // combine\n        ll s1   = b1.d;\n        ll s2_0 = b1.d + b2_0.d;\n        ll s2_1 = b2.d + b2_1.d;\n        ll s3_0 = b1.d + b2_0.d + b3_0.d;\n        ll bestS = s1;\n        int bestR=1, bestBr=0;\n        if(rem>=2){\n            if(s2_0>bestS){ bestS=s2_0; bestR=2; bestBr=0; }\n            if(s2_1>bestS){ bestS=s2_1; bestR=2; bestBr=1; }\n        }\n        if(rem>=3 && s3_0>bestS){\n            bestS=s3_0; bestR=3; bestBr=0;\n        }\n        if(bestS<=0) break;\n\n        // commit\n        if(bestR==1){\n            apply_add(Bheavy,b1.ci);\n            heavyOps.push_back({candM[b1.ci],candP[b1.ci],candQ[b1.ci]});\n        } else if(bestR==2){\n            if(bestBr==0){\n                apply_add(Bheavy,b1.ci);\n                apply_add(Bheavy,b2_0.ci);\n                heavyOps.push_back({candM[b1.ci],candP[b1.ci],candQ[b1.ci]});\n                heavyOps.push_back({candM[b2_0.ci],candP[b2_0.ci],candQ[b2_0.ci]});\n            } else {\n                apply_add(Bheavy,b2.ci);\n                apply_add(Bheavy,b2_1.ci);\n                heavyOps.push_back({candM[b2.ci],candP[b2.ci],candQ[b2.ci]});\n                heavyOps.push_back({candM[b2_1.ci],candP[b2_1.ci],candQ[b2_1.ci]});\n            }\n        } else { // bestR==3\n            apply_add(Bheavy,b1.ci);\n            apply_add(Bheavy,b2_0.ci);\n            apply_add(Bheavy,b3_0.ci);\n            heavyOps.push_back({candM[b1.ci],candP[b1.ci],candQ[b1.ci]});\n            heavyOps.push_back({candM[b2_0.ci],candP[b2_0.ci],candQ[b2_0.ci]});\n            heavyOps.push_back({candM[b3_0.ci],candP[b3_0.ci],candQ[b3_0.ci]});\n        }\n    }\n\n    // seed bestSolution\n    ll bestScore = 0;\n    for(int i=0;i<81;i++) bestScore += Bheavy[i];\n    vector<array<int,3>> bestOps = heavyOps;\n\n    // ---------------------------------------------------\n    // B) MULTI-START GREEDY (top-3 uniform) until \u22481.60 s\n    // ---------------------------------------------------\n    static int Br[81];\n    int trials=0;\n    while(true){\n        if((trials&1)==0){\n            auto now = chrono::steady_clock::now();\n            if(chrono::duration_cast<chrono::milliseconds>(now - T0).count() > 1600)\n                break;\n        }\n        trials++;\n        memcpy(Br,B0,sizeof B0);\n        vector<array<int,3>> ops;\n        ops.reserve(K);\n\n        for(int step=0; step<K; step++){\n            // brute\u2010force top\u20103\n            ll bd[3] = {LLONG_MIN,LLONG_MIN,LLONG_MIN};\n            int bi[3] = {-1,-1,-1};\n            for(int ci=0; ci<CAND; ci++){\n                ll d = delta_add(Br,ci);\n                if(d > bd[0]){\n                    bd[2]=bd[1]; bi[2]=bi[1];\n                    bd[1]=bd[0]; bi[1]=bi[0];\n                    bd[0]=d;    bi[0]=ci;\n                } else if(d > bd[1]){\n                    bd[2]=bd[1]; bi[2]=bi[1];\n                    bd[1]=d;    bi[1]=ci;\n                } else if(d > bd[2]){\n                    bd[2]=d;    bi[2]=ci;\n                }\n            }\n            if(bd[0] <= 0) break;\n            int pick = rnd() % min(3, K-step);\n            int ci = bi[pick];\n            apply_add(Br,ci);\n            ops.push_back({candM[ci],candP[ci],candQ[ci]});\n        }\n\n        ll sc=0;\n        for(int i=0;i<81;i++) sc += Br[i];\n        if(sc > bestScore){\n            bestScore = sc;\n            bestOps   = ops;\n        }\n    }\n\n    // ---------------------------------------------------\n    // C) FAST RANDOM-SWAP/ADD hill-climb until \u22481.90 s\n    // ---------------------------------------------------\n    static int Bc[81], Btmp[81];\n    memcpy(Bc,B0,sizeof B0);\n    for(auto &o:bestOps){\n        int ci = mapCI[o[0]][o[1]][o[2]];\n        apply_add(Bc,ci);\n    }\n    ll currScore = bestScore;\n    auto localOps = bestOps;\n    int li=0;\n    while(true){\n        if((li++ & 3)==0){\n            auto now = chrono::steady_clock::now();\n            if(chrono::duration_cast<chrono::milliseconds>(now - T0).count() > 1900)\n                break;\n        }\n        // 5% chance to random add\n        if((int)localOps.size()<K && (rnd() & 31)==0){\n            int ci = rnd() % CAND;\n            ll d = delta_add(Bc,ci);\n            if(d>0){\n                apply_add(Bc,ci);\n                currScore += d;\n                localOps.push_back({candM[ci],candP[ci],candQ[ci]});\n            }\n        } else {\n            if(localOps.empty()) continue;\n            int idx = rnd()%localOps.size();\n            auto [mo,po,qo] = localOps[idx];\n            int oldCi = mapCI[mo][po][qo];\n            int newCi = rnd()%CAND;\n            if(newCi==oldCi) continue;\n            memcpy(Btmp,Bc,sizeof Bc);\n            ll dr = delta_rem(Btmp,oldCi);\n            apply_rem(Btmp,oldCi);\n            ll da = delta_add(Btmp,newCi);\n            if(dr+da > 0){\n                apply_rem(Bc,oldCi);\n                apply_add(Bc,newCi);\n                currScore += dr+da;\n                localOps[idx] = {candM[newCi],candP[newCi],candQ[newCi]};\n            }\n        }\n    }\n\n    // ---------------------------------------------------\n    // D) QUICK PRUNE & GREEDY-FILL (last \u226a100 ms)\n    // ---------------------------------------------------\n    bool again=true;\n    while(again){\n        again=false;\n        for(int i=0;i<(int)localOps.size();i++){\n            auto &o = localOps[i];\n            int ci = mapCI[o[0]][o[1]][o[2]];\n            ll dr = delta_rem(Bc,ci);\n            if(dr>0){\n                apply_rem(Bc,ci);\n                currScore += dr;\n                localOps.erase(localOps.begin()+i);\n                again=true;\n                break;\n            }\n        }\n    }\n    while((int)localOps.size()<K){\n        ll bd=0; int bi=-1;\n        for(int ci=0;ci<CAND;ci++){\n            ll d = delta_add(Bc,ci);\n            if(d>bd){\n                bd=d; bi=ci;\n            }\n        }\n        if(bi<0 || bd<=0) break;\n        apply_add(Bc,bi);\n        currScore += bd;\n        localOps.push_back({candM[bi],candP[bi],candQ[bi]});\n    }\n\n    // OUTPUT\n    cout<<localOps.size()<<\"\\n\";\n    for(auto &o: localOps){\n        cout<<o[0]<<\" \"<<o[1]<<\" \"<<o[2]<<\"\\n\";\n    }\n    return 0;\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Cand { int r, id, dest, pd, cd; };\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    // A small sweep of fallback\u2010weights W:\n    static const vector<int> WEIGHTS = {0, 1, 2, 4, 8, 16, 32};\n\n    int N;\n    cin >> N;\n    vector<vector<int>> A(N, vector<int>(N));\n    for(int i = 0; i < N; i++)\n      for(int j = 0; j < N; j++)\n        cin >> A[i][j];\n\n    int bestScore = INT_MAX;\n    vector<char> bestOps;\n    int bestM = 0;\n\n    // Try each weight W\n    for(int W : WEIGHTS){\n        int curR = 0, curC = 0;\n        vector<int> picked(N,0), delivered(N,0);\n        vector<vector<int>> deliveredList(N);\n        vector<char> ops;\n        ops.reserve(2000);\n        int M1 = 0;\n\n        // Simulate all 25 picks\n        for(int done = 0; done < N*N; done++){\n            vector<Cand> safe, other;\n            // collect candidates\n            for(int r = 0; r < N; r++){\n                if(picked[r] < N){\n                    int id   = A[r][ picked[r] ];\n                    int dest = id / N;\n                    int pd   = abs(curR - r) + abs(curC - 0);\n                    int cd   = (N - 1) + abs(dest - r);\n                    if(id == dest * N + delivered[dest]){\n                        safe.push_back({r,id,dest,pd,cd});\n                    } else {\n                        other.push_back({r,id,dest,pd,cd});\n                    }\n                }\n            }\n\n            Cand best;\n            // 1) safe\u2010pick if possible\n            if(!safe.empty()){\n                int bestCost = INT_MAX, bestID = INT_MAX;\n                for(auto &c : safe){\n                    int cost = c.pd + c.cd;\n                    if(cost < bestCost || (cost == bestCost && c.id < bestID)){\n                        bestCost = cost;\n                        bestID   = c.id;\n                        best     = c;\n                    }\n                }\n            }\n            else {\n                // 2) fallback by score = id*W + (pd+cd)\n                int bestScoreW = INT_MAX, bestSum = INT_MAX, bestID = INT_MAX;\n                for(auto &c : other){\n                    int sum   = c.pd + c.cd;\n                    int score = c.id * W + sum;\n                    if(score < bestScoreW\n                     || (score == bestScoreW && (sum < bestSum\n                         || (sum == bestSum && c.id < bestID)))){\n                        bestScoreW = score;\n                        bestSum    = sum;\n                        bestID     = c.id;\n                        best       = c;\n                    }\n                }\n            }\n\n            // 3) move to (best.r,0)\n            int dr = best.r - curR;\n            if(dr > 0) for(int i=0;i<dr;i++) ops.push_back('D');\n            else       for(int i=0;i<-dr;i++) ops.push_back('U');\n            int dc = 0 - curC;\n            if(dc > 0) for(int i=0;i<dc;i++) ops.push_back('R');\n            else       for(int i=0;i<-dc;i++) ops.push_back('L');\n\n            // 4) pick\n            ops.push_back('P');\n            picked[best.r]++;\n\n            // 5) carry to (best.dest, N-1)\n            for(int i=0;i<N-1;i++) ops.push_back('R');\n            dr = best.dest - best.r;\n            if(dr > 0) for(int i=0;i<dr;i++) ops.push_back('D');\n            else       for(int i=0;i<-dr;i++) ops.push_back('U');\n\n            // 6) drop\n            ops.push_back('Q');\n            // count inversions in deliveredList[best.dest]\n            for(int x : deliveredList[best.dest])\n                if(x > best.id) M1++;\n            deliveredList[best.dest].push_back(best.id);\n            delivered[best.dest]++;\n\n            // 7) update crane position\n            curR = best.dest;\n            curC = N - 1;\n        }\n\n        int M0 = (int)ops.size();\n        int absScore = M0 + 100 * M1;\n        if(absScore < bestScore){\n            bestScore = absScore;\n            bestOps   = ops;\n            bestM     = M0;\n        }\n    }\n\n    // Build final output, bombing cranes 1..N-1 on turn 0\n    vector<string> S(N);\n    S[0].clear();\n    for(char c : bestOps) S[0].push_back(c);\n    for(int i = 1; i < N; i++){\n        S[i] = \"B\";\n        S[i].append(bestM - 1, '.');\n    }\n\n    // Emit\n    for(int i = 0; i < N; i++){\n        cout << S[i] << \"\\n\";\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\n// fast abs + Manhattan\nstatic inline int ABS(int x){ return x<0 ? -x : x; }\nstatic inline int MANH(int x1,int y1,int x2,int y2){\n    return ABS(x1-x2) + ABS(y1-y2);\n}\n// 5-bit Hilbert curve for 0..31\nstatic uint32_t hilbert5(int x, int y){\n    uint32_t rx, ry, s, d=0;\n    for(s = 1u<<4; s > 0; s >>= 1){\n        rx = (x & s)?1u:0u;\n        ry = (y & s)?1u:0u;\n        d = (d<<2) | ((rx*3u)^ry);\n        if(ry==0){\n            if(rx==1){\n                x = ((1<<5)-1)-x;\n                y = ((1<<5)-1)-y;\n            }\n            swap(x,y);\n        }\n    }\n    return d;\n}\n\nstruct Edge { int d,i,j; };\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;              // always 20\n    cin >> N;\n    static int h[20][20];\n    for(int i=0;i<N;i++) for(int j=0;j<N;j++) cin >> h[i][j];\n\n    // 1) collect source (h>0) and sink (h<0) cells\n    vector<pair<int,int>> src, dst;\n    vector<int> supply, demand;\n    src.reserve(N*N);\n    dst.reserve(N*N);\n    supply.reserve(N*N);\n    demand.reserve(N*N);\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            if(h[i][j]>0){\n                src.emplace_back(i,j);\n                supply.push_back(h[i][j]);\n            } else if(h[i][j]<0){\n                dst.emplace_back(i,j);\n                demand.push_back(-h[i][j]);\n            }\n        }\n    }\n    int S = src.size(), T = dst.size();\n    if(S==0){\n        // already flat\n        return 0;\n    }\n\n    // 2) greedy bipartite match by Manhattan distance\n    vector<Edge> E;\n    E.reserve((long long)S * T);\n    for(int i=0;i<S;i++){\n        for(int j=0;j<T;j++){\n            int d = MANH(src[i].first, src[i].second,\n                         dst[j].first, dst[j].second);\n            E.push_back({d,i,j});\n        }\n    }\n    sort(E.begin(), E.end(),\n         [](auto &a, auto &b){ return a.d < b.d; });\n\n    vector<int> remS = supply, remT = demand;\n    // flow[i][j] = how much to move from src[i] \u2192 dst[j]\n    vector<vector<int>> flow(S, vector<int>(T,0));\n    for(auto &e : E){\n        int i=e.i, j=e.j;\n        if(remS[i]>0 && remT[j]>0){\n            int f = min(remS[i], remT[j]);\n            flow[i][j] = f;\n            remS[i] -= f;\n            remT[j] -= f;\n        }\n    }\n\n    // 3) group sinks by each source i\n    //    and build a small NN\u2010TSP micro\u2010route\n    //    record for each i:\n    //      sumFlow[i], microOrder[i], exitPos[i]\n    vector<int> sumFlow(S,0);\n    vector<vector<int>> microOrder(S);\n    vector<pair<int,int>> exitPos(S);\n    for(int i=0;i<S;i++){\n        // collect all sink\u2010indices j with flow>0\n        vector<int> sinks;\n        sinks.reserve(T);\n        for(int j=0;j<T;j++){\n            if(flow[i][j]>0) sinks.push_back(j), sumFlow[i]+=flow[i][j];\n        }\n        int K = sinks.size();\n        microOrder[i].reserve(K);\n        // nearest\u2010neighbor on these K sinks:\n        int cx = src[i].first, cy = src[i].second;\n        vector<char> used(K,0);\n        for(int k=0;k<K;k++){\n            int best=-1, bd=INT_MAX;\n            for(int t=0;t<K;t++){\n                if(!used[t]){\n                    auto &p = dst[sinks[t]];\n                    int d = MANH(cx,cy,p.first,p.second);\n                    if(d<bd){\n                        bd=d; best=t;\n                    }\n                }\n            }\n            used[best]=1;\n            microOrder[i].push_back(sinks[best]);\n            cx = dst[sinks[best]].first;\n            cy = dst[sinks[best]].second;\n        }\n        exitPos[i] = {cx, cy};\n    }\n\n    // 4) build macro\u2010distance tables for S groups\n    //    distOri[i]   = cost empty from (0,0)\u2192src[i]\n    //    distG[i][j]  = cost empty from exitPos[i]\u2192src[j]\n    vector<long long> distOri(S);\n    vector<vector<long long>> distG(S, vector<long long>(S));\n    for(int i=0;i<S;i++){\n        distOri[i] = 1LL * MANH(0,0, src[i].first, src[i].second) * 100;\n    }\n    for(int i=0;i<S;i++){\n        for(int j=0;j<S;j++){\n            distG[i][j] = 1LL*MANH(\n                exitPos[i].first,  exitPos[i].second,\n                src[j].first,      src[j].second\n            ) * 100;\n        }\n    }\n\n    auto evalEmpty = [&](const vector<int>& ord){\n        long long c = distOri[ ord[0] ];\n        for(int k=0;k+1<S;k++){\n            c += distG[ ord[k] ][ ord[k+1] ];\n        }\n        return c;\n    };\n\n    // 5a) Nearest\u2010Neighbor macro\u2010tour over sources\n    vector<int> ordNN(S);\n    {\n        vector<char> usedG(S,0);\n        int cx=0, cy=0;\n        for(int k=0;k<S;k++){\n            int best=-1; long long bd=LLONG_MAX;\n            for(int i=0;i<S;i++){\n                if(!usedG[i]){\n                    long long d = \n                      (k==0\n                       ? distOri[i]\n                       : 1LL*MANH(cx,cy, src[i].first, src[i].second)*100);\n                    if(d<bd){\n                        bd=d; best=i;\n                    }\n                }\n            }\n            ordNN[k]=best;\n            usedG[best]=1;\n            cx = exitPos[best].first;\n            cy = exitPos[best].second;\n        }\n    }\n\n    // 5b) Hilbert & Reverse\u2010Hilbert on src coords\n    vector<pair<uint32_t,int>> H(S);\n    for(int i=0;i<S;i++){\n        H[i].first  = hilbert5(src[i].first, src[i].second);\n        H[i].second = i;\n    }\n    sort(H.begin(), H.end());\n    vector<int> ordH(S), ordHR(S);\n    for(int i=0;i<S;i++){\n        ordH[i]   = H[i].second;\n        ordHR[S-1-i] = H[i].second;\n    }\n\n    // 5c) Cheapest\u2010Insertion on the S groups\n    vector<int> ordCI;\n    ordCI.reserve(S);\n    {\n        vector<char> inT(S,0);\n        // start with the group whose source is nearest (0,0)\n        int start = 0; long long bd = distOri[0];\n        for(int i=1;i<S;i++){\n            if(distOri[i]<bd){\n                bd=distOri[i];\n                start=i;\n            }\n        }\n        ordCI.push_back(start);\n        inT[start]=1;\n        // insert the remaining S-1 groups\n        while((int)ordCI.size()<S){\n            long long bestDelta=LLONG_MAX;\n            int bi=-1, bp=-1;\n            int sz = ordCI.size();\n            for(int j=0;j<S;j++){\n                if(inT[j]) continue;\n                // try inserting j at every position p=0..sz\n                // p==0: between origin\u2192ordCI[0]\n                long long old0 = distOri[ ordCI[0] ];\n                long long new0 = distOri[j]\n                               +  distG[j][ ordCI[0] ];\n                long long delta0 = new0 - old0;\n                if(delta0 < bestDelta){\n                    bestDelta = delta0;\n                    bi=j; bp=0;\n                }\n                // p in 1..sz-1: between ordCI[p-1]\u2192ordCI[p]\n                for(int p=1;p<sz;p++){\n                    int u = ordCI[p-1], v = ordCI[p];\n                    long long oldE = distG[u][v];\n                    long long newE = distG[u][j] + distG[j][v];\n                    long long dE = newE - oldE;\n                    if(dE < bestDelta){\n                        bestDelta=dE;\n                        bi=j; bp=p;\n                    }\n                }\n                // p==sz: append after last\n                {\n                    int u = ordCI[sz-1];\n                    long long oldE = 0;\n                    long long newE = distG[u][j];\n                    long long dE = newE - oldE;\n                    if(dE < bestDelta){\n                        bestDelta=dE;\n                        bi=j; bp=sz;\n                    }\n                }\n            }\n            ordCI.insert(ordCI.begin()+bp, bi);\n            inT[bi]=1;\n        }\n    }\n\n    // 6) pick the best empty\u2010travel among our four candidates\n    vector<vector<int>> cands = { ordNN, ordH, ordHR, ordCI };\n    long long bestC = LLONG_MAX;\n    vector<int> *pBest = &cands[0];\n    for(auto &o : cands){\n        long long c = evalEmpty(o);\n        if(c < bestC){\n            bestC=c;\n            pBest = &o;\n        }\n    }\n    auto &ordG = *pBest;\n\n    // 7) emit the final operations: group by group\n    vector<string> ops;\n    ops.reserve( (S + dst.size()) * 2 + 20000 );\n    int cx=0, cy=0;\n    auto go = [&](int nx,int ny){\n        while(cx < nx){ ops.emplace_back(\"D\"); cx++; }\n        while(cx > nx){ ops.emplace_back(\"U\"); cx--; }\n        while(cy < ny){ ops.emplace_back(\"R\"); cy++; }\n        while(cy > ny){ ops.emplace_back(\"L\"); cy--; }\n    };\n\n    for(int gi : ordG){\n        // 7a) empty\u2010move to source[gi]\n        go(src[gi].first, src[gi].second);\n        // 7b) load the entire supply once\n        ops.emplace_back(\"+\" + to_string(sumFlow[gi]));\n        // 7c) micro\u2010route: visit all its sinks\n        for(int sj : microOrder[gi]){\n            auto &D = dst[sj];\n            go(D.first, D.second);\n            ops.emplace_back(\"-\" + to_string(flow[gi][sj]));\n        }\n        // now truck is empty at exitPos[gi]\n    }\n\n    // 8) output\n    for(auto &s : ops) \n        cout << s << \"\\n\";\n\n    return 0;\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// fast xorshift64 RNG\nstatic uint64_t _x = 88172645463325252ULL;\ninline uint64_t rnd64(){\n    _x ^= _x << 7;\n    _x ^= _x >> 9;\n    return _x;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, T;\n    cin >> N >> M >> T;\n    const int S = 2 * N * (N - 1); // 60 for N=6\n    const int P = N * N;           // 36\n\n    // read initial seeds\n    vector<vector<int>> X(S, vector<int>(M));\n    for(int i = 0; i < S; i++)\n      for(int j = 0; j < M; j++)\n        cin >> X[i][j];\n\n    // build neighbor\u2010lists on the N\u00d7N grid\n    auto idx = [&](int r,int c){ return r*N + c; };\n    vector<vector<int>> nbr(P);\n    for(int r = 0; r < N; r++){\n      for(int c = 0; c < N; c++){\n        int u = idx(r,c);\n        if(r>0)    nbr[u].push_back(idx(r-1,c));\n        if(r+1<N)  nbr[u].push_back(idx(r+1,c));\n        if(c>0)    nbr[u].push_back(idx(r,c-1));\n        if(c+1<N)  nbr[u].push_back(idx(r,c+1));\n      }\n    }\n\n    // bucket cells by degree\n    vector<int> interior, edges, corners;\n    auto deg = [&](int r,int c){\n      return (r>0)+(r+1<N)+(c>0)+(c+1<N);\n    };\n    for(int r=0;r<N;r++){\n      for(int c=0;c<N;c++){\n        int u = idx(r,c), d = deg(r,c);\n        if(d==4)      interior.push_back(u);\n        else if(d==3) edges.push_back(u);\n        else          corners.push_back(u);\n      }\n    }\n    // sort interior/edges by centrality for initial placement\n    auto dist2 = [&](int r,int c){\n      return abs(2*r - (N-1)) + abs(2*c - (N-1));\n    };\n    sort(interior.begin(), interior.end(),\n         [&](int a,int b){\n           return dist2(a/N,a%N) < dist2(b/N,b%N);\n         });\n    sort(edges.begin(), edges.end(),\n         [&](int a,int b){\n           return dist2(a/N,a%N) < dist2(b/N,b%N);\n         });\n    sort(corners.begin(), corners.end());\n\n    // working arrays\n    vector<int> sumVal(S), pos2seed(P);\n    vector<pair<int,int>> V(S);\n    vector<int> champSeeds, picks;\n    vector<char> isChampion(S), usedPlaced(S);\n\n    // NEW: diff matrix for picks\n    static int diffMat[36][36];\n    vector<int> seed2idx(S, -1);\n\n    // hill\u2010climb budgets (bumped)\n    const int FREE_ITERS    = 400000;\n    const int CLUSTER_ITERS = 200000;\n\n    for(int turn = 0; turn < T; turn++){\n      // 1) compute total\u2010sum and sort seeds by sum desc\n      for(int i = 0; i < S; i++){\n        int s = 0;\n        for(int x : X[i]) s += x;\n        sumVal[i] = s;\n        V[i] = {s, i};\n      }\n      sort(V.begin(), V.end(), greater<>());\n\n      // 2) pick distinct max\u2010in\u2010each\u2010dimension champions\n      champSeeds.clear();\n      fill(isChampion.begin(), isChampion.end(), 0);\n      for(int d = 0; d < M; d++){\n        int who = 0, bv = -1;\n        for(int i = 0; i < S; i++){\n          if(X[i][d] > bv){\n            bv = X[i][d];\n            who = i;\n          }\n        }\n        if(!isChampion[who]){\n          isChampion[who] = 1;\n          champSeeds.push_back(who);\n        }\n      }\n      // sort those champions by sum desc\n      sort(champSeeds.begin(), champSeeds.end(),\n           [&](int a,int b){ return sumVal[a] > sumVal[b]; });\n\n      // 3) build our 36 picks = all champions first, then top\u2010sum remainder\n      picks = champSeeds;\n      fill(usedPlaced.begin(), usedPlaced.end(), 0);\n      for(int c : champSeeds) usedPlaced[c] = 1;\n      for(auto &pr : V){\n        if((int)picks.size() >= P) break;\n        int id = pr.second;\n        if(!usedPlaced[id]){\n          usedPlaced[id] = 1;\n          picks.push_back(id);\n        }\n      }\n      // now picks.size()==36\n\n      // 4) sort all 36 picks by sum desc\n      sort(picks.begin(), picks.end(),\n           [&](int a,int b){ return sumVal[a] > sumVal[b]; });\n\n      // 5) INITIAL ASSIGNMENT: champion\u2010first into interior, then fill\n      fill(usedPlaced.begin(), usedPlaced.end(), 0);\n      int C = champSeeds.size(), ptr = 0;\n      // 5a) force champions into first C interior slots\n      for(int i = 0; i < C; i++){\n        int u  = interior[i];\n        int id = champSeeds[i];\n        pos2seed[u]    = id;\n        usedPlaced[id] = 1;\n      }\n      // 5b) fill remaining interior slots\n      ptr = 0;\n      for(int i = C; i < (int)interior.size(); i++){\n        while(usedPlaced[picks[ptr]]) ptr++;\n        int u  = interior[i];\n        int id = picks[ptr++];\n        pos2seed[u]    = id;\n        usedPlaced[id] = 1;\n      }\n      // 5c) fill edges\n      for(int u : edges){\n        while(usedPlaced[picks[ptr]]) ptr++;\n        int id = picks[ptr++];\n        pos2seed[u]    = id;\n        usedPlaced[id] = 1;\n      }\n      // 5d) fill corners\n      for(int u : corners){\n        while(usedPlaced[picks[ptr]]) ptr++;\n        int id = picks[ptr++];\n        pos2seed[u]    = id;\n        usedPlaced[id] = 1;\n      }\n\n      // 6) BUILD diffMat for these 36 picks\n      for(int i = 0; i < 36; i++){\n        seed2idx[ picks[i] ] = i;\n      }\n      for(int i = 0; i < 36; i++){\n        diffMat[i][i] = 0;\n        for(int j = i+1; j < 36; j++){\n          int a = picks[i], b = picks[j], d = 0;\n          for(int l = 0; l < M; l++){\n            d += abs(X[a][l] - X[b][l]);\n          }\n          diffMat[i][j] = diffMat[j][i] = d;\n        }\n      }\n\n      // 7) split into FREE vs CLUSTER (interior) cells\n      static vector<char> inInt(P,0);\n      fill(inInt.begin(), inInt.end(), 0);\n      for(int u : interior) inInt[u] = 1;\n      vector<int> FREE_POS, CLUSTER_POS;\n      FREE_POS.reserve(P);\n      CLUSTER_POS.reserve(interior.size());\n      for(int u = 0; u < P; u++){\n        if(inInt[u])      CLUSTER_POS.push_back(u);\n        else              FREE_POS.push_back(u);\n      }\n\n      // 8a) greedy hill\u2010climb among FREE_POS\n      int U0 = FREE_POS.size();\n      for(int it = 0; it < FREE_ITERS; it++){\n        int i = rnd64()%U0, j = rnd64()%U0;\n        if(i==j) continue;\n        int p = FREE_POS[i], q = FREE_POS[j];\n        int sp = pos2seed[p], sq = pos2seed[q];\n        int spi = seed2idx[sp], sqi = seed2idx[sq];\n        int delta = 0;\n        // p's neighbors\n        for(int r : nbr[p]){\n          if(r==q) continue;\n          int sr = pos2seed[r];\n          int sri = seed2idx[sr];\n          delta += (sumVal[sq] + sumVal[sr] + diffMat[sqi][sri])\n                 - (sumVal[sp] + sumVal[sr] + diffMat[spi][sri]);\n        }\n        // q's neighbors\n        for(int r : nbr[q]){\n          if(r==p) continue;\n          int sr = pos2seed[r];\n          int sri = seed2idx[sr];\n          delta += (sumVal[sp] + sumVal[sr] + diffMat[spi][sri])\n                 - (sumVal[sq] + sumVal[sr] + diffMat[sqi][sri]);\n        }\n        if(delta > 0){\n          swap(pos2seed[p], pos2seed[q]);\n        }\n      }\n\n      // 8b) greedy hill\u2010climb among CLUSTER_POS\n      int U1 = CLUSTER_POS.size();\n      for(int it = 0; it < CLUSTER_ITERS; it++){\n        int i = rnd64()%U1, j = rnd64()%U1;\n        if(i==j) continue;\n        int p = CLUSTER_POS[i], q = CLUSTER_POS[j];\n        int sp = pos2seed[p], sq = pos2seed[q];\n        int spi = seed2idx[sp], sqi = seed2idx[sq];\n        int delta = 0;\n        for(int r : nbr[p]){\n          if(r==q) continue;\n          int sr = pos2seed[r], sri = seed2idx[sr];\n          delta += (sumVal[sq] + sumVal[sr] + diffMat[sqi][sri])\n                 - (sumVal[sp] + sumVal[sr] + diffMat[spi][sri]);\n        }\n        for(int r : nbr[q]){\n          if(r==p) continue;\n          int sr = pos2seed[r], sri = seed2idx[sr];\n          delta += (sumVal[sp] + sumVal[sr] + diffMat[spi][sri])\n                 - (sumVal[sq] + sumVal[sr] + diffMat[sqi][sri]);\n        }\n        if(delta > 0){\n          swap(pos2seed[p], pos2seed[q]);\n        }\n      }\n\n      // 9) output planting\n      for(int r=0;r<N;r++){\n        for(int c=0;c<N;c++){\n          cout << pos2seed[idx(r,c)]\n               << (c+1<N?' ':'\\n');\n        }\n      }\n      cout << flush;\n\n      // 10) read next generation\n      for(int i = 0; i < S; i++){\n        for(int j = 0; j < M; j++){\n          cin >> X[i][j];\n        }\n      }\n    }\n\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\n// Directions: 0=right,1=down,2=left,3=up\nstatic const int DX[4] = {0,1,0,-1};\nstatic const int DY[4] = {1,0,-1,0};\nstatic const char DIRC[4] = {'R','D','L','U'};\n\nint N, M, Vmax, F, Vp;\nvector<pair<int,int>> src, dst;\nvector<vector<char>> cur;        // grid occupancy\nvector<int> dir_leaf;           // fingertip dir for each leaf 1..F\nvector<bool> holding_leaf;      // whether leaf i holds a takoyaki\nint rx, ry;                     // current root position\nvector<string> ops;\n\n// To forbid dropping on an unpicked source:\nvector<vector<int>> src_idx;    // src_idx[x][y] = index in src[] or -1\nvector<int> dst_src_idx;        // for each target j: overlapping source\u2010index or -1\n\n// Compute minimal turns to move leaf `lid` so its fingertip lands at (tx,ty),\n// starting from (rx,ry,dir_leaf[lid]).\nint schedule_cost(int lid, int tx, int ty) {\n    int best = INT_MAX;\n    int d0 = dir_leaf[lid];\n    for(int d=0; d<4; d++){\n        int brx = tx - DX[d], bry = ty - DY[d];\n        if(brx<0||brx>=N||bry<0||bry>=N) continue;\n        int dist = abs(brx - rx) + abs(bry - ry);\n        int cw   = (d - d0 + 4) % 4;\n        int ccw  = (d0 - d + 4) % 4;\n        int rot  = min(cw, ccw);\n        best = min(best, max(dist, rot));\n    }\n    return best;\n}\n\n// Actually move leaf `lid` so its fingertip lands on (tx,ty), then do one 'P'.\nvoid move_finger(int lid, int tx, int ty){\n    int bestT=INT_MAX, bestD=0, brx=0, bry=0, brot=0, bcw=0;\n    int d0 = dir_leaf[lid];\n    // 1) choose best orientation d and root pos\n    for(int d=0; d<4; d++){\n        int nrx = tx - DX[d], nry = ty - DY[d];\n        if(nrx<0||nrx>=N||nry<0||nry>=N) continue;\n        int dist = abs(nrx - rx) + abs(nry - ry);\n        int cw   = (d - d0 + 4) % 4;\n        int ccw  = (d0 - d + 4) % 4;\n        int rot  = min(cw, ccw);\n        int T    = max(dist, rot);\n        if(T < bestT){\n            bestT = T;\n            bestD = d;\n            brx   = nrx; bry = nry;\n            brot  = rot; bcw = (cw <= ccw);\n        }\n    }\n    if(bestT == INT_MAX){\n        ops.push_back(string(2*Vp, '.'));\n        return;\n    }\n    // 2) emit T = max(1,bestT) turns\n    int T = max(1, bestT);\n    int dist   = abs(brx - rx) + abs(bry - ry);\n    int remx   = brx - rx, remy = bry - ry;\n    int rotCnt = brot;\n    char rotCh = bcw ? 'R' : 'L';\n    for(int step=0; step<T; step++){\n        char m='.', r='.', a='.';\n        // move root\n        if(step < dist){\n            if(remx>0){ m='D'; remx--; rx++; }\n            else if(remx<0){ m='U'; remx++; rx--; }\n            else if(remy>0){ m='R'; remy--; ry++; }\n            else if(remy<0){ m='L'; remy++; ry--; }\n        }\n        // rotate leaf\n        if(step < rotCnt){\n            r = rotCh;\n            if(rotCh=='R') dir_leaf[lid] = (dir_leaf[lid]+1)&3;\n            else            dir_leaf[lid] = (dir_leaf[lid]+3)&3;\n        }\n        // on last step, pick/place\n        if(step == T-1){\n            int fx = rx + DX[ dir_leaf[lid] ];\n            int fy = ry + DY[ dir_leaf[lid] ];\n            if(fx>=0&&fx<N&&fy>=0&&fy<N){\n                if(!holding_leaf[lid] && cur[fx][fy]){\n                    cur[fx][fy] = 0;\n                    holding_leaf[lid] = true;\n                    a = 'P';\n                } else if(holding_leaf[lid] && !cur[fx][fy]){\n                    cur[fx][fy] = 1;\n                    holding_leaf[lid] = false;\n                    a = 'P';\n                }\n            }\n        }\n        string S(2*Vp, '.');\n        S[0]       = m;\n        S[lid]     = r;\n        S[Vp+lid]  = a;\n        ops.push_back(S);\n    }\n    dir_leaf[lid] = bestD;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    cin >> N >> M >> Vmax;\n    vector<string> Sin(N), Tin(N);\n    for(int i=0;i<N;i++) cin >> Sin[i];\n    for(int i=0;i<N;i++) cin >> Tin[i];\n\n    // Read sources & targets\n    src.reserve(M);\n    dst.reserve(M);\n    cur.assign(N, vector<char>(N,0));\n    vector<vector<char>> occ(N, vector<char>(N,0));\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            if(Sin[i][j]=='1'){\n                src.emplace_back(i,j);\n                cur[i][j] = 1;\n                occ[i][j]=1;\n            }\n            if(Tin[i][j]=='1'){\n                dst.emplace_back(i,j);\n                occ[i][j]=1;\n            }\n        }\n    }\n\n    // Overlap maps\n    src_idx.assign(N, vector<int>(N,-1));\n    for(int i=0;i<M;i++){\n        auto &p = src[i];\n        src_idx[p.first][p.second] = i;\n    }\n    dst_src_idx.assign(M,-1);\n    for(int j=0;j<M;j++){\n        auto &p = dst[j];\n        dst_src_idx[j] = src_idx[p.first][p.second];\n    }\n\n    // Initial root: median of all sources, BFS to nearest empty\n    {\n        vector<int> xs(M), ys(M);\n        for(int i=0;i<M;i++){\n            xs[i] = src[i].first;\n            ys[i] = src[i].second;\n        }\n        sort(xs.begin(), xs.end());\n        sort(ys.begin(), ys.end());\n        int mx0 = xs[M/2], my0 = ys[M/2];\n        queue<pair<int,int>> q;\n        vector<vector<int>> dist(N, vector<int>(N,-1));\n        q.push({mx0,my0});\n        dist[mx0][my0] = 0;\n        bool placed = false;\n        while(!q.empty() && !placed){\n            auto [x,y] = q.front(); q.pop();\n            if(!occ[x][y]){\n                rx = x; ry = y;\n                placed = true;\n                break;\n            }\n            for(int d=0; d<4; d++){\n                int nx=x+DX[d], ny=y+DY[d];\n                if(nx>=0&&nx<N&&ny>=0&&ny<N&&dist[nx][ny]==-1){\n                    dist[nx][ny]=dist[x][y]+1;\n                    q.push({nx,ny});\n                }\n            }\n        }\n        if(!placed){\n            for(int i=0;i<N && !placed;i++){\n                for(int j=0;j<N;j++){\n                    if(!occ[i][j]){\n                        rx=i; ry=j;\n                        placed=true;\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n    // Build star\u2010arm with F leaves\n    F  = min((int)src.size(), Vmax-1);\n    Vp = F + 1;\n    cout << Vp << \"\\n\";\n    for(int i=1;i<=F;i++){\n        cout << 0 << \" \" << 1 << \"\\n\";\n    }\n    cout << rx << \" \" << ry << \"\\n\";\n\n    // Initialize\n    dir_leaf.assign(Vp, 0);\n    holding_leaf.assign(Vp, false);\n\n    vector<int> rem_srcs(M), rem_dsts(M);\n    iota(rem_srcs.begin(), rem_srcs.end(), 0);\n    iota(rem_dsts.begin(), rem_dsts.end(), 0);\n    vector<char> used_src(M,0), used_dst(M,0);\n\n    // Main dynamic\u2010greedy loop\n    while(!rem_srcs.empty() || any_of(holding_leaf.begin()+1, holding_leaf.end(), [](bool b){return b;})) {\n        int bestCost = INT_MAX;\n        int bestLeaf = -1, bestType = -1, bestPos = -1, bestIdx = -1;\n        // scan all leaves\n        for(int lid=1; lid<=F; lid++){\n            if(!holding_leaf[lid]){\n                // can pick\n                for(int k=0; k<(int)rem_srcs.size(); k++){\n                    int si = rem_srcs[k];\n                    int c = schedule_cost(lid, src[si].first, src[si].second);\n                    if(c < bestCost){\n                        bestCost = c;\n                        bestLeaf = lid;\n                        bestType = 0;\n                        bestPos  = k;\n                        bestIdx  = si;\n                    }\n                }\n            } else {\n                // can drop\n                for(int k=0; k<(int)rem_dsts.size(); k++){\n                    int di = rem_dsts[k];\n                    int si = dst_src_idx[di];\n                    if(si >= 0 && !used_src[si]) continue;\n                    int c = schedule_cost(lid, dst[di].first, dst[di].second);\n                    if(c < bestCost){\n                        bestCost = c;\n                        bestLeaf = lid;\n                        bestType = 1;\n                        bestPos  = k;\n                        bestIdx  = di;\n                    }\n                }\n            }\n        }\n        // perform the best action\n        if(bestType == 0){\n            // pickup\n            used_src[bestIdx] = 1;\n            move_finger(bestLeaf, src[bestIdx].first, src[bestIdx].second);\n            // remove rem_srcs[bestPos]\n            rem_srcs[bestPos] = rem_srcs.back();\n            rem_srcs.pop_back();\n            holding_leaf[bestLeaf] = true;\n        } else {\n            // drop\n            used_dst[bestIdx] = 1;\n            move_finger(bestLeaf, dst[bestIdx].first, dst[bestIdx].second);\n            rem_dsts[bestPos] = rem_dsts.back();\n            rem_dsts.pop_back();\n            holding_leaf[bestLeaf] = false;\n        }\n    }\n\n    // Output all turns\n    for(auto &s: ops){\n        cout << s << \"\\n\";\n    }\n    return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Pt { int x, y, w; };\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int HMAX = 100000;\n    const int CG   = 200;\n    const int KREF = 50;   // allow bridging gutters up to 50\n    const int JTR  = 40;   // final jitter trials\n    const int RRS  = 25;   // random\u2010restart trials\n\n    // Multiscale X\u2013sliding windows: (width, trials)\n    vector<pair<int,int>> XSETS = {\n      {  50,  5},\n      { 100,  8},\n      { 200, 15},\n      { 350, 30},\n      { 600,  5}\n    };\n    // Multiscale Y\u2013sliding windows: (height, trials)\n    vector<pair<int,int>> YSETS = {\n      {  50,  5},\n      { 100,  8},\n      { 200, 10},\n      { 300,  6},\n      { 600,  3}\n    };\n\n    int N;\n    cin >> N;\n    vector<Pt> pts(2*N);\n    for(int i = 0; i < 2*N; i++){\n        cin >> pts[i].x >> pts[i].y;\n        pts[i].w = (i < N ? +1 : -1);\n    }\n\n    // 1) Coordinate compression\n    vector<int> xs, ys;\n    xs.reserve(2*N); ys.reserve(2*N);\n    for(auto &p: pts){\n        xs.push_back(p.x);\n        ys.push_back(p.y);\n    }\n    sort(xs.begin(), xs.end());\n    xs.erase(unique(xs.begin(), xs.end()), xs.end());\n    sort(ys.begin(), ys.end());\n    ys.erase(unique(ys.begin(), ys.end()), ys.end());\n    int MX = xs.size(), MY = ys.size();\n\n    vector<int> cX(2*N), cY(2*N);\n    for(int i = 0; i < 2*N; i++){\n        cX[i] = int(lower_bound(xs.begin(), xs.end(), pts[i].x) - xs.begin());\n        cY[i] = int(lower_bound(ys.begin(), ys.end(), pts[i].y) - ys.begin());\n    }\n\n    // 2) Build per\u2010column & per\u2010row bins + prefix sums\n    vector<vector<pair<int,int>>> binsX(MX), binsY(MY);\n    for(int i = 0; i < 2*N; i++){\n        binsX[cX[i]].emplace_back(cY[i], pts[i].w);\n        binsY[cY[i]].emplace_back(cX[i], pts[i].w);\n    }\n    vector<vector<int>> bX_y(MX), bX_ps(MX), bY_x(MY), bY_ps(MY);\n    for(int x = 0; x < MX; x++){\n        auto &v = binsX[x];\n        sort(v.begin(), v.end());\n        int m = v.size();\n        bX_y[x].resize(m);\n        bX_ps[x].resize(m);\n        for(int i = 0; i < m; i++){\n            bX_y[x][i]  = v[i].first;\n            bX_ps[x][i] = v[i].second + (i ? bX_ps[x][i-1] : 0);\n        }\n    }\n    for(int y = 0; y < MY; y++){\n        auto &v = binsY[y];\n        sort(v.begin(), v.end());\n        int m = v.size();\n        bY_x[y].resize(m);\n        bY_ps[y].resize(m);\n        for(int i = 0; i < m; i++){\n            bY_x[y][i]  = v[i].first;\n            bY_ps[y][i] = v[i].second + (i ? bY_ps[y][i-1] : 0);\n        }\n    }\n\n    // Helpers: sum of column cx over y\u2208[y1..y2], row cy over x\u2208[x1..x2]\n    auto colSum = [&](int cx, int y1, int y2){\n        auto &vy = bX_y[cx], &ps = bX_ps[cx];\n        int lo = int(lower_bound(vy.begin(), vy.end(), y1) - vy.begin());\n        int hi = int(upper_bound(vy.begin(), vy.end(), y2) - vy.begin()) - 1;\n        if(lo > hi) return 0;\n        return ps[hi] - (lo ? ps[lo-1] : 0);\n    };\n    auto rowSum = [&](int cy, int x1, int x2){\n        auto &vx = bY_x[cy], &ps = bY_ps[cy];\n        int lo = int(lower_bound(vx.begin(), vx.end(), x1) - vx.begin());\n        int hi = int(upper_bound(vx.begin(), vx.end(), x2) - vx.begin()) - 1;\n        if(lo > hi) return 0;\n        return ps[hi] - (lo ? ps[lo-1] : 0);\n    };\n\n    // 3) Multi\u2010step local refine for a rectangle [x1..x2]\u00d7[y1..y2]\n    auto refineRect = [&](int &x1, int &x2, int &y1, int &y2, int &A){\n        bool improved = true;\n        while(improved){\n            improved = false;\n            // expansions\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && x1-k>=0; k++){\n                    s += colSum(x1-k, y1, y2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ x1-=bk; A+=best; improved=true; continue; }\n            }\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && x2+k<MX; k++){\n                    s += colSum(x2+k, y1, y2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ x2+=bk; A+=best; improved=true; continue; }\n            }\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && y1-k>=0; k++){\n                    s += rowSum(y1-k, x1, x2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ y1-=bk; A+=best; improved=true; continue; }\n            }\n            {\n                int s=0, best=0, bk=0;\n                for(int k=1; k<=KREF && y2+k<MY; k++){\n                    s += rowSum(y2+k, x1, x2);\n                    if(s>best){ best=s; bk=k; }\n                }\n                if(bk){ y2+=bk; A+=best; improved=true; continue; }\n            }\n            // contractions\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && x1+k-1<=x2; k++){\n                    s += colSum(x1+k-1, y1, y2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ x1+=bk; A-=worst; improved=true; continue; }\n            }\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && x2-k+1>=x1; k++){\n                    s += colSum(x2-k+1, y1, y2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ x2-=bk; A-=worst; improved=true; continue; }\n            }\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && y1+k-1<=y2; k++){\n                    s += rowSum(y1+k-1, x1, x2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ y1+=bk; A-=worst; improved=true; continue; }\n            }\n            {\n                int s=0, worst=0, bk=0;\n                for(int k=1; k<=KREF && y2-k+1>=y1; k++){\n                    s += rowSum(y2-k+1, x1, x2);\n                    if(s<worst){ worst=s; bk=k; }\n                }\n                if(bk){ y2-=bk; A-=worst; improved=true; continue; }\n            }\n        }\n    };\n\n    struct Rect { int x1,x2,y1,y2,A; };\n    vector<Rect> cands;\n    mt19937_64 rng(1234567);\n\n    // 4) Multiscale X\u2010sliding windows\n    for(auto &ws : XSETS){\n        int K = ws.first, NI = ws.second;\n        uniform_int_distribution<int> distL(0, max(0, MX - K));\n        vector<int> W(MY);\n        int bestA = INT_MIN, bx1=0,bx2=0,by1=0,by2=0;\n        for(int it=0; it<NI; it++){\n            int L = (MX>K ? distL(rng) : 0);\n            fill(W.begin(), W.end(), 0);\n            int Rlim = min(MX, L + K);\n            for(int R=L; R<Rlim; R++){\n                for(auto &pr: binsX[R])\n                    W[pr.first] += pr.second;\n                // Kadane on W\n                int cur=W[0], t0=0, best=cur, sy=0, ey=0;\n                for(int y=1; y<MY; y++){\n                    if(cur>0) cur+=W[y];\n                    else { cur=W[y]; t0=y; }\n                    if(cur>best){ best=cur; sy=t0; ey=y; }\n                }\n                if(best>bestA){\n                    bestA=best;\n                    bx1=L; bx2=R;\n                    by1=sy; by2=ey;\n                }\n            }\n        }\n        if(bestA>INT_MIN/2)\n            cands.push_back({bx1,bx2,by1,by2,bestA});\n    }\n\n    // 5) Multiscale Y\u2010sliding windows (Kadane on X)\n    for(auto &hs : YSETS){\n        int Ht=hs.first, NI=hs.second;\n        uniform_int_distribution<int> distY(0, max(0, MY - Ht));\n        vector<int> W2(MX);\n        int bestA=INT_MIN, hy1=0,hy2=0,hx1=0,hx2=0;\n        for(int it=0; it<NI; it++){\n            int Ly = (MY>Ht ? distY(rng) : 0);\n            fill(W2.begin(), W2.end(), 0);\n            int Rym = min(MY, Ly + Ht);\n            for(int Ry=Ly; Ry<Rym; Ry++){\n                for(auto &pr: binsY[Ry])\n                    W2[pr.first] += pr.second;\n                // Kadane on W2\n                int cur=W2[0], t0=0, best=cur, sx=0, ex=0;\n                for(int x=1; x<MX; x++){\n                    if(cur>0) cur+=W2[x];\n                    else { cur=W2[x]; t0=x; }\n                    if(cur>best){ best=cur; sx=t0; ex=x; }\n                }\n                if(best>bestA){\n                    bestA=best;\n                    hy1=Ly; hy2=Ry;\n                    hx1=sx; hx2=ex;\n                }\n            }\n        }\n        if(bestA>INT_MIN/2)\n            cands.push_back({hx1,hx2,hy1,hy2,bestA});\n    }\n\n    // 6) Full\u2010width & full\u2010height stripes\n    {\n        vector<int> Wcol(MX);\n        for(int x=0; x<MX; x++)\n            Wcol[x] = bX_ps[x].empty() ? 0 : bX_ps[x].back();\n        int cur=Wcol[0], t0=0, best=cur, sx=0, ex=0;\n        for(int x=1; x<MX; x++){\n            if(cur>0) cur+=Wcol[x];\n            else { cur=Wcol[x]; t0=x; }\n            if(cur>best){ best=cur; sx=t0; ex=x; }\n        }\n        cands.push_back({sx,ex,0,MY-1,best});\n    }\n    {\n        vector<int> Wrow(MY);\n        for(int y=0; y<MY; y++)\n            Wrow[y] = bY_ps[y].empty() ? 0 : bY_ps[y].back();\n        int cur=Wrow[0], t0=0, best=cur, sy=0, ey=0;\n        for(int y=1; y<MY; y++){\n            if(cur>0) cur+=Wrow[y];\n            else { cur=Wrow[y]; t0=y; }\n            if(cur>best){ best=cur; sy=t0; ey=y; }\n        }\n        cands.push_back({0,MX-1,sy,ey,best});\n    }\n\n    // 7) Coarse\u2192fine rectangle\n    static int cgrid[CG][CG];\n    int CW = (HMAX + CG) / CG;\n    for(int i=0;i<CG;i++) for(int j=0;j<CG;j++) cgrid[i][j]=0;\n    for(auto &p: pts){\n        int xi = min(CG-1, p.x / CW);\n        int yi = min(CG-1, p.y / CW);\n        cgrid[xi][yi] += p.w;\n    }\n    vector<int> tmpCG(CG);\n    int bestA2=INT_MIN, cx1=0,cx2=0,cy1=0,cy2=0;\n    for(int Lx=0; Lx<CG; Lx++){\n        fill(tmpCG.begin(), tmpCG.end(), 0);\n        for(int Rx=Lx; Rx<CG; Rx++){\n            for(int y=0;y<CG;y++)\n                tmpCG[y] += cgrid[Rx][y];\n            int cur=tmpCG[0], t0=0, best=cur, sy=0, ey=0;\n            for(int y=1;y<CG;y++){\n                if(cur>0) cur+=tmpCG[y];\n                else { cur=tmpCG[y]; t0=y; }\n                if(cur>best){ best=cur; sy=t0; ey=y; }\n            }\n            if(best>bestA2){\n                bestA2=best;\n                cx1=Lx; cx2=Rx;\n                cy1=sy; cy2=ey;\n            }\n        }\n    }\n    {\n        int X0 = cx1*CW, X1 = min(HMAX,(cx2+1)*CW - 1);\n        int Y0 = cy1*CW, Y1 = min(HMAX,(cy2+1)*CW - 1);\n        vector<Pt> sub; sub.reserve(2000);\n        for(auto &p: pts)\n            if(p.x>=X0 && p.x<=X1 && p.y>=Y0 && p.y<=Y1)\n                sub.push_back(p);\n        if(!sub.empty()){\n            vector<int> xs3, ys3;\n            xs3.reserve(sub.size()); ys3.reserve(sub.size());\n            for(auto &q: sub){\n                xs3.push_back(q.x);\n                ys3.push_back(q.y);\n            }\n            sort(xs3.begin(), xs3.end());\n            xs3.erase(unique(xs3.begin(), xs3.end()), xs3.end());\n            sort(ys3.begin(), ys3.end());\n            ys3.erase(unique(ys3.begin(), ys3.end()), ys3.end());\n            int RX = xs3.size(), RY = ys3.size();\n            vector<int> cqx(sub.size()), cqy(sub.size());\n            for(int i=0;i<(int)sub.size();i++){\n                cqx[i] = int(lower_bound(xs3.begin(), xs3.end(), sub[i].x) - xs3.begin());\n                cqy[i] = int(lower_bound(ys3.begin(), ys3.end(), sub[i].y) - ys3.begin());\n            }\n            vector<vector<pair<int,int>>> bX2(RX);\n            for(int i=0;i<(int)sub.size();i++){\n                bX2[cqx[i]].emplace_back(cqy[i], sub[i].w);\n            }\n            int bestA3=INT_MIN, rx1=0,rx2=0,ry1=0,ry2=0;\n            if(RX <= 500){\n                vector<int> tmp(RY);\n                for(int L=0; L<RX; L++){\n                    fill(tmp.begin(), tmp.end(), 0);\n                    for(int R=L; R<RX; R++){\n                        for(auto &pr: bX2[R]) tmp[pr.first] += pr.second;\n                        int cur=tmp[0], t0=0, best=cur, sy=0, ey=0;\n                        for(int y=1;y<RY;y++){\n                            if(cur>0) cur+=tmp[y];\n                            else { cur=tmp[y]; t0=y; }\n                            if(cur>best){ best=cur; sy=t0; ey=y; }\n                        }\n                        if(best>bestA3){\n                            bestA3=best;\n                            rx1=L; rx2=R; ry1=sy; ry2=ey;\n                        }\n                    }\n                }\n            } else {\n                vector<int> tmp(RY);\n                uniform_int_distribution<int> dist2(0, max(0, RX-600));\n                vector<int> starts(6);\n                for(int i=0;i<6;i++) starts[i] = (RX>600?dist2(rng):0);\n                for(int L: starts){\n                    fill(tmp.begin(), tmp.end(), 0);\n                    int Rlim = min(RX, L+600);\n                    for(int R=L; R<Rlim; R++){\n                        for(auto &pr: bX2[R]) tmp[pr.first] += pr.second;\n                        int cur=tmp[0], t0=0, best=cur, sy=0, ey=0;\n                        for(int y=1;y<RY;y++){\n                            if(cur>0) cur+=tmp[y];\n                            else { cur=tmp[y]; t0=y; }\n                            if(cur>best){ best=cur; sy=t0; ey=y; }\n                        }\n                        if(best>bestA3){\n                            bestA3=best;\n                            rx1=L; rx2=R; ry1=sy; ry2=ey;\n                        }\n                    }\n                }\n            }\n            if(bestA3>INT_MIN/2){\n                int gx1 = int(lower_bound(xs.begin(), xs.end(), xs3[rx1]) - xs.begin());\n                int gx2 = int(lower_bound(xs.begin(), xs.end(), xs3[rx2]) - xs.begin());\n                int gy1 = int(lower_bound(ys.begin(), ys.end(), ys3[ry1]) - ys.begin());\n                int gy2 = int(lower_bound(ys.begin(), ys.end(), ys3[ry2]) - ys.begin());\n                if(gx1<=gx2 && gy1<=gy2){\n                    int A3=0;\n                    for(int xx=gx1; xx<=gx2; xx++)\n                        A3 += colSum(xx, gy1, gy2);\n                    cands.push_back({gx1,gx2,gy1,gy2,A3});\n                }\n            }\n        }\n    }\n\n    // 8) Refine all candidates\n    for(auto &r : cands){\n        if(r.x1<=r.x2 && r.y1<=r.y2)\n            refineRect(r.x1, r.x2, r.y1, r.y2, r.A);\n    }\n\n    // 9) Pick current best\n    int bestA = INT_MIN, bx1=0,bx2=0,by1=0,by2=0;\n    for(auto &r : cands){\n        if(r.A > bestA){\n            bestA=r.A;\n            bx1=r.x1; bx2=r.x2;\n            by1=r.y1; by2=r.y2;\n        }\n    }\n\n    // 10) Random\u2010Restart: try RRS random rectangles\n    uniform_int_distribution<int> distX0(0, MX-2), distY0(0, MY-2);\n    for(int it=0; it<RRS; it++){\n        int rx1 = distX0(rng);\n        int ry1 = distY0(rng);\n        int rx2 = uniform_int_distribution<int>(rx1+1, MX-1)(rng);\n        int ry2 = uniform_int_distribution<int>(ry1+1, MY-1)(rng);\n        int A = 0;\n        for(int x=rx1; x<=rx2; x++)\n            A += colSum(x, ry1, ry2);\n        refineRect(rx1, rx2, ry1, ry2, A);\n        if(A > bestA){\n            bestA = A;\n            bx1 = rx1; bx2 = rx2;\n            by1 = ry1; by2 = ry2;\n        }\n    }\n\n    // 11) Final jitter around best\n    uniform_int_distribution<int> uni01(0,1);\n    for(int it=0; it<JTR; it++){\n        int w = bx2 - bx1 + 1, h = by2 - by1 + 1;\n        int dx = max(1, w/2), dy = max(1, h/2);\n        uniform_int_distribution<int> dX(-dx, dx), dY(-dy, dy);\n        int rx1 = clamp(bx1 + dX(rng), 0, MX-2);\n        int rx2 = clamp(bx2 + dX(rng), rx1+1, MX-1);\n        int ry1 = clamp(by1 + dY(rng), 0, MY-2);\n        int ry2 = clamp(by2 + dY(rng), ry1+1, MY-1);\n        int A = 0;\n        for(int x=rx1; x<=rx2; x++)\n            A += colSum(x, ry1, ry2);\n        refineRect(rx1, rx2, ry1, ry2, A);\n        if(A > bestA){\n            bestA = A;\n            bx1 = rx1; bx2 = rx2;\n            by1 = ry1; by2 = ry2;\n        }\n    }\n\n    // 12) Fallback if non\u2010positive or degenerate\n    if(bestA <= 0 || bx2 <= bx1 || by2 <= by1){\n        bx1 = by1 = 0;\n        bx2 = by2 = 1;\n    }\n\n    // 13) Output final 4\u2010vertex rectangle\n    cout << 4 << \"\\n\";\n    cout << xs[bx1] << \" \" << ys[by1] << \"\\n\";\n    cout << xs[bx1] << \" \" << ys[by2] << \"\\n\";\n    cout << xs[bx2] << \" \" << ys[by2] << \"\\n\";\n    cout << xs[bx2] << \" \" << ys[by1] << \"\\n\";\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nstatic const int MAXN = 100;\n\nstruct Cand {\n    ll sc_pred;           // predicted max_row_width + sum_row_heights\n    int R;                // number of shelves\n    int row[MAXN];        // row[i] = shelf index of rect i\n    int rep[MAXN];        // rep[r] = index of tallest rect in shelf r\n};\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, T;\n    ll sigma;\n    cin >> N >> T >> sigma;\n\n    static ll w0[MAXN], h0[MAXN], wi[MAXN], hi[MAXN];\n    for(int i = 0; i < N; i++){\n        cin >> w0[i] >> h0[i];\n        wi[i] = min(w0[i], h0[i]);\n        hi[i] = max(w0[i], h0[i]);\n    }\n    ll totalW = accumulate(wi, wi+N, 0LL);\n\n    // Build up to 3\u00b7N candidates\n    vector<Cand> cands;\n    cands.reserve(3*N);\n\n    // Temps for slicing\n    static int start1[MAXN], sz1[MAXN];\n    static int start2[MAXN], sz2[MAXN];\n    static int start3[MAXN], sz3[MAXN];\n    static int rowT[MAXN], repT[MAXN];\n\n    for(int R = 1; R <= N; R++){\n        // Scheme 1: count\u2010balanced\n        {\n            int base = N/R, rem = N%R, idx = 0;\n            for(int r = 0; r < R; r++){\n                start1[r] = idx;\n                sz1[r]    = base + (r < rem);\n                idx       += sz1[r];\n            }\n            ll maxW = 0, sumH = 0;\n            for(int r = 0; r < R; r++){\n                ll sw = 0, mh = 0;\n                int t0 = start1[r];\n                for(int j = 0; j < sz1[r]; j++){\n                    int i = start1[r] + j;\n                    rowT[i] = r;\n                    sw += wi[i];\n                    mh = max(mh, hi[i]);\n                    if(hi[i] > hi[t0]) t0 = i;\n                }\n                repT[r] = t0;\n                maxW = max(maxW, sw);\n                sumH += mh;\n            }\n            Cand c{maxW + sumH, R};\n            memcpy(c.row, rowT, sizeof(int)*N);\n            memcpy(c.rep, repT, sizeof(int)*R);\n            cands.push_back(c);\n        }\n\n        // Scheme 2: greedy \u2264 target\n        {\n            ll target = totalW / R;\n            int idx = 0;\n            for(int r = 0; r < R; r++){\n                start2[r] = idx;\n                if(r == R-1){\n                    sz2[r] = N - idx;\n                    idx = N;\n                } else {\n                    ll acc = wi[idx];\n                    sz2[r] = 1; idx++;\n                    while(idx < N && acc + wi[idx] <= target){\n                        acc += wi[idx++];\n                        sz2[r]++;\n                    }\n                }\n            }\n            ll maxW = 0, sumH = 0;\n            for(int r = 0; r < R; r++){\n                ll sw = 0, mh = 0;\n                int t0 = start2[r];\n                for(int j = 0; j < sz2[r]; j++){\n                    int i = start2[r] + j;\n                    rowT[i] = r;\n                    sw += wi[i];\n                    mh = max(mh, hi[i]);\n                    if(hi[i] > hi[t0]) t0 = i;\n                }\n                repT[r] = t0;\n                maxW = max(maxW, sw);\n                sumH += mh;\n            }\n            Cand c{maxW + sumH, R};\n            memcpy(c.row, rowT, sizeof(int)*N);\n            memcpy(c.rep, repT, sizeof(int)*R);\n            cands.push_back(c);\n        }\n\n        // Scheme 3: greedy \u2265 target\n        {\n            ll target = totalW / R;\n            int idx = 0;\n            for(int r = 0; r < R; r++){\n                start3[r] = idx;\n                if(r == R-1){\n                    sz3[r] = N - idx;\n                    idx = N;\n                } else {\n                    ll acc = wi[idx];\n                    sz3[r] = 1; idx++;\n                    while(idx < N && acc < target){\n                        acc += wi[idx++];\n                        sz3[r]++;\n                    }\n                }\n            }\n            ll maxW = 0, sumH = 0;\n            for(int r = 0; r < R; r++){\n                ll sw = 0, mh = 0;\n                int t0 = start3[r];\n                for(int j = 0; j < sz3[r]; j++){\n                    int i = start3[r] + j;\n                    rowT[i] = r;\n                    sw += wi[i];\n                    mh = max(mh, hi[i]);\n                    if(hi[i] > hi[t0]) t0 = i;\n                }\n                repT[r] = t0;\n                maxW = max(maxW, sw);\n                sumH += mh;\n            }\n            Cand c{maxW + sumH, R};\n            memcpy(c.row, rowT, sizeof(int)*N);\n            memcpy(c.rep, repT, sizeof(int)*R);\n            cands.push_back(c);\n        }\n    }\n\n    // Sort all candidates by predicted score\n    sort(cands.begin(), cands.end(),\n         [&](auto &A, auto &B){ return A.sc_pred < B.sc_pred; });\n\n    int C = (int)cands.size();\n    int p1 = min(C, max(1, T/3));\n    int rem = T - p1;\n    int p2 = min(N, max(1, rem/2));\n    int p3 = T - p1 - p2;\n\n    // baseline rotations\n    vector<int> rotbest(N);\n    for(int i = 0; i < N; i++){\n        rotbest[i] = (h0[i] < w0[i] ? 1 : 0);\n    }\n\n    ll bestMeas = LLONG_MAX;\n    int bestIdx = 0, t = 0;\n\n    auto print_layout = [&](int row[], int rep[], const vector<int> &rot){\n        cout << N << \"\\n\";\n        int last0 = -1;\n        for(int i = 0; i < N; i++){\n            int r = row[i], rbit = rot[i];\n            char d; int b;\n            if(r == 0){\n                d = 'U'; b = last0; last0 = i;\n            } else {\n                d = 'L'; b = rep[r-1];\n            }\n            cout << i << \" \" << rbit << \" \" << d << \" \" << b << \"\\n\";\n        }\n        cout << flush;\n    };\n\n    // PHASE1: probe top p1 candidates\n    for(; t < p1; t++){\n        auto &cd = cands[t];\n        vector<int> rot = rotbest;\n        print_layout(cd.row, cd.rep, rot);\n        ll Wp,H; cin >> Wp >> H;\n        ll m = Wp + H;\n        if(m < bestMeas){\n            bestMeas = m;\n            bestIdx  = t;\n        }\n    }\n    // PHASE2: rotation local search\n    for(int j = 0; j < p2 && t < T; j++, t++){\n        auto &cd = cands[bestIdx];\n        vector<int> rot = rotbest;\n        rot[j] = 1 - rot[j];\n        print_layout(cd.row, cd.rep, rot);\n        ll Wp,H; cin >> Wp >> H;\n        ll m = Wp + H;\n        if(m < bestMeas){\n            bestMeas = m;\n            rotbest[j] = rot[j];\n        }\n    }\n    // PHASE3: boundary local search\n    // copy best candidate\n    auto &cb = cands[bestIdx];\n    vector<int> row_cur(N), rep_cur(cb.R), rot_cur = rotbest;\n    memcpy(row_cur.data(), cb.row, sizeof(int)*N);\n    memcpy(rep_cur.data(), cb.rep, sizeof(int)*cb.R);\n    int Rcur = cb.R;\n    for(int k = 0; k < p3 && t < T; k++, t++){\n        bool ok=false;\n        vector<int> row_new = row_cur, rep_new = rep_cur;\n        if(Rcur>1){\n            int br = 1 + (k % (Rcur-1));\n            int i0=-1;\n            for(int i=0;i<N;i++) if(row_cur[i]==br){ i0=i; break; }\n            if(i0>=0){\n                row_new[i0] = br-1;\n                // recompute rep for br-1 and br\n                ll mh=-1; int mi=-1;\n                for(int i=0;i<N;i++) if(row_new[i]==br-1 && hi[i]>mh){ mh=hi[i]; mi=i; }\n                rep_new[br-1] = mi;\n                mh=-1; mi=-1;\n                for(int i=0;i<N;i++) if(row_new[i]==br && hi[i]>mh){ mh=hi[i]; mi=i; }\n                rep_new[br] = mi;\n                ok = true;\n            }\n        }\n        if(ok){\n            print_layout(row_new.data(), rep_new.data(), rot_cur);\n            ll Wp,H; cin >> Wp >> H;\n            ll m = Wp + H;\n            if(m < bestMeas){\n                bestMeas = m;\n                row_cur.swap(row_new);\n                rep_cur.swap(rep_new);\n            }\n        } else {\n            print_layout(row_cur.data(), rep_cur.data(), rot_cur);\n            ll Wp,H; cin >> Wp >> H;\n        }\n    }\n    // leftover: replay\n    while(t < T){\n        print_layout(row_cur.data(), rep_cur.data(), rot_cur);\n        ll Wp,H; cin >> Wp >> H;\n        t++;\n    }\n\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, H;\n    cin >> N >> M >> H;\n\n    vector<int> A(N);\n    for(int i = 0; i < N; i++) 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    // discard coordinates\n    for(int i = 0; i < N; i++){\n        int x,y; \n        cin >> x >> y;\n    }\n\n    // ------------------------------------------------\n    // 1) Precompute for each r the list of (v,dist) with dist<=H\n    //    and the staticScore[r] = sum_{v,dist} (dist+1)*A[v]\n    // ------------------------------------------------\n    vector<vector<pair<int,uint8_t>>> reach(N);\n    vector<ll> staticScore(N, 0);\n    vector<int> q(N), dist(N, -1);\n\n    for(int r = 0; r < N; r++){\n        int ql = 0, qr = 0;\n        dist[r] = 0;\n        q[qr++] = r;\n        while(ql < qr){\n            int u = q[ql++];\n            if(dist[u] == H) continue;\n            for(int w: adj[u]){\n                if(dist[w] == -1){\n                    dist[w] = dist[u] + 1;\n                    q[qr++] = w;\n                }\n            }\n        }\n        ll sc = 0;\n        reach[r].reserve(qr);\n        for(int i = 0; i < qr; i++){\n            int v = q[i], d = dist[v];\n            reach[r].emplace_back(v, (uint8_t)d);\n            sc += ll(d + 1) * A[v];\n            dist[v] = -1;\n        }\n        staticScore[r] = sc;\n    }\n\n    // ------------------------------------------------\n    // 2) Multi\u2010start randomized greedy covering\n    // ------------------------------------------------\n    const int RUNS   = 40;  // independent restarts\n    const int TOPS   = 70;  // consider only the top\u201070 static\u2010score roots\n    const int Kbest  = 15;  // randomize among the top\u201015 by dynamic score\n    const int MAX_SUB = 80; // allow reattaching subtrees up to size 80\n\n    mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());\n\n    vector<int> bestParent(N), bestDepth(N);\n    ll bestGlobal = -1;\n\n    // working arrays for each run\n    vector<char> covered(N);\n    vector<int> parent(N), depth(N), dist2(N), q2(N);\n    vector<int> cand(TOPS), idx(TOPS);\n    vector<ll> dyn(TOPS);\n\n    for(int run = 0; run < RUNS; run++){\n        // build a run\u2010specific static ordering by adding \u00b120% noise\n        vector<pair<double,int>> order(N);\n        for(int i = 0; i < N; i++){\n            double noise = (double(rng()%40001)/10000.0 - 2.0) * 0.1; // [-0.2,+0.2]\n            order[i] = { staticScore[i] * (1.0 + noise), i };\n        }\n        sort(order.begin(), order.end(),\n             [&](auto &a, auto &b){ return a.first > b.first; });\n        vector<int> staticRun(N);\n        for(int i = 0; i < N; i++) staticRun[i] = order[i].second;\n\n        // reset\n        fill(covered.begin(), covered.end(), 0);\n        fill(parent.begin(), parent.end(), -1);\n        fill(depth.begin(), depth.end(), 0);\n        int rem = N;\n\n        // greedy\u2010cover loop\n        while(rem > 0){\n            // pick up to TOPS uncovered by staticRun\n            int S = 0;\n            for(int v: staticRun){\n                if(!covered[v]){\n                    cand[S++] = v;\n                    if(S == TOPS) break;\n                }\n            }\n            // compute dynamic scores\n            for(int i = 0; i < S; i++){\n                ll sc = 0;\n                int r = cand[i];\n                for(auto &pr: reach[r]){\n                    if(!covered[pr.first]){\n                        sc += ll(pr.second + 1) * A[pr.first];\n                    }\n                }\n                dyn[i] = sc;\n                idx[i] = i;\n            }\n            // partial sort by dyn[]\n            sort(idx.begin(), idx.begin()+S,\n                 [&](int i, int j){ return dyn[i] > dyn[j]; });\n\n            // pick one root (pure greedy on run0, otherwise random among top Kbest)\n            int pick;\n            if(run == 0){\n                pick = idx[0];\n            } else {\n                int L = min(Kbest, S);\n                uniform_int_distribution<int> D(0, L-1);\n                pick = idx[D(rng)];\n            }\n            int root = cand[pick];\n\n            // carve out an H\u2010limited BFS\u2010tree from root\n            fill(dist2.begin(), dist2.end(), -1);\n            int ql2 = 0, qr2 = 0;\n            dist2[root] = 0;\n            covered[root] = 1;\n            parent[root]  = -1;\n            depth[root]   = 0;\n            q2[qr2++]    = root;\n            rem--;\n\n            while(ql2 < qr2){\n                int u = q2[ql2++];\n                if(dist2[u] == H) continue;\n                for(int w: adj[u]){\n                    if(!covered[w] && dist2[w] == -1){\n                        dist2[w]    = dist2[u] + 1;\n                        covered[w]  = 1;\n                        parent[w]   = u;\n                        depth[w]    = dist2[w];\n                        q2[qr2++]   = w;\n                        rem--;\n                    }\n                }\n            }\n        }\n\n        // score this run\n        ll runScore = 0;\n        for(int v = 0; v < N; v++){\n            runScore += ll(depth[v] + 1) * A[v];\n        }\n        if(runScore > bestGlobal){\n            bestGlobal = runScore;\n            bestParent = parent;\n            bestDepth  = depth;\n        }\n    }\n\n    // ------------------------------------------------\n    // 3) \u201cSmall\u2010subtree reattachment\u201d local search (\u00d72 passes)\n    // ------------------------------------------------\n    vector<vector<int>> children(N);\n    vector<int> rootOf(N), tin(N), tout(N), subSize(N), subMaxD(N);\n    vector<ll> subSumA(N);\n    int timer;\n\n    auto rebuild = [&](){\n        for(int i = 0; i < N; i++) children[i].clear();\n        for(int v = 0; v < N; v++){\n            int p = bestParent[v];\n            if(p >= 0) children[p].push_back(v);\n        }\n        fill(rootOf.begin(), rootOf.end(), -1);\n        deque<int> dq;\n        for(int v = 0; v < N; v++){\n            if(bestParent[v] < 0){\n                rootOf[v] = v;\n                dq.push_back(v);\n                while(!dq.empty()){\n                    int u = dq.front(); dq.pop_front();\n                    for(int c: children[u]){\n                        rootOf[c] = rootOf[v];\n                        dq.push_back(c);\n                    }\n                }\n            }\n        }\n    };\n\n    function<void(int)> dfsSub = [&](int v){\n        tin[v] = timer++;\n        subSize[v]   = 1;\n        subSumA[v]   = A[v];\n        subMaxD[v]   = 0;\n        for(int c: children[v]){\n            dfsSub(c);\n            subSize[v]   += subSize[c];\n            subSumA[v]   += subSumA[c];\n            subMaxD[v]   = max(subMaxD[v], subMaxD[c] + 1);\n        }\n        tout[v] = timer;\n    };\n\n    for(int pass = 0; pass < 2; pass++){\n        while(true){\n            rebuild();\n            timer = 0;\n            for(int v = 0; v < N; v++){\n                if(bestParent[v] < 0) dfsSub(v);\n            }\n            ll bestGain = 0;\n            int  bestV = -1, bestU = -1, oldP = -1;\n\n            // try detaching **any** subtree of size \u2264 MAX_SUB\n            for(int v = 0; v < N; v++){\n                int p = bestParent[v];\n                if(p < 0) continue;\n                int sz = subSize[v];\n                if(sz > MAX_SUB) continue;\n                ll sm = subSumA[v];\n                int dv = bestDepth[v];\n                int md = subMaxD[v];\n                for(int u: adj[v]){\n                    // forbid cycles\n                    if(tin[u] >= tin[v] && tin[u] < tout[v]) continue;\n                    int du = bestDepth[u];\n                    if(du + 1 + md > H) continue;\n                    ll gain = ll(du - dv + 1) * sm;\n                    if(gain > bestGain){\n                        bestGain = gain;\n                        bestV     = v;\n                        bestU     = u;\n                        oldP      = p;\n                    }\n                }\n            }\n            if(bestGain <= 0) break;\n\n            // apply the best subtree\u2010move\n            auto &sib = children[oldP];\n            for(int i = 0; i < (int)sib.size(); i++){\n                if(sib[i] == bestV){\n                    sib[i] = sib.back();\n                    sib.pop_back();\n                    break;\n                }\n            }\n            children[bestU].push_back(bestV);\n            bestParent[bestV] = bestU;\n\n            // fix depths & rootOf in that moved subtree\n            deque<int> dq2;\n            bestDepth[bestV] = bestDepth[bestU] + 1;\n            rootOf[bestV]    = rootOf[bestU];\n            dq2.push_back(bestV);\n            while(!dq2.empty()){\n                int x = dq2.front(); dq2.pop_front();\n                for(int c: children[x]){\n                    bestDepth[c] = bestDepth[x] + 1;\n                    rootOf[c]    = rootOf[bestV];\n                    dq2.push_back(c);\n                }\n            }\n        }\n    }\n\n    // ------------------------------------------------\n    // 4) Output\n    // ------------------------------------------------\n    for(int v = 0; v < N; v++){\n        cout << bestParent[v] << (v+1 == N ? '\\n' : ' ');\n    }\n    return 0;\n}","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\nusing ull = unsigned long long;\n\n// map directions to 0..3 and back\ninline int dirc(char d){ return (d=='L'?0:(d=='R'?1:(d=='U'?2:3))); }\ninline char codir(int c){ return (c==0?'L': c==1?'R': c==2?'U':'D'); }\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    const int N = 20;\n    int n;\n    cin >> n;             // always 20\n    vector<string> B(N);\n    for(int i=0;i<N;i++) cin >> B[i];\n\n    // 1) Collect Oni positions\n    vector<pair<int,int>> oni;\n    oni.reserve(2*N);\n    vector<vector<int>> pos2id(N, vector<int>(N, -1));\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            if(B[i][j]=='x'){\n                int id = oni.size();\n                oni.emplace_back(i,j);\n                pos2id[i][j] = id;\n            }\n        }\n    }\n    int M = oni.size();   // =40\n\n    // 2) Nearest Fukunokami per row/col\n    const int INF = 1<<20;\n    vector<int> rmin(N,INF), rmax(N,-INF), cmin(N,INF), cmax(N,-INF);\n    for(int i=0;i<N;i++){\n        for(int j=0;j<N;j++){\n            if(B[i][j]=='o'){\n                rmin[i] = min(rmin[i], j);\n                rmax[i] = max(rmax[i], j);\n                cmin[j] = min(cmin[j], i);\n                cmax[j] = max(cmax[j], i);\n            }\n        }\n    }\n\n    // 3) Build exactly one *minimal* segment per Oni per clear direction\n    struct Seg { char d; int idx,k,cost; vector<int> cover; };\n    vector<Seg> segs;\n    segs.reserve(4*M);\n    // flat lookup: key in [0..4*N*(N+1))\n    int Ksz = 4*N*(N+1);\n    vector<int> segIndex(Ksz, -1);\n\n    auto add_seg = [&](char d,int idx,int k){\n        int dc = dirc(d);\n        int key = ((dc*N + idx)*(N+1)) + k;\n        if(segIndex[key] < 0){\n            segIndex[key] = segs.size();\n            segs.push_back({d, idx, k, 2*k, {}});\n        }\n    };\n\n    for(int id=0; id<M; id++){\n        auto [i,j] = oni[id];\n        if(rmin[i] > j) add_seg('L', i, j+1);\n        if(rmax[i] < j) add_seg('R', i, N-j);\n        if(cmin[j] > i) add_seg('U', j, i+1);\n        if(cmax[j] < i) add_seg('D', j, N-i);\n    }\n\n    int S = segs.size();\n    vector<ull> segMask(S,0);\n    // 4) Build cover-lists + 64-bit masks\n    for(int s=0; s<S; s++){\n        auto &sg = segs[s];\n        int K = sg.k, idx = sg.idx;\n        if(sg.d=='L'){\n            for(int x=0; x<K; x++){\n                int id = pos2id[idx][x];\n                if(id>=0){ sg.cover.push_back(id); segMask[s] |= (1ULL<<id); }\n            }\n        } else if(sg.d=='R'){\n            for(int x=N-K; x<N; x++){\n                int id = pos2id[idx][x];\n                if(id>=0){ sg.cover.push_back(id); segMask[s] |= (1ULL<<id); }\n            }\n        } else if(sg.d=='U'){\n            for(int x=0; x<K; x++){\n                int id = pos2id[x][idx];\n                if(id>=0){ sg.cover.push_back(id); segMask[s] |= (1ULL<<id); }\n            }\n        } else { // 'D'\n            for(int x=N-K; x<N; x++){\n                int id = pos2id[x][idx];\n                if(id>=0){ sg.cover.push_back(id); segMask[s] |= (1ULL<<id); }\n            }\n        }\n    }\n\n    // 5) Precompute alt-costs & Oni-rarity\n    vector<double> cost2(S), cost03(S), rare(S,0.0);\n    vector<int> freq(M,0);\n    for(int s=0;s<S;s++){\n        cost2[s]  = sqrt((double)segs[s].cost);\n        cost03[s] = pow((double)segs[s].cost,0.3);\n        for(int id: segs[s].cover) freq[id]++;\n    }\n    for(int s=0;s<S;s++){\n        double w=0;\n        for(int id: segs[s].cover) w += 1.0/freq[id];\n        rare[s] = w;\n    }\n\n    // 6) Build candidate lists for shrinking (ascending k)\n    vector<vector<pair<int,ull>>> cand(4*N);\n    for(int s=0;s<S;s++){\n        int key = dirc(segs[s].d)*N + segs[s].idx;\n        cand[key].emplace_back(segs[s].k, segMask[s]);\n    }\n    for(int key=0;key<4*N;key++){\n        auto &v = cand[key];\n        sort(v.begin(), v.end(),\n             [&](auto &a, auto &b){ return a.first < b.first; });\n    }\n\n    // 7) Time-based greedy + prune + merge loop\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    vector<char> used(S);\n    vector<int> cov_cnt(M);\n    vector<double> randf(S);\n\n    vector<int> bestk(4*N,0);\n    int bestCost = INT_MAX;\n\n    auto T0 = chrono::steady_clock::now();\n    const double TL = 1.95;        // overall time limit\n    const double T1 = TL * 0.6;    // spend ~60% on restarts\n\n    int rep = 0;\n    while(true){\n        rep++;\n        if((rep & 127)==0){\n            double t = chrono::duration<double>(chrono::steady_clock::now() - T0).count();\n            if(t > T1) break;\n        }\n\n        // randomize\n        double rareW = (rng()%501)/1000.0; // [0..0.5]\n        for(int s=0;s<S;s++){\n            int r = int(rng()%1001);\n            randf[s] = 1.0 + (r-500)/5000.0;\n        }\n        int mode = int(rng()%3);\n\n        // greedy cover\n        fill(used.begin(), used.end(), 0);\n        ull covered = 0;\n        vector<int> pick;\n        pick.reserve(M);\n\n        while(__builtin_popcountll(covered) < M){\n            double bestR=-1.0; int bestS=-1;\n            ull need = ~covered;\n            for(int s=0;s<S;s++){\n                if(used[s]) continue;\n                ull m = segMask[s] & need;\n                int nc = __builtin_popcountll(m);\n                if(nc==0) continue;\n                double denom = (mode==0 ? segs[s].cost\n                                : mode==1 ? cost2[s]\n                                          : cost03[s]);\n                double sc = (nc + rareW*rare[s]) * randf[s] / denom;\n                if(sc > bestR){\n                    bestR = sc; bestS = s;\n                }\n            }\n            if(bestS < 0) break;\n            used[bestS]=1;\n            covered |= segMask[bestS];\n            pick.push_back(bestS);\n        }\n        if(__builtin_popcountll(covered) < M) \n            continue;\n\n        // prune fully-redundant\n        fill(cov_cnt.begin(), cov_cnt.end(), 0);\n        for(int s: pick) for(int id: segs[s].cover) cov_cnt[id]++;\n        vector<int> pr;\n        pr.reserve(pick.size());\n        for(int s: pick){\n            bool red = true;\n            for(int id: segs[s].cover){\n                if(cov_cnt[id] <= 1){ red=false; break; }\n            }\n            if(red){\n                for(int id: segs[s].cover) cov_cnt[id]--;\n            } else {\n                pr.push_back(s);\n            }\n        }\n\n        // merge \u2192 one\u2010per\u2010(dir,idx)\n        vector<int> curk(4*N,0);\n        int cost=0;\n        for(int s: pr){\n            int key = dirc(segs[s].d)*N + segs[s].idx;\n            curk[key] = max(curk[key], segs[s].k);\n        }\n        for(int key=0;key<4*N;key++){\n            if(curk[key]>0) cost += 2*curk[key];\n        }\n        if(cost < bestCost){\n            bestCost = cost;\n            bestk     = curk;\n        }\n    }\n\n    // 8) Initial shrink of bestk[]\n    {\n        bool ch=true;\n        while(ch){\n            ch=false;\n            for(int key=0;key<4*N;key++){\n                int oldk = bestk[key];\n                if(oldk<=0) continue;\n                // coverage excluding this\n                ull covEx=0;\n                for(int k2=0;k2<4*N;k2++){\n                    int kk=bestk[k2];\n                    if(kk>0 && k2!=key){\n                        int mp = k2*(N+1)+kk;\n                        covEx |= segMask[ segIndex[mp] ];\n                    }\n                }\n                // try smaller k\n                for(auto &pr: cand[key]){\n                    int kk=pr.first;\n                    if(kk>=oldk) continue;\n                    if(__builtin_popcountll(covEx | pr.second)==M){\n                        bestk[key]=kk; ch=true; break;\n                    }\n                }\n                if(ch) break;\n            }\n        }\n        // recalc cost\n        bestCost=0;\n        for(int key=0;key<4*N;key++){\n            if(bestk[key]>0) bestCost += 2*bestk[key];\n        }\n    }\n\n    // 9) INC-k local search until TL\n    const int LS = 1500;\n    for(int it=0; it<LS; it++){\n        double t = chrono::duration<double>(chrono::steady_clock::now() - T0).count();\n        if(t > TL) break;\n\n        // gather growable dirs\n        vector<int> grow;\n        grow.reserve(4*N);\n        for(int key=0;key<4*N;key++){\n            int ok = bestk[key];\n            if(ok<=0) continue;\n            auto &v = cand[key];\n            if(v.back().first > ok) grow.push_back(key);\n        }\n        if(grow.empty()) break;\n\n        int a = grow[rng()%grow.size()];\n        int oldk = bestk[a];\n        // pick larger k\n        vector<int> bigger;\n        for(auto &pr: cand[a]) if(pr.first>oldk) bigger.push_back(pr.first);\n        if(bigger.empty()) continue;\n        int newka = bigger[rng()%bigger.size()];\n\n        // propose\n        vector<int> nk = bestk;\n        nk[a] = newka;\n\n        // find largest\u2010save segment now redundant\n        int dropKey=-1, dropSave=0;\n        for(int key=0; key<4*N; key++){\n            int kk = nk[key];\n            if(kk<=0) continue;\n            ull covEx=0;\n            for(int k2=0;k2<4*N;k2++){\n                int kk2=nk[k2];\n                if(kk2>0 && k2!=key){\n                    int mp2 = k2*(N+1)+kk2;\n                    covEx |= segMask[ segIndex[mp2] ];\n                }\n            }\n            if(__builtin_popcountll(covEx)==M){\n                int save = 2*kk;\n                if(save > dropSave){\n                    dropSave=save; dropKey=key;\n                }\n            }\n        }\n        if(dropKey<0) continue;\n        nk[dropKey] = 0;\n\n        // shrink nk\n        bool ch=true;\n        while(ch){\n            ch=false;\n            for(int key=0;key<4*N;key++){\n                int ok = nk[key];\n                if(ok<=0) continue;\n                ull covEx=0;\n                for(int k2=0;k2<4*N;k2++){\n                    int kk2 = nk[k2];\n                    if(kk2>0 && k2!=key){\n                        int mp2 = k2*(N+1)+kk2;\n                        covEx |= segMask[ segIndex[mp2] ];\n                    }\n                }\n                for(auto &pr: cand[key]){\n                    int kk=pr.first;\n                    if(kk>=ok) continue;\n                    if(__builtin_popcountll(covEx | pr.second)==M){\n                        nk[key] = kk; ch=true; break;\n                    }\n                }\n                if(ch) break;\n            }\n        }\n\n        int ncost=0;\n        for(int key=0;key<4*N;key++){\n            if(nk[key]>0) ncost += 2*nk[key];\n        }\n        if(ncost < bestCost){\n            bestCost = ncost;\n            bestk = move(nk);\n        }\n    }\n\n    // 10) Emit moves\n    auto opp = [&](char d){\n        if(d=='L') return 'R';\n        if(d=='R') return 'L';\n        if(d=='U') return 'D';\n        return 'U';\n    };\n    vector<pair<char,int>> ops;\n    ops.reserve(bestCost);\n    for(int key=0; key<4*N; key++){\n        int k = bestk[key];\n        if(k>0){\n            char d = codir(key/N), od = opp(d);\n            int idx = key%N;\n            for(int i=0;i<k;i++) ops.emplace_back(d, idx);\n            for(int i=0;i<k;i++) ops.emplace_back(od, idx);\n        }\n    }\n    for(auto &p: ops){\n        cout << p.first << \" \" << p.second << \"\\n\";\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\n\nstatic constexpr int N = 100;\nstatic constexpr long long L = 500000;\nstatic constexpr double TIME_LIMIT = 1.90;\n\n// power\u2010iteration step counts\nstatic constexpr int PI_BASE    = 400;  // for baselines\nstatic constexpr int PI_WARM    = 30;   // per\u2010candidate estimate\nstatic constexpr int PI_REFRESH = 80;   // after accepting\n\n// local\u2010search parameters\nstatic constexpr int LOCAL_M     = 10;    // scan top\u2010M over/under\nstatic constexpr double EPS_GAIN = 1e-8;\n\nint a[N], b_curr[N], best_b[N];\ndouble uniform_pi[N], pi_curr[N], cand_pi[N], best_cand_pi[N], tmp_pi[N];\n\n// Compute `steps` iterations of \u03c0 \u2190 0.5\u00b7P\u00b7\u03c0, starting from `init[]` into `out[]`.\n// Uses global a[] and b_curr[] as the 2-out adjacency.\nvoid power_iterate(int steps, const double init[], double out[]){\n    memcpy(out, init, sizeof(double)*N);\n    while(steps--){\n        memset(tmp_pi, 0, sizeof(tmp_pi));\n        for(int i = 0; i < N; i++){\n            double h = out[i] * 0.5;\n            tmp_pi[a[i]]      += h;\n            tmp_pi[b_curr[i]] += h;\n        }\n        memcpy(out, tmp_pi, sizeof(tmp_pi));\n    }\n}\n\n// L\u2081\u2010error of `arr[]` vs targets T\ndouble compute_err_arr(const double arr[], const vector<long long>& T){\n    double E = 0;\n    for(int i = 0; i < N; i++){\n        E += fabs(arr[i]*L - T[i]);\n    }\n    return E;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n; long long Lin;\n    cin >> n >> Lin;\n    vector<long long> T(n);\n    for(int i = 0; i < n; i++) cin >> T[i];\n\n    // 1) build the required big\u2010cycle in a[]\n    for(int i = 0; i < N; i++){\n        a[i] = (i + 1) % N;\n    }\n\n    // prepare the uniform start\u2010vector\n    double invN = 1.0 / N;\n    for(int i = 0; i < N; i++){\n        uniform_pi[i] = invN;\n    }\n\n    double best_err = 1e300;\n\n    // 2) uniform\u2010cycle baseline\n    for(int i = 0; i < N; i++){\n        b_curr[i] = a[i];\n    }\n    power_iterate(PI_BASE, uniform_pi, pi_curr);\n    best_err = compute_err_arr(pi_curr, T);\n    memcpy(best_b, b_curr, sizeof(b_curr));\n\n    // 3) sort for hot\u2010/cold\u2010group cycles\n    vector<pair<long long,int>> ord_desc(N), ord_asc(N);\n    for(int i = 0; i < N; i++){\n        ord_desc[i] = {T[i], i};\n        ord_asc [i] = {T[i], i};\n    }\n    sort(ord_desc.begin(), ord_desc.end(), greater<>());\n    sort(ord_asc .begin(), ord_asc .end());\n\n    // 4) hot\u2010group and cold\u2010group k\u2010cycles\n    for(int pass = 0; pass < 2; pass++){\n        auto &ord = (pass == 0 ? ord_desc : ord_asc);\n        for(int k = 1; k < N; k++){\n            // reset b_curr to the big\u2010cycle\n            for(int i = 0; i < N; i++){\n                b_curr[i] = a[i];\n            }\n            // link the chosen k\u2010group into a k\u2010cycle\n            for(int j = 0; j < k; j++){\n                int u = ord[j].second;\n                int v = ord[(j+1)%k].second;\n                b_curr[u] = v;\n            }\n            power_iterate(PI_BASE, uniform_pi, pi_curr);\n            double e = compute_err_arr(pi_curr, T);\n            if(e < best_err){\n                best_err = e;\n                memcpy(best_b, b_curr, sizeof(b_curr));\n            }\n        }\n    }\n\n    // 5) self\u2010loop baseline (top\u2010A and bottom\u2010A)\n    static int rank_desc[N], rank_asc[N];\n    for(int i = 0; i < N; i++){\n        rank_desc[ ord_desc[i].second ] = i;\n        rank_asc [ ord_asc [i].second ] = i;\n    }\n    for(int dir = 0; dir < 2; dir++){\n        int *rankp = (dir == 0 ? rank_desc : rank_asc);\n        // pick best A by closed\u2010form approximation\n        int bestA = 0;\n        double approx_err = 1e300;\n        for(int A = 0; A <= N; A++){\n            double denom = double(N + A);\n            double err = 0;\n            for(int i = 0; i < N; i++){\n                double alpha = (rankp[i] < A ? 1.0 : 0.0);\n                double pred  = double(L) * (1.0 + alpha) / denom;\n                err += fabs(pred - double(T[i]));\n            }\n            if(err < approx_err){\n                approx_err = err;\n                bestA = A;\n            }\n        }\n        // build & test that self\u2010loop map\n        for(int i = 0; i < N; i++){\n            b_curr[i] = (rankp[i] < bestA ? i : a[i]);\n        }\n        power_iterate(PI_BASE, uniform_pi, pi_curr);\n        double e = compute_err_arr(pi_curr, T);\n        if(e < best_err){\n            best_err = e;\n            memcpy(best_b, b_curr, sizeof(b_curr));\n        }\n    }\n\n    // 6) local\u2010search polish on b_curr[] using the full remaining time\n    //    warm\u2010start refresh from the best candidate estimate\n    //    (we recorded best_err and will update best_b[])\n    auto t_start = chrono::steady_clock::now();\n    memcpy(b_curr, best_b, sizeof(b_curr));\n    power_iterate(PI_BASE, uniform_pi, pi_curr);\n    double curr_err = compute_err_arr(pi_curr, T);\n\n    for(int iter = 0; iter < 100000; iter++){\n        // time\u2010check\n        auto t_now = chrono::steady_clock::now();\n        if(chrono::duration<double>(t_now - t_start).count() > TIME_LIMIT) break;\n\n        // gather over/under\u2013visited nodes\n        vector<pair<double,int>> over, under;\n        over.reserve(N); under.reserve(N);\n        for(int i = 0; i < N; i++){\n            double d = pi_curr[i]*L - T[i];\n            if(d >  1e-9) over.emplace_back(d,i);\n            if(d < -1e-9) under.emplace_back(d,i);\n        }\n        if(over.empty() || under.empty()) break;\n        sort(over.begin(), over.end(), greater<>());\n        sort(under.begin(), under.end());\n\n        int mo = min((int)over.size(), LOCAL_M);\n        int mu = min((int)under.size(), LOCAL_M);\n\n        double best_gain = EPS_GAIN;\n        int best_x = -1, best_y = -1;\n\n        // scan top\u2010M \u00d7 top\u2010M rewires\n        for(int xi = 0; xi < mo; xi++){\n            int x = over[xi].second;\n            int saved = b_curr[x];\n            for(int yi = 0; yi < mu; yi++){\n                int y = under[yi].second;\n                if(y == saved) continue;\n                b_curr[x] = y;\n                // warm\u2010start estimate from pi_curr\n                power_iterate(PI_WARM, pi_curr, cand_pi);\n                double e2 = compute_err_arr(cand_pi, T);\n                double gain = curr_err - e2;\n                if(gain > best_gain){\n                    best_gain = gain;\n                    best_x = x;\n                    best_y = y;\n                    // save this best candidate \u03c0\n                    memcpy(best_cand_pi, cand_pi, sizeof(cand_pi));\n                }\n            }\n            b_curr[x] = saved;\n        }\n\n        if(best_x < 0) break;  // no further improvement\n\n        // accept the best local move\n        b_curr[best_x] = best_y;\n        // warm\u2010start refresh from our best\u2010cand \u03c0\n        power_iterate(PI_REFRESH, best_cand_pi, pi_curr);\n        curr_err = compute_err_arr(pi_curr, T);\n\n        // record if overall best\n        if(curr_err < best_err){\n            best_err = curr_err;\n            memcpy(best_b, b_curr, sizeof(b_curr));\n        }\n    }\n\n    // 7) output the best mapping we found\n    for(int i = 0; i < N; i++){\n        cout << a[i] << \" \" << best_b[i] << \"\\n\";\n    }\n    return 0;\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n// Hilbert\u2010curve mapping of (x,y) in [0,2^bits)\n// into a 2*bits\u2010bit key.  Improves spatial locality.\nstatic inline uint64_t hilbertOrder(int x, int y, int bits = 14) {\n    uint64_t d = 0;\n    for(int s = bits - 1; s >= 0; s--) {\n        uint64_t rx = (x >> s) & 1;\n        uint64_t ry = (y >> s) & 1;\n        d = (d << 2) | ((rx << 1) | (rx ^ ry));\n        if(ry == 0) {\n            if(rx == 1) {\n                x = ((1<<bits) - 1) ^ x;\n                y = ((1<<bits) - 1) ^ y;\n            }\n            std::swap(x, y);\n        }\n    }\n    return d;\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N, M, Q, L, W;\n    cin >> N >> M >> Q >> L >> W;\n    vector<int> G(M);\n    for(int i = 0; i < M; i++) cin >> G[i];\n    vector<int> lx(N), rx(N), ly(N), ry(N);\n    for(int i = 0; i < N; i++){\n        cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    }\n\n    // 1) Compute centers (integers in [0..10000]) for ordering\n    vector<int> cx(N), cy(N);\n    for(int i = 0; i < N; i++){\n        cx[i] = (lx[i] + rx[i]) >> 1;\n        cy[i] = (ly[i] + ry[i]) >> 1;\n    }\n\n    // 2) Sort all cities by their Hilbert\u2010curve key\n    vector<int> idx(N);\n    iota(idx.begin(), idx.end(), 0);\n    vector<uint64_t> key(N);\n    for(int i = 0; i < N; i++){\n        key[i] = hilbertOrder(cx[i], cy[i], 14);\n    }\n    sort(idx.begin(), idx.end(), [&](int a, int b){\n        return key[a] < key[b];\n    });\n\n    // 3) Slice into the prescribed group\u2010sizes G[0],G[1],...\n    vector<vector<int>> groups(M);\n    {\n        int p = 0;\n        for(int k = 0; k < M; k++){\n            groups[k].reserve(G[k]);\n            for(int t = 0; t < G[k]; t++){\n                groups[k].push_back(idx[p++]);\n            }\n        }\n    }\n\n    // Collect the final edges here:\n    vector<vector<pair<int,int>>> answer_edges(M);\n    int remQ = Q;\n\n    // A simple Prim fallback in case we ever run out of queries.\n    auto prim_on_centers = [&](int k){\n        auto &g = groups[k];\n        int K = (int)g.size();\n        if(K <= 1) return;\n        vector<bool> in_mst(K,false);\n        vector<double> dist(K,1e18);\n        vector<int> par(K,-1);\n        dist[0] = 0;\n        for(int it=0; it<K; it++){\n            int u=-1; double best=1e18;\n            for(int i=0;i<K;i++){\n                if(!in_mst[i] && dist[i]<best){\n                    best=dist[i]; u=i;\n                }\n            }\n            in_mst[u]=true;\n            if(par[u]!=-1){\n                answer_edges[k].emplace_back(g[u], g[par[u]]);\n            }\n            for(int v=0;v<K;v++){\n                if(in_mst[v]) continue;\n                double dx = cx[g[u]] - cx[g[v]];\n                double dy = cy[g[u]] - cy[g[v]];\n                double d = floor(sqrt(dx*dx + dy*dy));\n                if(d < dist[v]){\n                    dist[v]=d;\n                    par[v]=u;\n                }\n            }\n        }\n    };\n\n    // 4) For each group, either query windows or fallback\n    for(int k = 0; k < M; k++){\n        auto &g = groups[k];\n        int K = (int)g.size();\n        if(K <= 1) continue;\n\n        // how many queries we need\n        int need = (K <= L\n                    ? 1\n                    : ( (K + L - 3) / (L - 1) )  // ceil((K-1)/(L-1)) = (K+L-3)/(L-1)\n                   );\n        if(remQ >= need){\n            int step = L - 1;\n            // issue exactly 'need' windows\n            for(int j = 0; j < need; j++){\n                int start = j * step;\n                int end = min(start + L, K);\n                int sz = end - start;  // guaranteed >= 2\n                cout << \"? \" << sz;\n                for(int t = start; t < end; t++){\n                    cout << ' ' << g[t];\n                }\n                cout << \"\\n\" << flush;\n                remQ--;\n\n                // read sz-1 edges\n                for(int e = 0; e < sz - 1; e++){\n                    int a, b;\n                    cin >> a >> b;\n                    answer_edges[k].emplace_back(a, b);\n                }\n            }\n        } else {\n            // fallback to approximate MST\n            prim_on_centers(k);\n        }\n    }\n\n    // 5) Output the final solution\n    cout << \"!\\n\";\n    for(int k = 0; k < M; k++){\n        // cities in group k\n        for(int i = 0; i < (int)groups[k].size(); i++){\n            if(i) cout << ' ';\n            cout << groups[k][i];\n        }\n        cout << \"\\n\";\n        // the (G[k] - 1) edges\n        for(auto &e : answer_edges[k]){\n            cout << e.first << \" \" << e.second << \"\\n\";\n        }\n    }\n    cout << flush;\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    cin >> N >> M;\n    vector<pair<int,int>> pts(M);\n    for(int i = 0; i < M; i++){\n        cin >> pts[i].first >> pts[i].second;\n    }\n    int ci = pts[0].first, cj = pts[0].second;\n    vector<pair<char,char>> ans;\n    const int INF = 1e9;\n\n    for(int k = 1; k < M; k++){\n        int ti = pts[k].first;\n        int tj = pts[k].second;\n        int di = ti - ci;\n        int dj = tj - cj;\n        int costVM = abs(di);\n        int costHM = abs(dj);\n        int costVS = INF, costHS = INF;\n\n        // cost of sliding vertically via boundary then back\n        if(di > 0){\n            // slide down to row N-1, then move up to ti\n            costVS = 1 + ((N-1) - ti);\n        } else if(di < 0){\n            // slide up to row 0, then move down to ti\n            costVS = 1 + ti;\n        }\n        // cost of sliding horizontally via boundary then back\n        if(dj > 0){\n            // slide right to col N-1, then move left to tj\n            costHS = 1 + ((N-1) - tj);\n        } else if(dj < 0){\n            // slide left to col 0, then move right to tj\n            costHS = 1 + tj;\n        }\n\n        bool useV = costVS < costVM;\n        bool useH = costHS < costHM;\n\n        // First do horizontal phase\n        if(useH){\n            if(dj > 0){\n                ans.emplace_back('S','R');\n                int moves = (N-1) - tj;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','L');\n                }\n            } else {\n                // dj<0\n                ans.emplace_back('S','L');\n                int moves = tj;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','R');\n                }\n            }\n            cj = tj;\n        } else {\n            // simple moves\n            if(dj > 0){\n                for(int t = 0; t < dj; t++){\n                    ans.emplace_back('M','R');\n                }\n            } else if(dj < 0){\n                for(int t = 0; t < -dj; t++){\n                    ans.emplace_back('M','L');\n                }\n            }\n            cj = tj;\n        }\n\n        // Then do vertical phase\n        if(useV){\n            if(di > 0){\n                ans.emplace_back('S','D');\n                int moves = (N-1) - ti;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','U');\n                }\n            } else {\n                // di<0\n                ans.emplace_back('S','U');\n                int moves = ti;\n                for(int t = 0; t < moves; t++){\n                    ans.emplace_back('M','D');\n                }\n            }\n            ci = ti;\n        } else {\n            // simple moves\n            if(di > 0){\n                for(int t = 0; t < di; t++){\n                    ans.emplace_back('M','D');\n                }\n            } else if(di < 0){\n                for(int t = 0; t < -di; t++){\n                    ans.emplace_back('M','U');\n                }\n            }\n            ci = ti;\n        }\n    }\n\n    // Output all actions\n    for(auto &ac : ans){\n        cout << ac.first << \" \" << ac.second << \"\\n\";\n    }\n    return 0;\n}"}}}