{"model_name":"grok-4.1-fast","codes":{"1":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing A4 = array<int, 4>;\n\nbool overlaps(const vector<A4>& occ, int a, int b, int c, int d) {\n  for (const auto& p : occ) {\n    if (a < p[2] && c > p[0] && b < p[3] && d > p[1]) return true;\n  }\n  return false;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n;\n  cin >> n;\n  vector<int> X(n), Y(n), R(n);\n  for (int i = 0; i < n; i++) {\n    cin >> X[i] >> Y[i] >> R[i];\n  }\n  vector<int> order(n);\n  iota(order.begin(), order.end(), 0);\n  sort(order.begin(), order.end(), [&](int i, int j) {\n    if (R[i] != R[j]) return R[i] > R[j];\n    return X[i] < X[j];\n  });\n  vector<A4> occupied;\n  vector<A4> solution(n);\n  for (int kk = 0; kk < n; kk++) {\n    int i = order[kk];\n    int xi = X[i], yi = Y[i], ri = R[i];\n    int aa = xi, bb = yi, cc = xi + 1, dd = yi + 1;\n    bool min_free = !overlaps(occupied, aa, bb, cc, dd);\n    if (!min_free) {\n      // conflicted, find dummy 1x1\n      bool found = false;\n      vector<pair<int, int>> dirs = {\n          {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};\n      for (auto [dx, dy] : dirs) {\n        int px = xi + dx, py = yi + dy;\n        if (px < 0 || px > 9999 || py < 0 || py > 9999) continue;\n        if (!overlaps(occupied, px, py, px + 1, py + 1)) {\n          solution[i] = {px, py, px + 1, py + 1};\n          occupied.push_back(solution[i]);\n          found = true;\n          break;\n        }\n      }\n      if (!found) {\n        for (int k = 0; k < 100; k++) {\n          int px = (k / 10) * 100;\n          int py = (k % 10) * 100;\n          if (px > 9999 || py > 9999) continue;\n          if (!overlaps(occupied, px, py, px + 1, py + 1)) {\n            solution[i] = {px, py, px + 1, py + 1};\n            occupied.push_back(solution[i]);\n            found = true;\n            break;\n          }\n        }\n      }\n      if (!found) {\n        solution[i] = {0, 0, 1, 1};\n        // don't push to occupied to avoid further conflicts, but rare\n      }\n      continue;\n    }\n    // expand\n    int cura = xi, curc = xi + 1, curb = yi, curd = yi + 1;\n    const int MAX_ITER = 100;\n    for (int iter = 0; iter < MAX_ITER; iter++) {\n      // deltas\n      int d_left = 0;\n      {\n        int lo = 0, hi = cura;\n        while (lo < hi) {\n          int mid = (lo + hi + 1) / 2;\n          int na = cura - mid;\n          if (na >= 0 && !overlaps(occupied, na, curb, curc, curd)) {\n            lo = mid;\n          } else {\n            hi = mid - 1;\n          }\n        }\n        d_left = lo;\n      }\n      int d_right = 0;\n      {\n        int lo = 0, hi = 10000 - curc;\n        while (lo < hi) {\n          int mid = (lo + hi + 1) / 2;\n          int nc = curc + mid;\n          if (nc <= 10000 && !overlaps(occupied, cura, curb, nc, curd)) {\n            lo = mid;\n          } else {\n            hi = mid - 1;\n          }\n        }\n        d_right = lo;\n      }\n      int d_bot = 0;\n      {\n        int lo = 0, hi = curb;\n        while (lo < hi) {\n          int mid = (lo + hi + 1) / 2;\n          int nb = curb - mid;\n          if (nb >= 0 && !overlaps(occupied, cura, nb, curc, curd)) {\n            lo = mid;\n          } else {\n            hi = mid - 1;\n          }\n        }\n        d_bot = lo;\n      }\n      int d_top = 0;\n      {\n        int lo = 0, hi = 10000 - curd;\n        while (lo < hi) {\n          int mid = (lo + hi + 1) / 2;\n          int nt = curd + mid;\n          if (nt <= 10000 && !overlaps(occupied, cura, curb, curc, nt)) {\n            lo = mid;\n          } else {\n            hi = mid - 1;\n          }\n        }\n        d_top = lo;\n      }\n      // gains\n      ll h = curd - curb;\n      ll w = curc - cura;\n      ll gain_l = (ll)d_left * h;\n      ll gain_r = (ll)d_right * h;\n      ll gain_b = (ll)d_bot * w;\n      ll gain_t = (ll)d_top * w;\n      ll maxg = max({gain_l, gain_r, gain_b, gain_t});\n      if (maxg == 0) break;\n      // choose dir: prefer l > r > b > t\n      int chdir = -1;\n      if (gain_l == maxg) chdir = 0;\n      else if (gain_r == maxg) chdir = 1;\n      else if (gain_b == maxg) chdir = 2;\n      else if (gain_t == maxg) chdir = 3;\n      // extend\n      if (chdir == 0) cura -= d_left;\n      else if (chdir == 1) curc += d_right;\n      else if (chdir == 2) curb -= d_bot;\n      else curd += d_top;\n    }\n    // now max rect cura curc curb curd\n    int Wma = curc - cura;\n    int Hma = curd - curb;\n    // best sub\n    double bestp = -1.0;\n    int besw = 1, besh = 1;\n    ll rri = ri;\n    for (int ww = 1; ww <= Wma; ++ww) {\n      double hhd = (double)rri / ww;\n      int hh = (int)round(hhd);\n      vector<int> cand = {hh - 1, hh, hh + 1};\n      for (int hht : cand) {\n        hht = max(1, min(Hma, hht));\n        ll ss = (ll)ww * hht;\n        double ra = min(rri, ss) * 1.0 / max(rri, ss);\n        double pp = 2 * ra - ra * ra;\n        if (pp > bestp) {\n          bestp = pp;\n          besw = ww;\n          besh = hht;\n        }\n      }\n    }\n    // set subrect\n    int a2 = max(cura, xi + 1 - besw);\n    int c2 = a2 + besw;\n    int b2 = max(curb, yi + 1 - besh);\n    int d2 = b2 + besh;\n    solution[i] = {a2, b2, c2, d2};\n    occupied.push_back(solution[i]);\n  }\n  for (int i = 0; i < n; i++) {\n    auto& re = solution[i];\n    cout << re[0] << \" \" << re[1] << \" \" << re[2] << \" \" << re[3] << \"\\n\";\n  }\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int si, sj;\n  cin >> si >> sj;\n  vector<vector<int>> T(50, vector<int>(50));\n  int maxt = 0;\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) {\n      cin >> T[i][j];\n      maxt = max(maxt, T[i][j]);\n    }\n  int M = maxt + 1;\n  vector<vector<int>> P(50, vector<int>(50));\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) cin >> P[i][j];\n\n  int DX[4] = {-1, 0, 1, 0};\n  int DY[4] = {0, 1, 0, -1};\n  char DC[4] = {'U', 'D', 'L', 'R'};\n\n  string best_str = \"\";\n  long long best_sc = -1;\n  const int TRIALS = 128;\n  srand(time(NULL));\n\n  for (int trial = 0; trial < TRIALS; trial++) {\n    vector<char> vis(M, 0);\n    int st = T[si][sj];\n    vis[st] = 1;\n    long long score = P[si][sj];\n    int cr = si, cc = sj;\n    string moves = \"\";\n    while (true) {\n      vector<tuple<int, int, int, int>> cands;\n      for (int d = 0; d < 4; d++) {\n        int nr = cr + DX[d];\n        int nc = cc + DY[d];\n        if (nr < 0 || nr >= 50 || nc < 0 || nc >= 50) continue;\n        int nt = T[nr][nc];\n        if (vis[nt]) continue;\n        int deg = 0;\n        for (int dd = 0; dd < 4; dd++) {\n          int mr = nr + DX[dd];\n          int mc = nc + DY[dd];\n          if (mr >= 0 && mr < 50 && mc >= 0 && mc < 50 && !vis[T[mr][mc]]) deg++;\n        }\n        int pp = P[nr][nc];\n        int hashh = nr * 51 + nc;\n        cands.emplace_back(deg, -pp, d, hashh);\n      }\n      if (cands.empty()) break;\n      sort(cands.begin(), cands.end());\n      size_t ncand = cands.size();\n      int pick = rand() % min(4UL, ncand);\n      auto [fdeg, fp, fdir, fhash] = cands[pick];\n      int nr = cr + DX[fdir];\n      int nc = cc + DY[fdir];\n      moves += DC[fdir];\n      vis[T[nr][nc]] = 1;\n      score += P[nr][nc];\n      cr = nr;\n      cc = nc;\n    }\n    if (score > best_sc) {\n      best_sc = score;\n      best_str = moves;\n    }\n  }\n  cout << best_str << '\\n';\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  const int N = 30;\n  auto nodef = [&](int i, int j) -> int { return i * N + j; };\n  auto geti = [&](int u) -> int { return u / N; };\n  auto getj = [&](int u) -> int { return u % N; };\n  vector<vector<double>> h(N, vector<double>(N - 1, 1000.0));\n  vector<vector<double>> vv(N - 1, vector<double>(N, 1000.0));\n  for (int q = 0; q < 1000; ++q) {\n    int si, sj, ti, tj;\n    cin >> si >> sj >> ti >> tj;\n    int ss = nodef(si, sj);\n    int tt = nodef(ti, tj);\n    vector<double> dist(N * N, 1e18);\n    vector<int> prevv(N * N, -1);\n    dist[ss] = 0.0;\n    priority_queue<pair<double, int>, vector<pair<double, int>>, greater<pair<double, int>>> pq;\n    pq.push({0.0, ss});\n    while (!pq.empty()) {\n      auto [cost, u] = pq.top();\n      pq.pop();\n      if (cost > dist[u]) continue;\n      int i = geti(u), j = getj(u);\n      // right\n      if (j < N - 1) {\n        int v = nodef(i, j + 1);\n        double w = h[i][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // left\n      if (j > 0) {\n        int v = nodef(i, j - 1);\n        double w = h[i][j - 1];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // down\n      if (i < N - 1) {\n        int v = nodef(i + 1, j);\n        double w = vv[i][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // up\n      if (i > 0) {\n        int v = nodef(i - 1, j);\n        double w = vv[i - 1][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n    }\n    double predicted = dist[tt];\n    // reconstruct path for output\n    string path_str;\n    {\n      vector<int> path_nodes;\n      int cur = tt;\n      while (cur != ss) {\n        path_nodes.push_back(cur);\n        cur = prevv[cur];\n      }\n      path_nodes.push_back(ss);\n      reverse(path_nodes.begin(), path_nodes.end());\n      for (size_t k = 0; k + 1 < path_nodes.size(); ++k) {\n        int u = path_nodes[k], v = path_nodes[k + 1];\n        int ui = geti(u), uj = getj(u), vi = geti(v), vj = getj(v);\n        int di = vi - ui, dj = vj - uj;\n        char ch;\n        if (di == -1 && dj == 0) ch = 'U';\n        else if (di == 1 && dj == 0) ch = 'D';\n        else if (di == 0 && dj == -1) ch = 'L';\n        else if (di == 0 && dj == 1) ch = 'R';\n        else ch = '?'; // error, but shouldn't\n        path_str += ch;\n      }\n    }\n    cout << path_str << '\\n';\n    cout.flush();\n    int obs;\n    cin >> obs;\n    // reconstruct for update\n    vector<int> path_nodes;\n    int cur = tt;\n    while (cur != ss) {\n      path_nodes.push_back(cur);\n      cur = prevv[cur];\n    }\n    path_nodes.push_back(ss);\n    reverse(path_nodes.begin(), path_nodes.end());\n    int num_e = path_nodes.size() - 1;\n    double delta = (double)obs - predicted;\n    double avg_d = (num_e > 0 ? delta / num_e : 0.0);\n    for (int k = 0; k < num_e; ++k) {\n      int u = path_nodes[k], v = path_nodes[k + 1];\n      int ui = geti(u), uj = getj(u), vi = geti(v), vj = getj(v);\n      if (ui == vi) {  // horiz\n        int lj = min(uj, vj);\n        h[ui][lj] += avg_d;\n        h[ui][lj] = max(50.0, min(20000.0, h[ui][lj]));\n      } else {  // vert\n        int ti_ = min(ui, vi);\n        vv[ti_][uj] += avg_d;\n        vv[ti_][uj] = max(50.0, min(20000.0, vv[ti_][uj]));\n      }\n    }\n  }\n  return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N = 20;\nint M;\nstring SS[805];\nint Lens[805];\nchar grid[20][20];\nchar best_grid[20][20];\nchar chars[8] = {'A','B','C','D','E','F','G','H'};\n\nint get_covered(char g[20][20]) {\n  static char dblr[20][41];\n  static char dblc[20][41];\n  for (int r = 0; r < N; ++r) {\n    memcpy(dblr[r], g[r], N);\n    memcpy(dblr[r] + N, g[r], N);\n  }\n  for (int c = 0; c < N; ++c) {\n    for (int r = 0; r < N; ++r) dblc[c][r] = g[r][c];\n    memcpy(dblc[c] + N, dblc[c], N);\n  }\n  int cnt = 0;\n  for (int si = 0; si < M; ++si) {\n    int k = Lens[si];\n    const char* pat = SS[si].c_str();\n    bool ok = false;\n    // rows\n    for (int r = 0; r < N && !ok; ++r) {\n      const char* dbl = dblr[r];\n      for (int st = 0; st < N; ++st) {\n        bool match = true;\n        for (int p = 0; p < k; ++p) {\n          if (dbl[st + p] != pat[p]) {\n            match = false;\n            break;\n          }\n        }\n        if (match) {\n          ok = true;\n          break;\n        }\n      }\n    }\n    if (!ok) {\n      // cols\n      for (int c = 0; c < N && !ok; ++c) {\n        const char* dbl = dblc[c];\n        for (int st = 0; st < N; ++st) {\n          bool match = true;\n          for (int p = 0; p < k; ++p) {\n            if (dbl[st + p] != pat[p]) {\n              match = false;\n              break;\n            }\n          }\n          if (match) {\n            ok = true;\n            break;\n          }\n        }\n      }\n    }\n    if (ok) ++cnt;\n  }\n  return cnt;\n}\n\nvector<bool> get_covered_vec(char g[20][20]) {\n  static char dblr[20][41];\n  static char dblc[20][41];\n  for (int r = 0; r < N; ++r) {\n    memcpy(dblr[r], g[r], N);\n    memcpy(dblr[r] + N, g[r], N);\n  }\n  for (int c = 0; c < N; ++c) {\n    for (int r = 0; r < N; ++r) dblc[c][r] = g[r][c];\n    memcpy(dblc[c] + N, dblc[c], N);\n  }\n  vector<bool> cov(M, false);\n  for (int si = 0; si < M; ++si) {\n    int k = Lens[si];\n    const char* pat = SS[si].c_str();\n    bool ok = false;\n    // rows\n    for (int r = 0; r < N && !ok; ++r) {\n      const char* dbl = dblr[r];\n      for (int st = 0; st < N; ++st) {\n        bool match = true;\n        for (int p = 0; p < k; ++p) {\n          if (dbl[st + p] != pat[p]) {\n            match = false;\n            break;\n          }\n        }\n        if (match) {\n          ok = true;\n          break;\n        }\n      }\n    }\n    if (!ok) {\n      // cols\n      for (int c = 0; c < N && !ok; ++c) {\n        const char* dbl = dblc[c];\n        for (int st = 0; st < N; ++st) {\n          bool match = true;\n          for (int p = 0; p < k; ++p) {\n            if (dbl[st + p] != pat[p]) {\n              match = false;\n              break;\n            }\n          }\n          if (match) {\n            ok = true;\n            break;\n          }\n        }\n      }\n    }\n    cov[si] = ok;\n  }\n  return cov;\n}\n\nvoid do_sa() {\n  memcpy(best_grid, grid, sizeof(grid));\n  int best_c = get_covered(grid);\n  int curr_c = best_c;\n  double temp = 32.0;\n  double cool_rate = 0.9998;\n  int iters = 0;\n  const int max_iters = 2000000;\n  srand(time(NULL));\n  while (iters < max_iters && temp > 0.05 && curr_c < M) {\n    int ri = rand() % N;\n    int ci = rand() % N;\n    char old_ch = grid[ri][ci];\n    int ch_idx = rand() % 8;\n    char new_ch = chars[ch_idx];\n    if (new_ch == old_ch) continue;\n    grid[ri][ci] = new_ch;\n    int new_c = get_covered(grid);\n    double delta = new_c - curr_c;\n    bool accept = (delta > 0);\n    if (!accept && temp > 0) {\n      double prob = exp(delta / temp);\n      if (prob > ((double)rand() / RAND_MAX)) accept = true;\n    }\n    if (accept) {\n      curr_c = new_c;\n      if (curr_c > best_c) {\n        best_c = curr_c;\n        memcpy(best_grid, grid, sizeof(grid));\n      }\n    } else {\n      grid[ri][ci] = old_ch;\n    }\n    temp *= cool_rate;\n    ++iters;\n  }\n  // copy back best\n  memcpy(grid, best_grid, sizeof(grid));\n}\n\nint main() {\n  srand(42);\n  cin >> N >> M;\n  for (int i = 0; i < M; ++i) {\n    cin >> SS[i];\n    Lens[i] = SS[i].size();\n    fill(grid[i], grid[i] + N, '.');\n  }\n  // greedy passes\n  int passes = 0;\n  bool changed = true;\n  while (changed && passes++ < 20) {\n    changed = false;\n    auto cov = get_covered_vec(grid);\n    vector<int> unc;\n    for (int si = 0; si < M; ++si) {\n      if (!cov[si]) unc.push_back(si);\n    }\n    if (unc.empty()) break;\n    // sort unc by len desc\n    sort(unc.begin(), unc.end(), [](int a, int b) {\n      return Lens[a] > Lens[b];\n    });\n    for (int si : unc) {\n      const string& s = SS[si];\n      int k = Lens[si];\n      int best_cost = INT_MAX / 2;\n      int best_ndot = -1;\n      int best_dir = -1, best_fix = -1, best_st = -1;\n      for (int dir = 0; dir < 2; ++dir) {\n        for (int fix = 0; fix < N; ++fix) {\n          for (int st = 0; st < N; ++st) {\n            int cost = 0;\n            int ndot = 0;\n            for (int p = 0; p < k; ++p) {\n              int rr = dir ? (st + p) % N : fix;\n              int cc = dir ? fix : (st + p) % N;\n              char cur = grid[rr][cc];\n              if (cur != '.' && cur != s[p]) ++cost;\n              if (cur == '.') ++ndot;\n            }\n            if (cost < best_cost || (cost == best_cost && ndot > best_ndot)) {\n              best_cost = cost;\n              best_ndot = ndot;\n              best_dir = dir;\n              best_fix = fix;\n              best_st = st;\n            }\n          }\n        }\n      }\n      if (best_cost == 0) {\n        // place\n        int dir = best_dir, fix = best_fix, st = best_st;\n        for (int p = 0; p < k; ++p) {\n          int rr = dir ? (st + p) % N : fix;\n          int cc = dir ? fix : (st + p) % N;\n          grid[rr][cc] = s[p];\n        }\n        changed = true;\n      }\n    }\n  }\n  // fill dots safely\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      if (grid[i][j] == '.') grid[i][j] = 'A';\n    }\n  }\n  int final_c = get_covered(grid);\n  if (final_c < M) {\n    do_sa();\n  }\n  // output\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      cout << grid[i][j];\n    }\n    cout << '\\n';\n  }\n  return 0;\n}","ahc005":"","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, K, R;\n  cin >> N >> M >> K >> R;\n  vector<vector<int>> D(N + 1, vector<int>(K));\n  vector<double> avg_d(K, 0.0);\n  for (int i = 1; i <= N; ++i) {\n    for (int k = 0; k < K; ++k) {\n      cin >> D[i][k];\n      avg_d[k] += D[i][k];\n    }\n  }\n  for (int k = 0; k < K; ++k) {\n    avg_d[k] /= N;\n  }\n  vector<vector<int>> adj(N + 1);\n  vector<int> pending(N + 1, 0);\n  for (int r = 0; r < R; ++r) {\n    int u, v;\n    cin >> u >> v;\n    adj[u].push_back(v);\n    ++pending[v];\n  }\n  vector<vector<double>> est_s(M + 1, vector<double>(K, 0.0));\n  vector<vector<double>> sum_d(M + 1, vector<double>(K, 0.0));\n  vector<double> sum_w(M + 1, 0.0);\n  vector<int> obs_count(M + 1, 0);\n  for (int j = 1; j <= M; ++j) {\n    for (int k = 0; k < K; ++k) {\n      est_s[j][k] = avg_d[k] * 1.6;\n    }\n  }\n  vector<int> task_worker(N + 1, 0);\n  vector<int> task_start(N + 1, 0);\n  vector<bool> task_completed(N + 1, false);\n  vector<int> worker_task(M + 1, 0);\n  set<int> ready_set;\n  for (int i = 1; i <= N; ++i) {\n    if (pending[i] == 0) {\n      ready_set.insert(i);\n    }\n  }\n  int day = 0;\n  while (true) {\n    ++day;\n    vector<int> idles;\n    for (int j = 1; j <= M; ++j) {\n      if (worker_task[j] == 0) {\n        idles.push_back(j);\n      }\n    }\n    vector<int> readies(ready_set.begin(), ready_set.end());\n    size_t num_idle = idles.size();\n    size_t num_ready = readies.size();\n    size_t na = min(num_idle, num_ready);\n    if (na == 0) {\n      cout << 0 << '\\n';\n      cout.flush();\n    } else {\n      vector<tuple<double, int, int, int>> cands;\n      for (int i : readies) {\n        int nsucc = adj[i].size();\n        for (int j : idles) {\n          double w = 0.0;\n          for (int k = 0; k < K; ++k) {\n            w += max(0.0, (double)D[i][k] - est_s[j][k]);\n          }\n          double pt = (w <= 0.0 ? 1.0 : max(1.0, w));\n          cands.emplace_back(pt, -nsucc, i, j);\n        }\n      }\n      sort(cands.begin(), cands.end());\n      set<int> used_task, used_worker;\n      vector<pair<int, int>> assignment;\n      for (auto& cand : cands) {\n        double pt;\n        int neg_succ, ti, wj;\n        tie(pt, neg_succ, ti, wj) = cand;\n        if (used_task.count(ti) || used_worker.count(wj)) continue;\n        assignment.emplace_back(wj, ti);\n        used_task.insert(ti);\n        used_worker.insert(wj);\n        if (assignment.size() == na) break;\n      }\n      cout << assignment.size();\n      for (auto [a, b] : assignment) {\n        cout << ' ' << a << ' ' << b;\n        task_worker[b] = a;\n        task_start[b] = day;\n        worker_task[a] = b;\n      }\n      cout << '\\n';\n      cout.flush();\n      for (auto [a, b] : assignment) {\n        ready_set.erase(b);\n      }\n    }\n    int n;\n    cin >> n;\n    if (n == -1) {\n      return 0;\n    }\n    vector<int> finished_workers(n);\n    for (int i = 0; i < n; ++i) {\n      cin >> finished_workers[i];\n    }\n    for (int jj : finished_workers) {\n      int tsk = worker_task[jj];\n      if (tsk == 0) continue;\n      int t_obs = day - task_start[tsk] + 1;\n      double est_w_obs = (t_obs > 1 ? (double)t_obs : 0.0);\n      ++obs_count[jj];\n      sum_w[jj] += est_w_obs;\n      for (int k = 0; k < K; ++k) {\n        sum_d[jj][k] += D[tsk][k];\n      }\n      double p = obs_count[jj];\n      double avg_def_per_dim = sum_w[jj] / (p * K);\n      for (int k = 0; k < K; ++k) {\n        double avg_dk = sum_d[jj][k] / p;\n        est_s[jj][k] = avg_dk - avg_def_per_dim;\n        if (est_s[jj][k] < 0.0) est_s[jj][k] = 0.0;\n      }\n      task_completed[tsk] = true;\n      task_worker[tsk] = 0;\n      worker_task[jj] = 0;\n      for (int suc : adj[tsk]) {\n        --pending[suc];\n        if (pending[suc] == 0 && task_worker[suc] == 0 && !task_completed[suc]) {\n          ready_set.insert(suc);\n        }\n      }\n    }\n  }\n  return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int xx = 0, int yy = 0) : x(xx), y(yy) {}\n};\n\nint dist(Point a, Point b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\ndouble get_angle(const Point& pp) {\n    return atan2(pp.y - 400, pp.x - 400);\n}\n\nstruct Order {\n    Point p, d;\n    int id;\n    int len() const { return dist(p, d); }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    vector<Order> orders(1000);\n    Point O(400, 400);\n    for (int i = 0; i < 1000; i++) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        orders[i].p = {a, b};\n        orders[i].d = {c, d};\n        orders[i].id = i + 1;\n    }\n    const int N = 50;\n\n    // Forward greedy\n    vector<int> fsel;\n    bool fused[1000] = {};\n    Point fcurr = O;\n    for (int k = 0; k < N; k++) {\n        int best = -1;\n        int md = INT_MAX;\n        for (int u = 0; u < 1000; u++) {\n            if (fused[u]) continue;\n            int dd = dist(fcurr, orders[u].p);\n            if (dd < md || (dd == md && orders[u].len() < orders[best].len())) {\n                md = dd;\n                best = u;\n            }\n        }\n        fsel.push_back(best);\n        fused[best] = true;\n        fcurr = orders[best].d;\n    }\n\n    // Reverse greedy\n    vector<int> rsel;\n    bool rused[1000] = {};\n    Point rcurr = O;\n    for (int k = 0; k < N; k++) {\n        int best = -1;\n        int md = INT_MAX;\n        for (int u = 0; u < 1000; u++) {\n            if (rused[u]) continue;\n            int dd = dist(orders[u].d, rcurr);\n            if (dd < md || (dd == md && dist(orders[u].p, O) < dist(orders[best].p, O))) {\n                md = dd;\n                best = u;\n            }\n        }\n        rsel.push_back(best);\n        rused[best] = true;\n        rcurr = orders[best].p;\n    }\n    reverse(rsel.begin(), rsel.end());\n\n    // Compute full costs for both\n    auto compute_full = [&](const vector<int>& sel) -> pair<int, int> {\n        int suml = 0;\n        for (int oi : sel) suml += orders[oi].len();\n        int varc = dist(O, orders[sel[0]].p);\n        for (int i = 0; i < N - 1; i++) {\n            varc += dist(orders[sel[i]].d, orders[sel[i + 1]].p);\n        }\n        varc += dist(orders[sel.back()].d, O);\n        return {varc + suml, varc};\n    };\n\n    auto [ffull, fvar] = compute_full(fsel);\n    auto [rfull, rvar] = compute_full(rsel);\n\n    vector<int> sel = (ffull <= rfull ? fsel : rsel);\n    int initial_fixed_var = (ffull <= rfull ? fvar : rvar);\n\n    // Now build Ps, Ds, ids from sel\n    vector<Point> Ps(N), Ds(N);\n    vector<int> ids(N);\n    for (int i = 0; i < N; i++) {\n        int oi = sel[i];\n        Ps[i] = orders[oi].p;\n        Ds[i] = orders[oi].d;\n        ids[i] = orders[oi].id;\n    }\n\n    // get_var_cost\n    auto get_var_cost = [&](const vector<int>& perm) -> int {\n        if (perm.empty()) return 0;\n        int res = dist(O, Ps[perm[0]]);\n        for (size_t i = 0; i + 1 < perm.size(); ++i) {\n            res += dist(Ds[perm[i]], Ps[perm[(size_t)i + 1]]);\n        }\n        res += dist(Ds[perm.back()], O);\n        return res;\n    };\n\n    // Three initials\n    vector<vector<int>> inits(3);\n    // 1: identity (greedy)\n    inits[0].resize(N);\n    iota(inits[0].begin(), inits[0].end(), 0);\n    // 2: angle sort on P\n    {\n        vector<pair<double, int>> ang(N);\n        for (int i = 0; i < N; i++) ang[i] = {get_angle(Ps[i]), i};\n        sort(ang.begin(), ang.end());\n        inits[1].resize(N);\n        for (int i = 0; i < N; i++) inits[1][i] = ang[i].second;\n    }\n    // 3: manh coord sort on P (u=x+y, v=x-y)\n    {\n        vector<pair<pair<int, int>, int>> mng(N);\n        for (int i = 0; i < N; i++) {\n            int u = Ps[i].x + Ps[i].y;\n            int v = Ps[i].x - Ps[i].y;\n            mng[i] = {{u, v}, i};\n        }\n        sort(mng.begin(), mng.end());\n        inits[2].resize(N);\n        for (int i = 0; i < N; i++) inits[2][i] = mng[i].second;\n    }\n\n    vector<int> path = inits[0];\n    int current_cost = get_var_cost(path);\n    int bestcost = current_cost;\n    vector<int> bestpath = path;\n    for (int ii = 1; ii < 3; ii++) {\n        int cc = get_var_cost(inits[ii]);\n        if (cc < bestcost) {\n            bestcost = cc;\n            bestpath = inits[ii];\n            path = inits[ii];\n            current_cost = cc;\n        }\n    }\n\n    // SA\n    mt19937 gen(random_device{}());\n    uniform_int_distribution<int> randpos(0, N - 1);\n    uniform_real_distribution<double> rdis(0.0, 1.0);\n    double Tstart = 4000.0;\n    double T = Tstart;\n    double cool_rate = 0.9999;\n    const int MAX_ATT = 8000000;\n    for (int att = 0; att < MAX_ATT; att++) {\n        int i = randpos(gen);\n        int j = randpos(gen);\n        if (i == j) continue;\n        if (i > j) swap(i, j);\n        vector<int> newp = path;\n        swap(newp[i], newp[j]);\n        int nc = get_var_cost(newp);\n        int delta = nc - current_cost;\n        if (delta < 0 || rdis(gen) < exp(-double(delta) / T)) {\n            path = std::move(newp);\n            current_cost = nc;\n            if (nc < bestcost) {\n                bestcost = nc;\n                bestpath = path;\n            }\n        }\n        T *= cool_rate;\n        if (T < 0.1) break;\n    }\n\n    // Build output\n    vector<Point> route;\n    route.reserve(102);\n    route.push_back(O);\n    for (int pi : bestpath) {\n        route.push_back(Ps[pi]);\n        route.push_back(Ds[pi]);\n    }\n    route.push_back(O);\n\n    vector<int> out_ids(N);\n    for (int i = 0; i < N; i++) {\n        out_ids[i] = ids[bestpath[i]];\n    }\n    sort(out_ids.begin(), out_ids.end());\n\n    cout << N;\n    for (int r : out_ids) cout << ' ' << r;\n    cout << '\\n';\n    cout << route.size();\n    for (const auto& pt : route) {\n        cout << ' ' << pt.x << ' ' << pt.y;\n    }\n    cout << '\\n';\n\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    vector<int> X(N), Y(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> X[i] >> Y[i];\n    }\n\n    vector<pair<int, int>> Edge(M);\n    vector<int> D(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        Edge[i] = {u, v};\n        double dx = X[u] - X[v];\n        double dy = Y[u] - Y[v];\n        D[i] = (int)round(hypot(dx, dy));\n    }\n\n    vector<int> par(N), sz(N, 1);\n    vector<double> cminx(N), cmaxx(N), cminy(N), cmaxy(N);\n    for (int i = 0; i < N; ++i) {\n        par[i] = i;\n        cminx[i] = cmaxx[i] = X[i];\n        cminy[i] = cmaxy[i] = Y[i];\n    }\n\n    auto find = [&](auto&& self, int x) -> int {\n        return par[x] == x ? x : par[x] = self(self, par[x]);\n    };\n\n    auto rect_dist = [&](int c1, int c2) -> double {\n        double dx = max({0.0, cminx[c1] - cmaxx[c2], cminx[c2] - cmaxx[c1]});\n        double dy = max({0.0, cminy[c1] - cmaxy[c2], cminy[c2] - cmaxy[c1]});\n        return hypot(dx, dy);\n    };\n\n    auto unite = [&](int a, int b) {\n        a = find(find, a);\n        b = find(find, b);\n        if (a == b) return;\n        if (sz[a] < sz[b]) swap(a, b);\n        par[b] = a;\n        sz[a] += sz[b];\n        cminx[a] = min(cminx[a], cminx[b]);\n        cmaxx[a] = max(cmaxx[a], cmaxx[b]);\n        cminy[a] = min(cminy[a], cminy[b]);\n        cmaxy[a] = max(cmaxy[a], cmaxy[b]);\n    };\n\n    int cur_comp = N;\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;\n\n        int u = Edge[i].first, v = Edge[i].second;\n        int pu = find(find, u), pv = find(find, v);\n        if (pu == pv) {\n            cout << 0 << '\\n' << flush;\n            continue;\n        }\n\n        int s1 = sz[pu], s2 = sz[pv];\n        int smin = min(s1, s2);\n        double sepd = rect_dist(pu, pv);\n        double de_uv = hypot(double(X[u] - X[v]), double(Y[u] - Y[v]));\n        double d_this = D[i];\n\n        bool too_bad = (l > 2.9 * d_this);\n        bool is_small = (smin <= 16);\n        bool separated = (sepd > 1e-9);\n\n        bool good_dist = true;\n        if (separated) {\n            good_dist = (l <= 1.7 * sepd + 3.0);\n        }\n\n        bool take = (!too_bad) && (is_small || good_dist);\n\n        // urgency\n        int remaining = M - i - 1;\n        int needed = cur_comp - 1;\n        if (remaining <= needed * 2 || needed <= 8 || (double)needed / max(1, remaining) > 0.3) {\n            take = !too_bad;\n        }\n\n        if (take) {\n            unite(u, v);\n            --cur_comp;\n            cout << 1 << '\\n' << flush;\n        } else {\n            cout << 0 << '\\n' << flush;\n        }\n    }\n\n    return 0;\n}","ahc008":"","ahc009":"","ahc010":"","ahc011":"","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing P = pair<ll, ll>;\n\nstruct Line {\n  ll px, py, qx, qy;\n};\n\nint side(const Line& l, ll x, ll y) {\n  ll dx1 = l.qx - l.px;\n  ll dy1 = l.qy - l.py;\n  ll dx2 = x - l.px;\n  ll dy2 = y - l.py;\n  ll cross = dx1 * dy2 - dy1 * dx2;\n  if (cross == 0) return 0;\n  return cross > 0 ? 1 : -1;\n}\n\ntuple<ll, ll, ll> exgcd(ll a, ll b) {\n  if (b == 0) return {a, 1, 0};\n  auto [g, x, y] = exgcd(b, a % b);\n  return {g, y, x - (a / b) * y};\n}\n\nint compute_score(const vector<Line>& lines, const vector<P>& points, const vector<int>& a, int N) {\n  int k = lines.size();\n  vector<vector<signed char>> sigs;\n  sigs.reserve(N);\n  for (int i = 0; i < N; ++i) {\n    ll x = points[i].first;\n    ll y = points[i].second;\n    vector<signed char> sig(k);\n    bool ok = true;\n    for (int j = 0; j < k; ++j) {\n      int s = side(lines[j], x, y);\n      if (s == 0) {\n        ok = false;\n        break;\n      }\n      sig[j] = s == 1 ? 1 : -1;\n    }\n    if (ok) {\n      sigs.push_back(move(sig));\n    }\n  }\n  sort(sigs.begin(), sigs.end());\n  vector<int> b(11, 0);\n  size_t ns = sigs.size();\n  if (ns == 0) return 0;\n  size_t i = 1;\n  size_t cnt = 1;\n  for (; i < ns; ++i) {\n    if (sigs[i] == sigs[i - 1]) {\n      ++cnt;\n    } else {\n      if (cnt <= 10) ++b[cnt];\n      cnt = 1;\n    }\n  }\n  if (cnt <= 10) ++b[cnt];\n  int score = 0;\n  for (int d = 1; d <= 10; ++d) {\n    score += min(a[d], b[d]);\n  }\n  return score;\n}\n\npair<int, vector<Line>> get_score_and_cands(const vector<Line>& lines, const vector<P>& points,\n                                            const vector<int>& a, int N) {\n  int k = lines.size();\n  vector<pair<vector<signed char>, int>> point_sigs;\n  point_sigs.reserve(N);\n  for (int i = 0; i < N; ++i) {\n    ll x = points[i].first;\n    ll y = points[i].second;\n    vector<signed char> sig(k);\n    bool ok = true;\n    for (int j = 0; j < k; ++j) {\n      int s = side(lines[j], x, y);\n      if (s == 0) {\n        ok = false;\n        break;\n      }\n      sig[j] = s == 1 ? 1 : -1;\n    }\n    if (ok) {\n      point_sigs.emplace_back(move(sig), i);\n    }\n  }\n  sort(point_sigs.begin(), point_sigs.end());\n  vector<int> b(11, 0);\n  size_t ns = point_sigs.size();\n  int score = 0;\n  vector<Line> cands;\n  if (ns > 0) {\n    size_t istart = 0;\n    for (size_t i = 1; i <= ns; ++i) {\n      bool newgroup = (i == ns) || (point_sigs[i].first != point_sigs[i - 1].first);\n      if (newgroup) {\n        int cntt = i - istart;\n        if (cntt <= 10) ++b[cntt];\n        if (cntt >= 2 && cands.size() < 50) {\n          vector<int> group;\n          group.reserve(cntt);\n          for (size_t j = istart; j < i; ++j) {\n            group.push_back(point_sigs[j].second);\n          }\n          // generate cands\n          mt19937_64 rng((size_t)group[0] + (size_t)group.back() * 12345);  // semi-random\n          int ngen = 20;\n          if (group.size() < 20) ngen = group.size();\n          for (int tr = 0; tr < ngen && cands.size() < 50; ++tr) {\n            int range = 100;\n            ll aa = (rng() % (2LL * range + 1)) - range;\n            ll bb = (rng() % (2LL * range + 1)) - range;\n            if (aa == 0 && bb == 0) continue;\n            ll gg = __gcd(abs(aa), abs(bb));\n            aa /= gg;\n            bb /= gg;\n            vector<pair<ll, int>> projs;\n            projs.reserve(group.size());\n            for (int id : group) {\n              ll pr = aa * points[id].first + bb * points[id].second;\n              projs.emplace_back(pr, id);\n            }\n            sort(projs.begin(), projs.end());\n            int gm = min(10, (int)group.size() - 1);\n            for (int m = 1; m <= gm && cands.size() < 50; ++m) {\n              ll ml = projs[m - 1].first;\n              ll mr = projs[m].first;\n              if (ml + 1 >= mr) continue;\n              ll kk = ml + 1;\n              ll cc = -kk;\n              ll dd = -cc;\n              auto [g, x, y] = exgcd(aa, bb);\n              if (g < 0) {\n                g = -g;\n                x = -x;\n                y = -y;\n              }\n              if (dd % g != 0) continue;\n              ll mul = dd / g;\n              ll xx_ = x * mul;\n              ll yy_ = y * mul;\n              ll dirx_ = bb;\n              ll diry_ = -aa;\n              ll ppx, ppy;\n              if (bb != 0) {\n                ll tt = -xx_ / bb;\n                ppx = xx_ + bb * tt;\n                ppy = yy_ - aa * tt;\n              } else {\n                ppx = xx_;\n                ppy = yy_;\n              }\n              ll qqx = ppx + dirx_;\n              ll qqy = ppy + diry_;\n              if (abs(ppx) > 1000000000LL || abs(ppy) > 1000000000LL || abs(qqx) > 1000000000LL ||\n                  abs(qqy) > 1000000000LL)\n                continue;\n              if (ppx == qqx && ppy == qqy) continue;\n              cands.push_back({ppx, ppy, qqx, qqy});\n            }\n          }\n        }\n        istart = i;\n      }\n    }\n    for (int d = 1; d <= 10; ++d) {\n      score += min(a[d], b[d]);\n    }\n  }\n  return {score, move(cands)};\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  srand((unsigned)time(nullptr));\n  int N, K;\n  cin >> N >> K;\n  vector<int> a(11, 0);\n  for (int d = 1; d <= 10; ++d) {\n    cin >> a[d];\n  }\n  vector<P> points(N);\n  for (auto& p : points) {\n    cin >> p.first >> p.second;\n  }\n  vector<Line> curr;\n  auto [cur_score, _c] = get_score_and_cands(curr, points, a, N);\n  int best_score = cur_score;\n  vector<Line> best_curr = curr;\n  while (curr.size() < K) {\n    auto [cscore, cands] = get_score_and_cands(curr, points, a, N);\n    if (cands.empty()) break;\n    Line best_cand;\n    int best_new = cscore;\n    bool found_better = false;\n    for (const auto& cand : cands) {\n      vector<Line> temp = curr;\n      temp.push_back(cand);\n      int nsc = compute_score(temp, points, a, N);\n      if (nsc > best_new) {\n        best_new = nsc;\n        best_cand = cand;\n        found_better = true;\n      }\n    }\n    if (found_better) {\n      curr.push_back(best_cand);\n      if (best_new > best_score) {\n        best_score = best_new;\n      }\n    } else {\n      break;\n    }\n  }\n  cout << curr.size() << '\\n';\n  for (const auto& l : curr) {\n    cout << l.px << ' ' << l.py << ' ' << l.qx << ' ' << l.qy << '\\n';\n  }\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 64;\nbool occupied[MAXN][MAXN];\nbool used_h[MAXN][MAXN];\nbool used_v[MAXN][MAXN];\nbool used_ne[MAXN][MAXN];\nbool used_nw[MAXN][MAXN];\nint N, c;\nint NN;\n\nstruct Move {\n    int x1, y1, x2, y2, x3, y3, x4, y4;\n    long long prio;\n};\n\nvector<Move> cands;\nvector<Move> ans_moves;\n\nlong long distsq(int x, int y) {\n    long long dx = x - c;\n    long long dy = y - c;\n    return dx * dx + dy * dy;\n}\n\npair<int, int> getxy(int uu, int vv) {\n    int xx = (uu + vv) / 2;\n    int yy = (uu - vv) / 2;\n    return {xx, yy};\n}\n\nbool in_grid(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool check_clean(int x0, int y0, int x1, int y1) {\n    int dx = x1 - x0;\n    int dy = y1 - y0;\n    int adx = abs(dx);\n    int ady = abs(dy);\n    if (adx == 0 && ady == 0) return false;\n    if ((adx != 0 && ady != 0 && adx != ady)) return false;\n    int k = max(adx, ady);\n    int stepx = (dx > 0 ? 1 : (dx < 0 ? -1 : 0));\n    int stepy = (dy > 0 ? 1 : (dy < 0 ? -1 : 0));\n\n    // interiors\n    for (int i = 1; i < k; ++i) {\n        int xx = x0 + i * stepx;\n        int yy = y0 + i * stepy;\n        if (!in_grid(xx, yy) || occupied[xx][yy]) return false;\n    }\n\n    // units\n    for (int i = 0; i < k; ++i) {\n        int xx = x0 + i * stepx;\n        int yy = y0 + i * stepy;\n        int nx = xx + stepx;\n        int ny = yy + stepy;\n        if (!in_grid(xx, yy) || !in_grid(nx, ny)) return false;\n\n        int mx = min(xx, nx);\n        int yleft = (xx == mx ? yy : ny);\n        int yright = (nx == mx ? ny : yy);\n\n        if (stepx == 0) {  // vert\n            int miny = min(yy, ny);\n            if (miny < 0 || miny >= N - 1 || used_v[xx][miny]) return false;\n        } else if (stepy == 0) {  // horiz\n            if (mx < 0 || mx >= N - 1 || used_h[yy][mx]) return false;\n        } else {  // diag\n            if (yright == yleft + 1) {\n                if (mx < 0 || mx >= N - 1 || yleft < 0 || yleft >= N - 1 || used_ne[mx][yleft]) return false;\n            } else if (yright == yleft - 1) {\n                if (mx < 0 || mx >= N - 1 || yleft < 1 || yleft >= N || used_nw[mx][yleft]) return false;\n            } else {\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nvoid mark_side(int x0, int y0, int x1, int y1) {\n    int dx = x1 - x0;\n    int dy = y1 - y0;\n    int adx = abs(dx);\n    int ady = abs(dy);\n    if (adx == 0 && ady == 0) return;\n    int k = max(adx, ady);\n    int stepx = (dx > 0 ? 1 : (dx < 0 ? -1 : 0));\n    int stepy = (dy > 0 ? 1 : (dy < 0 ? -1 : 0));\n\n    // mark units only\n    for (int i = 0; i < k; ++i) {\n        int xx = x0 + i * stepx;\n        int yy = y0 + i * stepy;\n        int nx = xx + stepx;\n        int ny = yy + stepy;\n\n        int mx = min(xx, nx);\n        int yleft = (xx == mx ? yy : ny);\n        int yright = (nx == mx ? ny : yy);\n\n        if (stepx == 0) {  // vert\n            int miny = min(yy, ny);\n            used_v[xx][miny] = true;\n        } else if (stepy == 0) {  // horiz\n            used_h[yy][mx] = true;\n        } else {  // diag\n            if (yright == yleft + 1) {\n                used_ne[mx][yleft] = true;\n            } else if (yright == yleft - 1) {\n                used_nw[mx][yleft] = true;\n            }\n        }\n    }\n}\n\nvoid scan_axis() {\n    for (int xl = 0; xl < N; ++xl) {\n        for (int xr = xl + 1; xr < N; ++xr) {\n            for (int yb = 0; yb < N; ++yb) {\n                for (int yt = yb + 1; yt < N; ++yt) {\n                    vector<pair<int, int>> corns = {\n                        {xl, yb}, {xr, yb}, {xr, yt}, {xl, yt}\n                    };\n                    int cnt = 0;\n                    for (auto& p : corns) {\n                        if (occupied[p.first][p.second]) ++cnt;\n                    }\n                    if (cnt != 3) continue;\n                    pair<int, int> p1;\n                    int miss_idx = -1;\n                    for (int ii = 0; ii < 4; ++ii) {\n                        if (!occupied[corns[ii].first][corns[ii].second]) {\n                            p1 = corns[ii];\n                            miss_idx = ii;\n                            break;\n                        }\n                    }\n                    if (occupied[p1.first][p1.second]) continue;\n\n                    // check cleans\n                    vector<pair<int, int>> side_starts = {corns[0], corns[1], corns[2], corns[3]};\n                    if (!check_clean(corns[0], corns[1]) ||\n                        !check_clean(corns[1], corns[2]) ||\n                        !check_clean(corns[2], corns[3]) ||\n                        !check_clean(corns[3], corns[0])) continue;\n\n                    // order\n                    int idx2 = (miss_idx + 1) % 4;\n                    int idx3 = (miss_idx + 2) % 4;\n                    int idx4 = (miss_idx + 3) % 4;\n                    Move m{\n                        p1.first, p1.second,\n                        corns[idx2].first, corns[idx2].second,\n                        corns[idx3].first, corns[idx3].second,\n                        corns[idx4].first, corns[idx4].second\n                    };\n                    m.prio = -distsq(p1.first, p1.second);\n                    cands.push_back(m);\n                }\n            }\n        }\n    }\n}\n\nvoid scan_45(int parity) {\n    vector<int> us, vs;\n    int startu = parity;\n    int startv = parity ? 1 : 0;\n    if (parity == 0) {  // even\n        for (int uu = 0; uu <= 2 * (N - 1); uu += 2) us.push_back(uu);\n        for (int vv = -(N - 1); vv <= N - 1; vv += 2) {\n            if ((vv % 2 + 2) % 2 == 0) vs.push_back(vv);  // even\n        }\n    } else {  // odd\n        for (int uu = 1; uu <= 2 * (N - 1); uu += 2) us.push_back(uu);\n        for (int vv = -(N - 1); vv <= N - 1; vv += 2) {\n            if ((vv % 2 + 2) % 2 == 1) vs.push_back(vv);  // odd\n        }\n    }\n    if (us.empty() || vs.empty()) return;\n    for (size_t i = 0; i < us.size(); ++i) {\n        for (size_t j = i + 1; j < us.size(); ++j) {\n            int u1 = us[i], u2 = us[j];\n            for (size_t kk = 0; kk < vs.size(); ++kk) {\n                for (size_t l = kk + 1; l < vs.size(); ++l) {\n                    int v1 = vs[kk], v2 = vs[l];\n                    auto c0 = getxy(u1, v1);\n                    if (!in_grid(c0.first, c0.second)) continue;\n                    auto c1 = getxy(u1, v2);\n                    if (!in_grid(c1.first, c1.second)) continue;\n                    auto c2 = getxy(u2, v2);\n                    if (!in_grid(c2.first, c2.second)) continue;\n                    auto c3 = getxy(u2, v1);\n                    if (!in_grid(c3.first, c3.second)) continue;\n\n                    vector<pair<int, int>> corns = {c0, c1, c2, c3};\n                    int cnt = 0;\n                    for (auto& p : corns) {\n                        if (occupied[p.first][p.second]) ++cnt;\n                    }\n                    if (cnt != 3) continue;\n                    pair<int, int> p1;\n                    int miss_idx = -1;\n                    for (int ii = 0; ii < 4; ++ii) {\n                        if (!occupied[corns[ii].first][corns[ii].second]) {\n                            p1 = corns[ii];\n                            miss_idx = ii;\n                            break;\n                        }\n                    }\n                    if (occupied[p1.first][p1.second]) continue;\n\n                    // check cleans: 0-1, 1-2, 2-3, 3-0\n                    if (!check_clean(corns[0], corns[1]) ||\n                        !check_clean(corns[1], corns[2]) ||\n                        !check_clean(corns[2], corns[3]) ||\n                        !check_clean(corns[3], corns[0])) continue;\n\n                    // order\n                    int idx2 = (miss_idx + 1) % 4;\n                    int idx3 = (miss_idx + 2) % 4;\n                    int idx4 = (miss_idx + 3) % 4;\n                    Move m{\n                        p1.first, p1.second,\n                        corns[idx2].first, corns[idx2].second,\n                        corns[idx3].first, corns[idx3].second,\n                        corns[idx4].first, corns[idx4].second\n                    };\n                    m.prio = -distsq(p1.first, p1.second);\n                    cands.push_back(m);\n                }\n            }\n        }\n    }\n}\n\nvoid do_scan() {\n    cands.clear();\n    scan_axis();\n    scan_45(0);  // even\n    scan_45(1);  // odd\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    clock_t start_clk = clock();\n\n    cin >> N >> NN;\n    c = (N - 1) / 2;\n    memset(occupied, 0, sizeof(occupied));\n    memset(used_h, 0, sizeof(used_h));\n    memset(used_v, 0, sizeof(used_v));\n    memset(used_ne, 0, sizeof(used_ne));\n    memset(used_nw, 0, sizeof(used_nw));\n    for (int i = 0; i < NN; ++i) {\n        int x, y;\n        cin >> x >> y;\n        occupied[x][y] = true;\n    }\n\n    int max_iters = 1000;\n    int iter = 0;\n    while (iter++ < max_iters) {\n        double timet = (clock() - start_clk) / (double)CLOCKS_PER_SEC;\n        if (timet > 4.2) break;\n\n        do_scan();\n        if (cands.empty()) break;\n\n        sort(cands.begin(), cands.end(), [](const Move& a, const Move& b) {\n            return a.prio > b.prio;\n        });\n\n        for (auto& mv : cands) {\n            double timet2 = (clock() - start_clk) / (double)CLOCKS_PER_SEC;\n            if (timet2 > 4.4) break;\n\n            if (occupied[mv.x1][mv.y1]) continue;\n\n            pair<int,int> pp1 = {mv.x1, mv.y1};\n            pair<int,int> pp2 = {mv.x2, mv.y2};\n            pair<int,int> pp3 = {mv.x3, mv.y3};\n            pair<int,int> pp4 = {mv.x4, mv.y4};\n\n            if (check_clean(pp1, pp2) &&\n                check_clean(pp2, pp3) &&\n                check_clean(pp3, pp4) &&\n                check_clean(pp4, pp1)) {\n                ans_moves.push_back(mv);\n                occupied[mv.x1][mv.y1] = true;\n                mark_side(mv.x1, mv.y1, mv.x2, mv.y2);\n                mark_side(mv.x2, mv.y2, mv.x3, mv.y3);\n                mark_side(mv.x3, mv.y3, mv.x4, mv.y4);\n                mark_side(mv.x4, mv.y4, mv.x1, mv.y1);\n            }\n        }\n    }\n\n    cout << ans_moves.size() << '\\n';\n    for (auto& m : ans_moves) {\n        cout << m.x1 << ' ' << m.y1 << ' ' << m.x2 << ' ' << m.y2\n             << ' ' << m.x3 << ' ' << m.y3 << ' ' << m.x4 << ' ' << m.y4 << '\\n';\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int, int>;\nusing vv = vector<vector<int>>;\n\nvoid simulate(vv& g, char dir) {\n    if (dir == 'F') {\n        for (int c = 0; c < 10; ++c) {\n            vector<int> lis;\n            for (int r = 0; r < 10; ++r) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            for (int r = 0; r < sz; ++r) g[r][c] = lis[r];\n            for (int r = sz; r < 10; ++r) g[r][c] = 0;\n        }\n    } else if (dir == 'B') {\n        for (int c = 0; c < 10; ++c) {\n            vector<int> lis;\n            for (int r = 0; r < 10; ++r) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            int off = 10 - sz;\n            for (int r = 0; r < off; ++r) g[r][c] = 0;\n            for (int r = 0; r < sz; ++r) g[off + r][c] = lis[r];\n        }\n    } else if (dir == 'L') {\n        for (int r = 0; r < 10; ++r) {\n            vector<int> lis;\n            for (int c = 0; c < 10; ++c) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            for (int c = 0; c < sz; ++c) g[r][c] = lis[c];\n            for (int c = sz; c < 10; ++c) g[r][c] = 0;\n        }\n    } else if (dir == 'R') {\n        for (int r = 0; r < 10; ++r) {\n            vector<int> lis;\n            for (int c = 0; c < 10; ++c) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            int off = 10 - sz;\n            for (int c = 0; c < off; ++c) g[r][c] = 0;\n            for (int c = 0; c < sz; ++c) g[r][off + c] = lis[c];\n        }\n    }\n}\n\nlong long compute(const vv& g) {\n    bool vis[10][10] = {};\n    int dr[] = {-1, 0, 1, 0};\n    int dc[] = {0, 1, 0, -1};\n    long long sumsq = 0;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            if (g[r][c] != 0 && !vis[r][c]) {\n                int flav = g[r][c];\n                queue<pii> q;\n                q.emplace(r, c);\n                vis[r][c] = true;\n                int sz = 1;\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    for (int d = 0; d < 4; ++d) {\n                        int nr = x + dr[d];\n                        int nc = y + dc[d];\n                        if (nr >= 0 && nr < 10 && nc >= 0 && nc < 10 &&\n                            !vis[nr][nc] && g[nr][nc] == flav) {\n                            vis[nr][nc] = true;\n                            q.emplace(nr, nc);\n                            ++sz;\n                        }\n                    }\n                }\n                sumsq += 1LL * sz * sz;\n            }\n        }\n    }\n    return sumsq;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    vector<int> f(101);\n    for (int i = 1; i <= 100; ++i) {\n        cin >> f[i];\n    }\n    vv grid(10, vector<int>(10, 0));\n    set<pii> empties;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            empties.emplace(r, c);\n        }\n    }\n    string dirs = \"FBLR\";\n    for (int t = 1; t <= 100; ++t) {\n        int p;\n        cin >> p;\n        auto it = empties.begin();\n        advance(it, p - 1);\n        auto [pr, pc] = *it;\n        grid[pr][pc] = f[t];\n        empties.erase(it);\n\n        long long best_score = -1;\n        char best_dir = ' ';\n        for (char d : dirs) {\n            vv temp = grid;\n            simulate(temp, d);\n            long long sc = compute(temp);\n            if (sc > best_score || (sc == best_score && d < best_dir)) {\n                best_score = sc;\n                best_dir = d;\n            }\n        }\n        cout << best_dir << endl;\n        simulate(grid, best_dir);\n    }\n    return 0;\n}","ahc016":"","ahc017":"","ahc019":"","ahc020":"","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int, int>;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N = 30;\n  int total = N * (N + 1) / 2;\n  vector<int> cum(N + 1, 0);\n  for (int i = 1; i <= N; ++i) {\n    cum[i] = cum[i - 1] + i;\n  }\n  vector<pii> coord(total);\n  vector<vector<int>> flat_pos(N, vector<int>(N));\n  for (int x = 0; x < N; ++x) {\n    for (int y = 0; y <= x; ++y) {\n      int id = cum[x] + y;\n      coord[id] = {x, y};\n      flat_pos[x][y] = id;\n    }\n  }\n  vector<int> a(total);\n  for (int i = 0; i < total; ++i) {\n    cin >> a[i];\n  }\n  vector<vector<int>> childs(total);\n  for (int x = 0; x < N - 1; ++x) {\n    for (int y = 0; y <= x; ++y) {\n      int p = flat_pos[x][y];\n      int l = flat_pos[x + 1][y];\n      int r = flat_pos[x + 1][y + 1];\n      childs[p] = {l, r};\n    }\n  }\n  vector<vector<int>> ops;\n  auto siftdown = [&](auto&& self, int node) -> void {\n    while (true) {\n      auto& ch = childs[node];\n      if (ch.empty()) return;\n      int l = ch[0], r = ch[1];\n      int smallest = node;\n      if (a[l] < a[smallest]) smallest = l;\n      if (a[r] < a[smallest]) smallest = r;\n      if (smallest == node) return;\n      swap(a[node], a[smallest]);\n      auto [x1, y1] = coord[node];\n      auto [x2, y2] = coord[smallest];\n      ops.push_back({x1, y1, x2, y2});\n      node = smallest;\n    }\n  };\n  int last_nl = cum[N - 1] - 1;\n  for (int i = last_nl; i >= 0; --i) {\n    siftdown(siftdown, i);\n  }\n  cout << ops.size() << '\\n';\n  for (auto& op : ops) {\n    cout << op[0] << ' ' << op[1] << ' ' << op[2] << ' ' << op[3] << '\\n';\n  }\n}","toyota2023summer-final":"","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n, m;\n  cin >> n >> m;\n  vector<vector<int>> grid(n, vector<int>(n));\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      cin >> grid[i][j];\n    }\n  }\n  vector<vector<int>> touches0(m + 1, false);\n  vector<pair<int, int>> anchor(m + 1, make_pair(-1, -1));\n  vector<int> cursize(m + 1, 0);\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      int c = grid[i][j];\n      cursize[c]++;\n      if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {\n        touches0[c] = true;\n        if (anchor[c].first == -1) {\n          anchor[c] = {i, j};\n        }\n      }\n    }\n  }\n  vector<vector<int>> cnt(m + 1, vector<int>(m + 1, 0));\n  // horizontal\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n - 1; ++j) {\n      int a = grid[i][j], b = grid[i][j + 1];\n      if (a != b) {\n        int u = min(a, b), v = max(a, b);\n        cnt[u][v]++;\n      }\n    }\n  }\n  // vertical\n  for (int i = 0; i < n - 1; ++i) {\n    for (int j = 0; j < n; ++j) {\n      int a = grid[i][j], b = grid[i + 1][j];\n      if (a != b) {\n        int u = min(a, b), v = max(a, b);\n        cnt[u][v]++;\n      }\n    }\n  }\n\n  vector<pair<int, int>> dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n  auto peel = [&](vector<vector<int>> g, const vector<int>& init_size, auto&& self) -> pair<vector<vector<int>>, int> {\n    vector<vector<int>> out = g;\n    vector<int> size = init_size;\n    auto cnte = cnt;  // copy\n    bool changed = true;\n    while (changed) {\n      changed = false;\n      for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n          if (out[i][j] == 0) continue;\n          int c = out[i][j];\n          if (anchor[c].first == i && anchor[c].second == j) continue;\n          if (size[c] == 1) continue;\n          int same_n = 0;\n          bool can_zero = (i == 0 || i == n - 1 || j == 0 || j == n - 1);\n          bool safe_adj = true;\n          bool would_hurt_i = false;\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) continue;\n            int nc = out[ni][nj];\n            if (nc == c) ++same_n;\n            else if (nc == 0) can_zero = true;\n            else {\n              int u = min(c, nc), v = max(c, nc);\n              if (cnte[u][v] == 1) safe_adj = false;\n              if (!touches0[nc]) would_hurt_i = true;\n            }\n          }\n          if (same_n > 1 || !safe_adj || !can_zero || would_hurt_i) continue;\n          // remove\n          out[i][j] = 0;\n          size[c]--;\n          // update cnt\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n              int nc = out[ni][nj];\n              if (nc > 0 && nc != c) {\n                int u = min(c, nc), v = max(c, nc);\n                cnte[u][v]--;\n              }\n            }\n          }\n          changed = true;\n        }\n      }\n    }\n    int zeros = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        if (out[i][j] == 0) ++zeros;\n      }\n    }\n    return {out, zeros};\n  };\n\n  // first peel normal\n  auto [out1, z1] = peel(grid, cursize, peel);\n\n  // second peel reverse order\n  vector<vector<int>> grid_rev = grid;  // same\n  // but change scan to reverse\n  auto peel_rev = [&](vector<vector<int>> g, const vector<int>& init_size, auto&& self) -> pair<vector<vector<int>>, int> {\n    vector<vector<int>> out = g;\n    vector<int> size = init_size;\n    auto cnte = cnt;\n    bool changed = true;\n    while (changed) {\n      changed = false;\n      for (int i = n - 1; i >= 0; --i) {\n        for (int j = n - 1; j >= 0; --j) {\n          if (out[i][j] == 0) continue;\n          int c = out[i][j];\n          if (anchor[c].first == i && anchor[c].second == j) continue;\n          if (size[c] == 1) continue;\n          int same_n = 0;\n          bool can_zero = (i == 0 || i == n - 1 || j == 0 || j == n - 1);\n          bool safe_adj = true;\n          bool would_hurt_i = false;\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) continue;\n            int nc = out[ni][nj];\n            if (nc == c) ++same_n;\n            else if (nc == 0) can_zero = true;\n            else {\n              int u = min(c, nc), v = max(c, nc);\n              if (cnte[u][v] == 1) safe_adj = false;\n              if (!touches0[nc]) would_hurt_i = true;\n            }\n          }\n          if (same_n > 1 || !safe_adj || !can_zero || would_hurt_i) continue;\n          // remove\n          out[i][j] = 0;\n          size[c]--;\n          // update cnt\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n              int nc = out[ni][nj];\n              if (nc > 0 && nc != c) {\n                int u = min(c, nc), v = max(c, nc);\n                cnte[u][v]--;\n              }\n            }\n          }\n          changed = true;\n        }\n      }\n    }\n    int zeros = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        if (out[i][j] == 0) ++zeros;\n      }\n    }\n    return {out, zeros};\n  };\n  auto [out2, z2] = peel_rev(grid, cursize, peel_rev);\n\n  // pick the better one\n  vector<vector<int>> final_out = (z1 >= z2 ? out1 : out2);\n\n  // output\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      cout << final_out[i][j];\n      if (j < n - 1) cout << \" \";\n      else cout << \"\\n\";\n    }\n  }\n  return 0;\n}","ahc025":"","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  int n, m;\n  cin >> n >> m;\n  vector<vector<int>> stacks(m);\n  vector<int> location(n + 1, -1);\n  for (int i = 0; i < m; i++) {\n    stacks[i].resize(n / m);\n    for (int j = 0; j < n / m; j++) {\n      cin >> stacks[i][j];\n      location[stacks[i][j]] = i;\n    }\n  }\n  vector<pair<int, int>> ops;\n  int next_box = 1;\n  while (next_box <= n) {\n    int s = location[next_box];\n    if (s != -1 && !stacks[s].empty() && stacks[s].back() == next_box) {\n      ops.emplace_back(next_box, 0);\n      stacks[s].pop_back();\n      location[next_box] = -1;\n      next_box++;\n      continue;\n    }\n    // dig to expose\n    assert(s != -1);\n    auto& stk = stacks[s];\n    auto it = find(stk.begin(), stk.end(), next_box);\n    assert(it != stk.end());\n    size_t p = it - stk.begin();\n    size_t h = stk.size();\n    assert(p < h - 1);\n    size_t start_idx = p + 1;\n    int v_move = stk[start_idx];\n    int new_top_after = stk.back();\n    // find best dest\n    int best_d = -1;\n    int best_score = INT_MAX;\n    for (int d = 0; d < m; d++) {\n      if (d == s) continue;\n      bool acc = stacks[d].empty();\n      if (!acc) {\n        int t = stacks[d].back();\n        if (t > new_top_after) acc = true;\n      }\n      if (acc) {\n        int score = stacks[d].empty() ? INT_MIN : stacks[d].back();\n        if (score < best_score) {\n          best_score = score;\n          best_d = d;\n        }\n      }\n    }\n    if (best_d == -1) {\n      // fallback: max t\n      int max_t = -1;\n      for (int d = 0; d < m; d++) {\n        if (d == s) continue;\n        int tt = stacks[d].empty() ? INT_MAX : stacks[d].back();\n        if (tt > max_t) {\n          max_t = tt;\n          best_d = d;\n        }\n      }\n      assert(best_d != -1);\n    }\n    // perform move\n    auto& dstk = stacks[best_d];\n    vector<int> pile(stk.begin() + start_idx, stk.end());\n    stk.resize(start_idx);\n    dstk.insert(dstk.end(), pile.begin(), pile.end());\n    for (int b : pile) {\n      location[b] = best_d;\n    }\n    ops.emplace_back(v_move, best_d + 1);\n  }\n  for (auto [v, i] : ops) {\n    cout << v << \" \" << i << '\\n';\n  }\n}","ahc027":"","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing pii = pair<int, int>;\nint manh(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); }\n\nstruct Emb {\n  array<pii, 5> seq;\n  int intd;\n};\n\nint compute_connect(const vector<int>& ord, const vector<Emb>& embs, pii init_pos, int M) {\n  int sumd = manh(init_pos.first, init_pos.second, embs[ord[0]].seq[0].first, embs[ord[0]].seq[0].second);\n  for (int i = 0; i < M - 1; ++i) {\n    sumd += manh(embs[ord[i]].seq[4].first, embs[ord[i]].seq[4].second,\n                 embs[ord[i + 1]].seq[0].first, embs[ord[i + 1]].seq[0].second);\n  }\n  return sumd;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M;\n  cin >> N >> M;\n  int si, sj;\n  cin >> si >> sj;\n  pii init_pos = {si, sj};\n  vector<string> grid(N);\n  for (auto& s : grid) cin >> s;\n  vector<vector<pii>> pos(26);\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      int c = grid[i][j] - 'A';\n      pos[c].emplace_back(i, j);\n    }\n  }\n  vector<string> ts(M);\n  for (auto& s : ts) cin >> s;\n  vector<Emb> embs(M);\n  const int INF = 1e9 + 5;\n  for (int k = 0; k < M; ++k) {\n    string t = ts[k];\n    vector<vector<pii>> cand(5);\n    for (int l = 0; l < 5; ++l) {\n      cand[l] = pos[t[l] - 'A'];\n    }\n    int sz[5];\n    for (int l = 0; l < 5; ++l) sz[l] = cand[l].size();\n    int min_d = INF;\n    Emb best;\n    for (int a0 = 0; a0 < sz[0]; ++a0) {\n      pii p0 = cand[0][a0];\n      for (int a1 = 0; a1 < sz[1]; ++a1) {\n        pii p1 = cand[1][a1];\n        int d01 = manh(p0.first, p0.second, p1.first, p1.second);\n        for (int a2 = 0; a2 < sz[2]; ++a2) {\n          pii p2 = cand[2][a2];\n          int d12 = manh(p1.first, p1.second, p2.first, p2.second);\n          int cd = d01 + d12;\n          if (cd >= min_d) continue;\n          for (int a3 = 0; a3 < sz[3]; ++a3) {\n            pii p3 = cand[3][a3];\n            int d23 = manh(p2.first, p2.second, p3.first, p3.second);\n            int cd2 = cd + d23;\n            if (cd2 >= min_d) continue;\n            for (int a4 = 0; a4 < sz[4]; ++a4) {\n              pii p4 = cand[4][a4];\n              int d34 = manh(p3.first, p3.second, p4.first, p4.second);\n              int tot = cd2 + d34;\n              if (tot < min_d) {\n                min_d = tot;\n                best.seq = {p0, p1, p2, p3, p4};\n                best.intd = tot;\n              }\n            }\n          }\n        }\n      }\n    }\n    embs[k] = best;\n  }\n  // NN greedy\n  vector<int> order_nn(M);\n  vector<bool> used(M, false);\n  pii curr = init_pos;\n  for (int st = 0; st < M; ++st) {\n    int bestk = -1;\n    int mindd = INF;\n    for (int k = 0; k < M; ++k) {\n      if (used[k]) continue;\n      pii stp = embs[k].seq[0];\n      int dd = manh(curr.first, curr.second, stp.first, stp.second);\n      if (dd < mindd || (dd == mindd && k < bestk)) {\n        mindd = dd;\n        bestk = k;\n      }\n    }\n    order_nn[st] = bestk;\n    used[bestk] = true;\n    curr = embs[bestk].seq[4];\n  }\n  vector<int> order1 = order_nn;\n  // 2-opt on order1\n  {\n    bool improved;\n    int passes = 0;\n    do {\n      improved = false;\n      for (int a = 0; a < M; ++a) {\n        for (int b = a + 1; b < M; ++b) {\n          pii prev_end = (a == 0 ? init_pos : embs[order1[a - 1]].seq[4]);\n          pii s_a = embs[order1[a]].seq[0];\n          int old1 = manh(prev_end.first, prev_end.second, s_a.first, s_a.second);\n          int old2 = (b == M - 1 ? 0\n                          : manh(embs[order1[b]].seq[4].first, embs[order1[b]].seq[4].second,\n                                 embs[order1[b + 1]].seq[0].first, embs[order1[b + 1]].seq[0].second));\n          pii s_b = embs[order1[b]].seq[0];\n          int new1 = manh(prev_end.first, prev_end.second, s_b.first, s_b.second);\n          pii e_a = embs[order1[a]].seq[4];\n          int new2 = (b == M - 1 ? 0\n                          : manh(e_a.first, e_a.second,\n                                 embs[order1[b + 1]].seq[0].first, embs[order1[b + 1]].seq[0].second));\n          int delta = new1 + new2 - old1 - old2;\n          if (delta < 0) {\n            reverse(order1.begin() + a, order1.begin() + b + 1);\n            improved = true;\n          }\n        }\n      }\n    } while (improved && ++passes < 200);\n  }\n  // Sorted order\n  vector<int> order2(M);\n  iota(order2.begin(), order2.end(), 0);\n  sort(order2.begin(), order2.end(), [&](int aa, int bb) {\n    int cia = (embs[aa].seq[0].first + embs[aa].seq[4].first) / 2;\n    int cja = (embs[aa].seq[0].second + embs[aa].seq[4].second) / 2;\n    int cib = (embs[bb].seq[0].first + embs[bb].seq[4].first) / 2;\n    int cjb = (embs[bb].seq[0].second + embs[bb].seq[4].second) / 2;\n    return cia * N + cja < cib * N + cjb;\n  });\n  vector<int> order3 = order2;\n  // 2-opt on order3\n  {\n    bool improved;\n    int passes = 0;\n    do {\n      improved = false;\n      for (int a = 0; a < M; ++a) {\n        for (int b = a + 1; b < M; ++b) {\n          pii prev_end = (a == 0 ? init_pos : embs[order3[a - 1]].seq[4]);\n          pii s_a = embs[order3[a]].seq[0];\n          int old1 = manh(prev_end.first, prev_end.second, s_a.first, s_a.second);\n          int old2 = (b == M - 1 ? 0\n                          : manh(embs[order3[b]].seq[4].first, embs[order3[b]].seq[4].second,\n                                 embs[order3[b + 1]].seq[0].first, embs[order3[b + 1]].seq[0].second));\n          pii s_b = embs[order3[b]].seq[0];\n          int new1 = manh(prev_end.first, prev_end.second, s_b.first, s_b.second);\n          pii e_a = embs[order3[a]].seq[4];\n          int new2 = (b == M - 1 ? 0\n                          : manh(e_a.first, e_a.second,\n                                 embs[order3[b + 1]].seq[0].first, embs[order3[b + 1]].seq[0].second));\n          int delta = new1 + new2 - old1 - old2;\n          if (delta < 0) {\n            reverse(order3.begin() + a, order3.begin() + b + 1);\n            improved = true;\n          }\n        }\n      }\n    } while (improved && ++passes < 200);\n  }\n  // Pick the best\n  int c1 = compute_connect(order1, embs, init_pos, M);\n  int c2 = compute_connect(order3, embs, init_pos, M);\n  vector<int> best_order = (c1 <= c2 ? order1 : order3);\n  // Build path\n  vector<pii> path;\n  for (int idx : best_order) {\n    for (auto p : embs[idx].seq) {\n      path.push_back(p);\n    }\n  }\n  // Output\n  for (auto [i, j] : path) {\n    cout << i << \" \" << j << '\\n';\n  }\n}","ahc030":"#include <bits/stdc++.h>\n#include <Eigen/Dense>\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M;\n  double eps;\n  cin >> N >> M >> eps;\n  vector<vector<pair<int, int>>> shapes(M);\n  for (int m = 0; m < M; ++m) {\n    int d;\n    cin >> d;\n    shapes[m].resize(d);\n    for (int l = 0; l < d; ++l) {\n      cin >> shapes[m][l].first >> shapes[m][l].second;\n    }\n  }\n  int NN = N * N;\n  int max_ops = 2 * NN;\n  int QQ = max_ops / 2;\n  mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n  // Phase 1: Divinations for density map\n  vector<vector<int>> subsets(QQ);\n  vector<double> ys(QQ);\n  for (int q = 0; q < QQ; ++q) {\n    vector<int> all_cells(NN);\n    iota(all_cells.begin(), all_cells.end(), 0);\n    shuffle(all_cells.begin(), all_cells.end(), rng);\n    int kk = NN / 2;\n    subsets[q].reserve(kk);\n    for (int t = 0; t < kk; ++t) {\n      subsets[q].push_back(all_cells[t]);\n    }\n    cout << \"q \" << kk;\n    for (int c : subsets[q]) {\n      int i = c / N, j = c % N;\n      cout << \" \" << i << \" \" << j;\n    }\n    cout << endl;\n    cout.flush();\n    int y;\n    cin >> y;\n    ys[q] = y;\n  }\n\n  // Build A and solve LS\n  MatrixXd A(QQ, NN);\n  A.setZero();\n  vector<int> ks(QQ);\n  for (int q = 0; q < QQ; ++q) {\n    ks[q] = subsets[q].size();\n    for (int c : subsets[q]) {\n      A(q, c) = 1.0;\n    }\n  }\n  double alpha = 1.0 - 2 * eps;\n  VectorXd sh(QQ);\n  for (int q = 0; q < QQ; ++q) {\n    double bq = eps * ks[q];\n    double corr = (ys[q] - bq) / alpha;\n    sh(q) = max(0.0, corr);\n  }\n  ColPivHouseholderQR<MatrixXd> decomp(A);\n  VectorXd vhat = decomp.solve(sh);\n  vector<double> vhat_grid(NN);\n  for (int c = 0; c < NN; ++c) {\n    vhat_grid[c] = max(0.0, vhat(c));\n  }\n\n  // Compute top placements\n  struct Placement {\n    int di, dj;\n    double score;\n  };\n  vector<vector<Placement>> top_placements(M);\n  int L = 20;\n  for (int m = 0; m < M; ++m) {\n    const auto& shp = shapes[m];\n    int d = shp.size();\n    int h = 0, w = 0;\n    for (auto [ii, jj] : shp) {\n      h = max(h, ii);\n      w = max(w, jj);\n    }\n    int ndi = N - h;\n    int ndj = N - w;\n    vector<tuple<double, int, int>> cand;\n    for (int di = 0; di < ndi; ++di) {\n      for (int dj = 0; dj < ndj; ++dj) {\n        double sc = 0.0;\n        for (auto [ri, rj] : shp) {\n          int x = di + ri;\n          int y = dj + rj;\n          sc += vhat_grid[x * N + y];\n        }\n        double avg_sc = sc / d;\n        cand.emplace_back(-avg_sc, di, dj);\n      }\n    }\n    sort(cand.begin(), cand.end());\n    top_placements[m].reserve(L);\n    int tk = min(L, (int)cand.size());\n    for (int l = 0; l < tk; ++l) {\n      auto [_, di, dj] = cand[l];\n      top_placements[m].push_back({di, dj, -get<0>(cand[l])});\n    }\n  }\n\n  // Order fields by size desc\n  vector<int> order(M);\n  iota(order.begin(), order.end(), 0);\n  sort(order.begin(), order.end(), [&](int a, int b) {\n    return shapes[a].size() > shapes[b].size();\n  });\n\n  // Beam search\n  struct State {\n    double score;\n    vector<int> choice;\n  };\n  const int B = 200;\n  vector<State> current_beam;\n  current_beam.reserve(B);\n  current_beam.emplace_back();\n  current_beam.back().choice.assign(M, -1);\n  current_beam.back().score = 0.0;\n  double lambda = 0.5;\n  vector<vector<int>> temp_cover(N, vector<int>(N));\n  for (int s = 0; s < M; ++s) {\n    int fld = order[s];\n    vector<State> next_beam;\n    next_beam.reserve(current_beam.size() * L * 2);\n    for (const auto& st : current_beam) {\n      for (size_t l = 0; l < top_placements[fld].size(); ++l) {\n        State nst = st;\n        nst.choice[fld] = l;\n        // compute cover\n        for (int i = 0; i < N; ++i)\n          fill(temp_cover[i].begin(), temp_cover[i].end(), 0);\n        for (int ff = 0; ff < M; ++ff) {\n          int cl = nst.choice[ff];\n          if (cl != -1) {\n            const auto& pl = top_placements[ff][cl];\n            const auto& shp = shapes[ff];\n            for (auto [ri, rj] : shp) {\n              int x = pl.di + ri;\n              int y = pl.dj + rj;\n              temp_cover[x][y]++;\n            }\n          }\n        }\n        double sc = 0.0;\n        for (int i = 0; i < N; ++i) {\n          for (int j = 0; j < N; ++j) {\n            int cv = temp_cover[i][j];\n            double vh = vhat_grid[i * N + j];\n            sc += vh * cv - lambda * cv * cv;\n          }\n        }\n        nst.score = sc;\n        next_beam.push_back(std::move(nst));\n      }\n    }\n    // sort desc\n    sort(next_beam.begin(), next_beam.end(),\n         [](const State& aa, const State& bb) { return aa.score > bb.score; });\n    current_beam.clear();\n    current_beam.reserve(B);\n    int nb = min(B, (int)next_beam.size());\n    for (int bi = 0; bi < nb; ++bi) {\n      current_beam.push_back(std::move(next_beam[bi]));\n    }\n  }\n\n  // Best state\n  const State& best = current_beam[0];\n\n  // Compute union\n  set<pair<int, int>> union_set;\n  for (int ff = 0; ff < M; ++ff) {\n    int cl = best.choice[ff];\n    if (cl == -1) continue;\n    const auto& pl = top_placements[ff][cl];\n    const auto& shp = shapes[ff];\n    for (auto [ri, rj] : shp) {\n      union_set.emplace(pl.di + ri, pl.dj + rj);\n    }\n  }\n  vector<pair<int, int>> ans(union_set.begin(), union_set.end());\n\n  // Guess\n  cout << \"a \" << ans.size();\n  for (auto [i, j] : ans) {\n    cout << \" \" << i << \" \" << j;\n  }\n  cout << endl;\n  cout.flush();\n  int ver;\n  cin >> ver;\n  if (ver == 1) {\n    return 0;\n  }\n  // Fallback: drill all\n  vector<pair<int, int>> all_oil;\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      cout << \"q 1 \" << i << \" \" << j << endl;\n      cout.flush();\n      int vv;\n      cin >> vv;\n      if (vv > 0) {\n        all_oil.emplace_back(i, j);\n      }\n    }\n  }\n  cout << \"a \" << all_oil.size();\n  for (auto [i, j] : all_oil) {\n    cout << \" \" << i << \" \" << j;\n  }\n  cout << endl;\n  cout.flush();\n  return 0;\n}","ahc031":"","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll MOD = 998244353LL;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N = 9, M = 20, K = 81;\n  vector<vector<ll>> A(N, vector<ll>(N));\n  for (int i = 0; i < N; i++)\n    for (int j = 0; j < N; j++)\n      cin >> A[i][j];\n  vector<vector<vector<ll>>> stamps(M, vector<vector<ll>>(3, vector<ll>(3)));\n  for (int m = 0; m < M; m++) {\n    for (int i = 0; i < 3; i++)\n      for (int j = 0; j < 3; j++)\n        cin >> stamps[m][i][j];\n  }\n  vector<vector<ll>> current = A;\n  vector<tuple<int, int, int>> ops;\n  while ((int)ops.size() < K) {\n    ll best_delta = 0;\n    int best_m = -1, best_p = -1, best_q = -1;\n    for (int m = 0; m < M; m++) {\n      for (int p = 0; p <= 6; p++) {\n        for (int q = 0; q <= 6; q++) {\n          ll delta = 0;\n          for (int di = 0; di < 3; di++) {\n            for (int dj = 0; dj < 3; dj++) {\n              int x = p + di, y = q + dj;\n              ll s = stamps[m][di][dj];\n              ll r = current[x][y];\n              ll nr = (r + s) % MOD;\n              delta += nr - r;\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 (best_delta <= 0) break;\n    ops.emplace_back(best_m, best_p, best_q);\n    for (int di = 0; di < 3; di++) {\n      for (int dj = 0; dj < 3; dj++) {\n        int x = best_p + di, y = best_q + dj;\n        ll s = stamps[best_m][di][dj];\n        current[x][y] = (current[x][y] + s) % MOD;\n      }\n    }\n  }\n  cout << ops.size() << '\\n';\n  for (auto [m, p, q] : ops) {\n    cout << m << ' ' << p << ' ' << q << '\\n';\n  }\n}","ahc033":"","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<string> get_moves(int r1, int c1, int r2, int c2) {\n    vector<string> res;\n    int dr = r2 - r1;\n    int dc = c2 - c1;\n    string vdir = \"\";\n    if (dr > 0) vdir = \"D\";\n    else if (dr < 0) vdir = \"U\";\n    string hdir = \"\";\n    if (dc > 0) hdir = \"R\";\n    else if (dc < 0) hdir = \"L\";\n    for (int i = 0; i < abs(dr); ++i) {\n        res.push_back(vdir);\n    }\n    for (int i = 0; i < abs(dc); ++i) {\n        res.push_back(hdir);\n    }\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    cin >> N;\n    vector<vector<int>> height(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> height[i][j];\n        }\n    }\n    vector<string> ops;\n    int cur_r = 0, cur_c = 0;\n    long long current_load = 0;\n    const double K = 30.0;\n    while (ops.size() < 95000) {\n        // check if done\n        bool is_done = (current_load == 0);\n        if (is_done) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (height[i][j] != 0) {\n                        is_done = false;\n                        goto next;\n                    }\n                }\n            }\n        }\n    next:;\n        if (is_done) break;\n\n        double best_score = 1e100;\n        int best_r = -1, best_c = -1;\n        if (current_load > 0) {\n            // find best sink (h < 0)\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (height[i][j] < 0) {\n                        double dist = abs(i - cur_r) + abs(j - cur_c);\n                        double needd = -height[i][j];\n                        double score = dist + K / needd;\n                        if (score < best_score) {\n                            best_score = score;\n                            best_r = i;\n                            best_c = j;\n                        }\n                    }\n                }\n            }\n        } else {\n            // find best source (h > 0)\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (height[i][j] > 0) {\n                        double dist = abs(i - cur_r) + abs(j - cur_c);\n                        double amtd = height[i][j];\n                        double score = dist + K / amtd;\n                        if (score < best_score) {\n                            best_score = score;\n                            best_r = i;\n                            best_c = j;\n                        }\n                    }\n                }\n            }\n        }\n        if (best_r == -1) break;\n\n        // move\n        auto path = get_moves(cur_r, cur_c, best_r, best_c);\n        for (auto& p : path) {\n            ops.push_back(p);\n        }\n        cur_r = best_r;\n        cur_c = best_c;\n\n        // act\n        if (current_load > 0) {\n            // unload\n            long long need = -(long long)height[best_r][best_c];\n            long long d = min(current_load, need);\n            ops.push_back(\"-\" + to_string(d));\n            height[best_r][best_c] += (int)d;\n            current_load -= d;\n        } else {\n            // load\n            long long d = height[best_r][best_c];\n            ops.push_back(\"+\" + to_string(d));\n            height[best_r][best_c] -= (int)d;\n            current_load += d;\n        }\n    }\n    for (auto& s : ops) {\n        cout << s << '\\n';\n    }\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int N, M, T;\n    cin >> N >> M >> T;\n    const int P = N * N; // 36\n    const int S = 2 * N * (N - 1); // 60\n    vector<vector<int>> cur(S, vector<int>(M));\n    for (int k = 0; k < S; k++) {\n        for (int j = 0; j < M; j++) {\n            cin >> cur[k][j];\n        }\n    }\n\n    auto pid = [N](int i, int j) { return i * N + j; };\n\n    // adjacency list for positions 0..35\n    vector<vector<int>> adj(P);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N - 1; j++) {\n            int u = pid(i, j), v = pid(i, j + 1);\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n    }\n    for (int i = 0; i < N - 1; i++) {\n        for (int j = 0; j < N; j++) {\n            int u = pid(i, j), v = pid(i + 1, j);\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n    }\n\n    // edges for initial score computation\n    vector<pair<int, int>> edges;\n    for (int u = 0; u < P; u++) {\n        for (int v : adj[u]) {\n            if (v > u) {\n                edges.emplace_back(u, v);\n            }\n        }\n    }\n    assert((int)edges.size() == S);\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> uni_pos(0, P - 1);\n    uniform_real_distribution<double> uni_prob(0.0, 1.0);\n\n    for (int t = 0; t < T; t++) {\n        // compute values\n        vector<long long> val(S, 0);\n        for (int k = 0; k < S; k++) {\n            for (int j = 0; j < M; j++) {\n                val[k] += cur[k][j];\n            }\n        }\n\n        // top 36 global indices, sorted by val desc, then index\n        vector<int> idx(S);\n        iota(idx.begin(), idx.end(), 0);\n        sort(idx.begin(), idx.end(), [&](int a, int b) {\n            if (val[a] != val[b]) return val[a] > val[b];\n            return a < b;\n        });\n        vector<int> top36;\n        for (int i = 0; i < P; i++) top36.push_back(idx[i]);\n\n        // local seeds values\n        vector<vector<int>> loc(P, vector<int>(M));\n        vector<long long> local_val(P);\n        for (int li = 0; li < P; li++) {\n            int gi = top36[li];\n            local_val[li] = val[gi];\n            for (int m = 0; m < M; m++) {\n                loc[li][m] = cur[gi][m];\n            }\n        }\n\n        // sort local ids by local_val desc\n        vector<int> local_order(P);\n        iota(local_order.begin(), local_order.end(), 0);\n        sort(local_order.begin(), local_order.end(), [&](int a, int b) {\n            if (local_val[a] != local_val[b]) return local_val[a] > local_val[b];\n            return a < b;\n        });\n\n        // initial assignment: row-major order of sorted local\n        vector<int> assignment(P);\n        int pp = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                assignment[pid(i, j)] = local_order[pp++];\n            }\n        }\n\n        // supersum lambda\n        auto supersum = [&](int lid1, int lid2) -> int {\n            int s = 0;\n            for (int m = 0; m < M; m++) {\n                s += max(loc[lid1][m], loc[lid2][m]);\n            }\n            return s;\n        };\n\n        // initial score\n        long long score = 0;\n        for (auto [u, v] : edges) {\n            score += supersum(assignment[u], assignment[v]);\n        }\n\n        // SA parameters\n        const int MAX_ITER = 300000;\n        const double TEMP_START = 8000.0;\n        const double COOL_RATE = 0.9993;\n        double cur_temp = TEMP_START;\n\n        for (int iter = 0; iter < MAX_ITER; iter++) {\n            int a = uni_pos(rng);\n            int b = uni_pos(rng);\n            if (a == b) continue;\n\n            int sidA = assignment[a];\n            int sidB = assignment[b];\n\n            long long delta = 0;\n\n            // neighbors of a except b\n            for (int n : adj[a]) {\n                if (n == b) continue;\n                int sidN = assignment[n];\n                delta += supersum(sidB, sidN) - supersum(sidA, sidN);\n            }\n            // neighbors of b except a\n            for (int n : adj[b]) {\n                if (n == a) continue;\n                int sidN = assignment[n];\n                delta += supersum(sidA, sidN) - supersum(sidB, sidN);\n            }\n\n            bool accept = false;\n            if (delta >= 0) {\n                accept = true;\n            } else {\n                double p = exp((double)delta / cur_temp);\n                if (uni_prob(rng) < p) {\n                    accept = true;\n                }\n            }\n            if (accept) {\n                swap(assignment[a], assignment[b]);\n                score += delta;\n            }\n\n            cur_temp *= COOL_RATE;\n            if (cur_temp < 1.0) break;\n        }\n\n        // build grid\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                int pos = pid(i, j);\n                int lid = assignment[pos];\n                grid[i][j] = top36[lid];\n            }\n        }\n\n        // output\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << grid[i][j];\n                if (j + 1 < N) cout << \" \";\n                else cout << \"\\n\";\n            }\n        }\n        cout.flush();\n\n        // read new seeds\n        for (int k = 0; k < S; k++) {\n            for (int m = 0; m < M; m++) {\n                cin >> cur[k][m];\n            }\n        }\n    }\n    return 0;\n}","ahc038":"","ahc039":"","ahc040":"","ahc041":"","ahc042":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    \n    int N = 20;\n    vector<string> board(N);\n    vector<vector<bool>> has_x(N, vector<bool>(N, false));\n    int total_x = 0;\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                has_x[i][j] = true;\n                ++total_x;\n            }\n        }\n    }\n    \n    // Precompute kmax for each\n    vector<int> row_left_kmax(N), row_right_kmax(N);\n    for (int r = 0; r < N; ++r) {\n        int first_o = N;\n        for (int j = 0; j < N; ++j) {\n            if (board[r][j] == 'o') {\n                first_o = j;\n                break;\n            }\n        }\n        row_left_kmax[r] = first_o;\n        \n        int last_o = -1;\n        for (int j = N - 1; j >= 0; --j) {\n            if (board[r][j] == 'o') {\n                last_o = j;\n                break;\n            }\n        }\n        row_right_kmax[r] = N - (last_o + 1);\n    }\n    \n    vector<int> col_up_kmax(N), col_down_kmax(N);\n    for (int c = 0; c < N; ++c) {\n        int first_o = N;\n        for (int i = 0; i < N; ++i) {\n            if (board[i][c] == 'o') {\n                first_o = i;\n                break;\n            }\n        }\n        col_up_kmax[c] = first_o;\n        \n        int last_o = -1;\n        for (int i = N - 1; i >= 0; --i) {\n            if (board[i][c] == 'o') {\n                last_o = i;\n                break;\n            }\n        }\n        col_down_kmax[c] = N - (last_o + 1);\n    }\n    \n    vector<pair<char, int>> operations;\n    int rem_x = total_x;\n    \n    while (rem_x > 0) {\n        double best_ratio = -1.0;\n        int best_cnt = 0;\n        int best_kk = 0;\n        char best_d = ' ';\n        int best_p = -1;\n        \n        // Row lefts\n        for (int r = 0; r < N; ++r) {\n            int kmaxx = row_left_kmax[r];\n            for (int kk = 1; kk <= kmaxx; ++kk) {\n                int cnt = 0;\n                for (int j = 0; j < kk; ++j) {\n                    if (has_x[r][j]) ++cnt;\n                }\n                if (cnt == 0) continue;\n                double ratio = static_cast<double>(cnt) / kk;\n                bool better = false;\n                if (ratio > best_ratio + 1e-9) {\n                    better = true;\n                } else if (abs(ratio - best_ratio) < 1e-9) {\n                    if (cnt > best_cnt || (cnt == best_cnt && kk < best_kk)) {\n                        better = true;\n                    }\n                }\n                if (better) {\n                    best_ratio = ratio;\n                    best_cnt = cnt;\n                    best_kk = kk;\n                    best_d = 'L';\n                    best_p = r;\n                }\n            }\n        }\n        \n        // Row rights\n        for (int r = 0; r < N; ++r) {\n            int kmaxx = row_right_kmax[r];\n            for (int kk = 1; kk <= kmaxx; ++kk) {\n                int cnt = 0;\n                int startj = N - kk;\n                for (int j = startj; j < N; ++j) {\n                    if (has_x[r][j]) ++cnt;\n                }\n                if (cnt == 0) continue;\n                double ratio = static_cast<double>(cnt) / kk;\n                bool better = false;\n                if (ratio > best_ratio + 1e-9) {\n                    better = true;\n                } else if (abs(ratio - best_ratio) < 1e-9) {\n                    if (cnt > best_cnt || (cnt == best_cnt && kk < best_kk)) {\n                        better = true;\n                    }\n                }\n                if (better) {\n                    best_ratio = ratio;\n                    best_cnt = cnt;\n                    best_kk = kk;\n                    best_d = 'R';\n                    best_p = r;\n                }\n            }\n        }\n        \n        // Col ups\n        for (int c = 0; c < N; ++c) {\n            int kmaxx = col_up_kmax[c];\n            for (int kk = 1; kk <= kmaxx; ++kk) {\n                int cnt = 0;\n                for (int i = 0; i < kk; ++i) {\n                    if (has_x[i][c]) ++cnt;\n                }\n                if (cnt == 0) continue;\n                double ratio = static_cast<double>(cnt) / kk;\n                bool better = false;\n                if (ratio > best_ratio + 1e-9) {\n                    better = true;\n                } else if (abs(ratio - best_ratio) < 1e-9) {\n                    if (cnt > best_cnt || (cnt == best_cnt && kk < best_kk)) {\n                        better = true;\n                    }\n                }\n                if (better) {\n                    best_ratio = ratio;\n                    best_cnt = cnt;\n                    best_kk = kk;\n                    best_d = 'U';\n                    best_p = c;\n                }\n            }\n        }\n        \n        // Col downs\n        for (int c = 0; c < N; ++c) {\n            int kmaxx = col_down_kmax[c];\n            for (int kk = 1; kk <= kmaxx; ++kk) {\n                int cnt = 0;\n                int starti = N - kk;\n                for (int i = starti; i < N; ++i) {\n                    if (has_x[i][c]) ++cnt;\n                }\n                if (cnt == 0) continue;\n                double ratio = static_cast<double>(cnt) / kk;\n                bool better = false;\n                if (ratio > best_ratio + 1e-9) {\n                    better = true;\n                } else if (abs(ratio - best_ratio) < 1e-9) {\n                    if (cnt > best_cnt || (cnt == best_cnt && kk < best_kk)) {\n                        better = true;\n                    }\n                }\n                if (better) {\n                    best_ratio = ratio;\n                    best_cnt = cnt;\n                    best_kk = kk;\n                    best_d = 'D';\n                    best_p = c;\n                }\n            }\n        }\n        \n        // Apply\n        assert(best_d != ' ');\n        char opp_d;\n        if (best_d == 'L') opp_d = 'R';\n        else if (best_d == 'R') opp_d = 'L';\n        else if (best_d == 'U') opp_d = 'D';\n        else opp_d = 'U';\n        \n        for (int t = 0; t < best_kk; ++t) {\n            operations.emplace_back(best_d, best_p);\n        }\n        for (int t = 0; t < best_kk; ++t) {\n            operations.emplace_back(opp_d, best_p);\n        }\n        \n        // Mark covered\n        if (best_d == 'L' || best_d == 'R') {\n            int r = best_p;\n            if (best_d == 'L') {\n                for (int j = 0; j < best_kk; ++j) {\n                    if (has_x[r][j]) {\n                        has_x[r][j] = false;\n                        --rem_x;\n                    }\n                }\n            } else {\n                int start = N - best_kk;\n                for (int j = start; j < N; ++j) {\n                    if (has_x[r][j]) {\n                        has_x[r][j] = false;\n                        --rem_x;\n                    }\n                }\n            }\n        } else {\n            int c = best_p;\n            if (best_d == 'U') {\n                for (int i = 0; i < best_kk; ++i) {\n                    if (has_x[i][c]) {\n                        has_x[i][c] = false;\n                        --rem_x;\n                    }\n                }\n            } else {\n                int start = N - best_kk;\n                for (int i = start; i < N; ++i) {\n                    if (has_x[i][c]) {\n                        has_x[i][c] = false;\n                        --rem_x;\n                    }\n                }\n            }\n        }\n    }\n    \n    // Output\n    for (const auto& op : operations) {\n        cout << op.first << ' ' << op.second << '\\n';\n    }\n    \n    return 0;\n}","ahc044":"","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing pii = pair<int, int>;\nusing vpii = vector<pii>;\n\nvoid get_mst(const vector<int>& C, vpii& mst_edges) {\n  int l = C.size();\n  cout << \"? \" << l;\n  for (int u : C) cout << \" \" << u;\n  cout << endl << flush;\n  mst_edges.resize(l - 1);\n  for (int i = 0; i < l - 1; i++) {\n    int a, b;\n    cin >> a >> b;\n    if (a > b) swap(a, b);\n    mst_edges[i] = {a, b};\n  }\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, Q, L, W;\n  cin >> N >> M >> Q >> L >> W;\n  vi G(M);\n  for (auto& g : G) cin >> g;\n  vi lx(N), rx(N), ly(N), ry(N);\n  vi cx(N), cy(N);\n  for (int i = 0; i < N; i++) {\n    cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    cx[i] = (lx[i] + rx[i]) / 2;\n    cy[i] = (ly[i] + ry[i]) / 2;\n  }\n  vi order(N);\n  iota(order.begin(), order.end(), 0);\n  auto cmp = [&](int i, int j) {\n    if (cx[i] != cx[j]) return cx[i] < cx[j];\n    return cy[i] < cy[j];\n  };\n  sort(order.begin(), order.end(), cmp);\n  vi cum(M + 1, 0);\n  for (int i = 1; i <= M; i++) {\n    cum[i] = cum[i - 1] + G[i - 1];\n  }\n  vvi groups(M);\n  for (int m = 0; m < M; m++) {\n    groups[m].assign(order.begin() + cum[m], order.begin() + cum[m + 1]);\n  }\n  vector<vpii> all_trees(M);\n  for (int m = 0; m < M; m++) {\n    int g = groups[m].size();\n    if (g < 2) {\n      all_trees[m] = {};\n      continue;\n    }\n    vi C = groups[m];\n    vpii candidates;\n    if (g <= L) {\n      vpii temp;\n      get_mst(C, temp);\n      candidates = std::move(temp);\n    } else {\n      int wsz = L;\n      int step = L - 1;\n      int pos = 0;\n      while (pos + wsz <= g) {\n        vi sub(C.begin() + pos, C.begin() + pos + wsz);\n        vpii temp;\n        get_mst(sub, temp);\n        for (auto e : temp) candidates.push_back(e);\n        pos += step;\n      }\n      if (pos < g) {\n        int rem = g - pos;\n        if (rem >= 2) {\n          int lsz = min(wsz, rem);\n          vi sub(C.begin() + pos, C.begin() + pos + lsz);\n          vpii temp;\n          get_mst(sub, temp);\n          for (auto e : temp) candidates.push_back(e);\n        }\n      }\n    }\n    if (g <= L) {\n      all_trees[m] = std::move(candidates);\n      continue;\n    }\n    // large group: add path edges\n    for (int i = 0; i < g - 1; i++) {\n      int u = C[i], v = C[i + 1];\n      if (u > v) swap(u, v);\n      candidates.emplace_back(u, v);\n    }\n    // build adj local\n    vi local_id(N, -1);\n    for (int loc = 0; loc < g; loc++) {\n      local_id[C[loc]] = loc;\n    }\n    vvi adj(g);\n    for (auto [a, b] : candidates) {\n      int la = local_id[a];\n      int lb = local_id[b];\n      adj[la].push_back(lb);\n      adj[lb].push_back(la);\n    }\n    // BFS tree from 0\n    vi parent(g, -1);\n    vb vis(g, false);\n    queue<int> qu;\n    qu.push(0);\n    vis[0] = true;\n    int visited_cnt = 1;\n    while (!qu.empty()) {\n      int u = qu.front();\n      qu.pop();\n      for (int v : adj[u]) {\n        if (!vis[v]) {\n          vis[v] = true;\n          parent[v] = u;\n          qu.push(v);\n          visited_cnt++;\n        }\n      }\n    }\n    // build tree edges\n    vpii tree_edges;\n    for (int loc = 1; loc < g; loc++) {\n      int pv = parent[loc];\n      int gu = C[loc], gpv = C[pv];\n      if (gu > gpv) swap(gu, gpv);\n      tree_edges.emplace_back(gu, gpv);\n    }\n    all_trees[m] = std::move(tree_edges);\n  }\n  cout << \"!\" << endl;\n  for (int m = 0; m < M; m++) {\n    for (size_t i = 0; i < groups[m].size(); ++i) {\n      if (i > 0) cout << \" \";\n      cout << groups[m][i];\n    }\n    cout << '\\n';\n    for (const auto& e : all_trees[m]) {\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\nconst int INF = 1e9 + 5;\nint dr[4] = {-1, 1, 0, 0};\nint dc[4] = {0, 0, -1, 1};\nchar dirch[4] = {'U', 'D', 'L', 'R'};\n\nvector<pair<char, char>> get_path(int sr, int sc, int tr, int tc, int N) {\n  int NN = N * N;\n  vector<int> dist(NN, INF);\n  vector<int> prevv(NN, -1);\n  vector<char> pactt(NN, 0);\n  vector<char> pdirr(NN, 0);\n  int sid = sr * N + sc;\n  int tid = tr * N + tc;\n  dist[sid] = 0;\n  queue<int> q;\n  q.push(sid);\n  while (!q.empty()) {\n    int id = q.front();\n    q.pop();\n    int cr = id / N;\n    int cc = id % N;\n    // moves\n    for (int d = 0; d < 4; d++) {\n      int nr = cr + dr[d];\n      int nc = cc + dc[d];\n      if (nr >= 0 && nr < N && nc >= 0 && nc < N) {\n        int nid = nr * N + nc;\n        if (dist[nid] == INF) {\n          dist[nid] = dist[id] + 1;\n          prevv[nid] = id;\n          pactt[nid] = 'M';\n          pdirr[nid] = dirch[d];\n          q.push(nid);\n        }\n      }\n    }\n    // slides\n    for (int d = 0; d < 4; d++) {\n      int er = cr;\n      int ec = cc;\n      int ddr = dr[d];\n      int ddc = dc[d];\n      while (true) {\n        int nr = er + ddr;\n        int nc = ec + ddc;\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N) break;\n        er = nr;\n        ec = nc;\n      }\n      int eid = er * N + ec;\n      if (dist[eid] == INF) {\n        dist[eid] = dist[id] + 1;\n        prevv[eid] = id;\n        pactt[eid] = 'S';\n        pdirr[eid] = dirch[d];\n        q.push(eid);\n      }\n    }\n  }\n  // reconstruct\n  vector<pair<char, char>> path;\n  if (dist[tid] == INF) return path;\n  int cur = tid;\n  while (cur != sid) {\n    char a = pactt[cur];\n    char dd = pdirr[cur];\n    path.emplace_back(a, dd);\n    cur = prevv[cur];\n  }\n  reverse(path.begin(), path.end());\n  return path;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M;\n  cin >> N >> M;\n  vector<pair<int, int>> pos(M);\n  for (int i = 0; i < M; i++) {\n    cin >> pos[i].first >> pos[i].second;\n  }\n  int cr = pos[0].first;\n  int cc = pos[0].second;\n  vector<pair<char, char>> total;\n  for (int k = 1; k < M; k++) {\n    auto pth = get_path(cr, cc, pos[k].first, pos[k].second, N);\n    for (auto pr : pth) {\n      total.push_back(pr);\n    }\n    cr = pos[k].first;\n    cc = pos[k].second;\n  }\n  for (auto [a, d] : total) {\n    cout << a << ' ' << d << '\\n';\n  }\n  return 0;\n}"},"2":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing A4 = array<int, 4>;\nusing u32 = uint32_t;\n\nbool overlaps(const vector<A4>& occ, int a, int b, int c, int d) {\n  for (const auto& p : occ) {\n    if (a < p[2] && c > p[0] && b < p[3] && d > p[1]) return true;\n  }\n  return false;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n;\n  cin >> n;\n  vector<int> X(n), Y(n), R(n);\n  for (int i = 0; i < n; i++) {\n    cin >> X[i] >> Y[i] >> R[i];\n  }\n  vector<int> order(n);\n  iota(order.begin(), order.end(), 0);\n  sort(order.begin(), order.end(), [&](int i, int j) {\n    if (R[i] != R[j]) return R[i] > R[j];\n    return X[i] < X[j];\n  });\n  vector<A4> occupied;\n  vector<A4> solution(n);\n  for (int kk = 0; kk < n; kk++) {\n    int i = order[kk];\n    int xi = X[i], yi = Y[i];\n    ll rri = R[i];\n    // minimal rect\n    int aa = xi, bb = yi, cc = xi + 1, dd = yi + 1;\n    bool min_free = !overlaps(occupied, aa, bb, cc, dd);\n    if (min_free) {\n      // expand\n      int cura = xi, curb = yi, curc = xi + 1, curd = yi + 1;\n      const int MAX_ITER = 200;\n      for (int iter = 0; iter < MAX_ITER; iter++) {\n        // d_left\n        int d_left = 0;\n        {\n          int lo = 0, hi = cura;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int na = cura - mid;\n            if (na >= 0 && !overlaps(occupied, na, curb, curc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_left = lo;\n        }\n        // d_right\n        int d_right = 0;\n        {\n          int lo = 0, hi = 10000 - curc;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nc = curc + mid;\n            if (nc <= 10000 && !overlaps(occupied, cura, curb, nc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_right = lo;\n        }\n        // d_bot\n        int d_bot = 0;\n        {\n          int lo = 0, hi = curb;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nb = curb - mid;\n            if (nb >= 0 && !overlaps(occupied, cura, nb, curc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_bot = lo;\n        }\n        // d_top\n        int d_top = 0;\n        {\n          int lo = 0, hi = 10000 - curd;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nt = curd + mid;\n            if (nt <= 10000 && !overlaps(occupied, cura, curb, curc, nt)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_top = lo;\n        }\n        // gains\n        ll h = (ll)(curd - curb);\n        ll w = (ll)(curc - cura);\n        ll gain_l = d_left * h;\n        ll gain_r = d_right * h;\n        ll gain_b = d_bot * w;\n        ll gain_t = d_top * w;\n        ll maxg = max({gain_l, gain_r, gain_b, gain_t});\n        if (maxg == 0) break;\n        // choose dir prefer l > r > b > t\n        int chdir = -1;\n        if (gain_l == maxg) chdir = 0;\n        else if (gain_r == maxg) chdir = 1;\n        else if (gain_b == maxg) chdir = 2;\n        else chdir = 3;\n        // extend\n        if (chdir == 0) cura -= d_left;\n        else if (chdir == 1) curc += d_right;\n        else if (chdir == 2) curb -= d_bot;\n        else curd += d_top;\n      }\n      // now max rect [cura,curc) [curb,curd)\n      int Wma = curc - cura;\n      int Hma = curd - curb;\n      // best subrect area\n      double bestp = -1.0;\n      int besw = 1, besh = 1;\n      for (int ww = 1; ww <= Wma; ++ww) {\n        double hhd = (double)rri / ww;\n        int hh = round(hhd);\n        vector<int> cand = {hh - 1, hh, hh + 1};\n        for (int hht : cand) {\n          hht = max(1, min(Hma, hht));\n          ll ss = (ll)ww * hht;\n          double ra = min(rri, ss) * 1.0 / max(rri, ss);\n          double pp = 2 * ra - ra * ra;\n          if (pp > bestp) {\n            bestp = pp;\n            besw = ww;\n            besh = hht;\n          }\n        }\n      }\n      // position subrect inside max, upper-right at (xi+1, yi+1)\n      int a2 = max(cura, xi + 1 - besw);\n      int c2 = a2 + besw;\n      int b2 = max(curb, yi + 1 - besh);\n      int d2 = b2 + besh;\n      solution[i] = {a2, b2, c2, d2};\n      occupied.push_back(solution[i]);\n    } else {\n      // dummy 1x1 somewhere free\n      bool found = false;\n      u32 state = static_cast<u32>(i) * 1103515245u + 12345u;\n      const int MAX_ATT = 30000;\n      for (int att = 0; att < MAX_ATT; att++) {\n        u32 st = state;\n        state = state * 1103515245u + 12345u;\n        int px = static_cast<int>((st >> 16) % 10000u);\n        int py = static_cast<int>(st % 10000u);\n        if (!overlaps(occupied, px, py, px + 1, py + 1)) {\n          solution[i] = {px, py, px + 1, py + 1};\n          occupied.push_back(solution[i]);\n          found = true;\n          break;\n        }\n      }\n      if (!found) {\n        // emergency scan\n        found = false;\n        for (int px = 9999; px >= 0 && !found; px -= 5) {\n          for (int py = 9999; py >= 0 && !found; py -= 5) {\n            if (!overlaps(occupied, px, py, px + 1, py + 1)) {\n              solution[i] = {px, py, px + 1, py + 1};\n              occupied.push_back(solution[i]);\n              found = true;\n              break;\n            }\n          }\n        }\n      }\n      if (!found) {\n        // ultimate last resort\n        solution[i] = {0, 0, 1, 1};\n        occupied.push_back(solution[i]);  // push even if overlaps\n      }\n    }\n  }\n  for (int i = 0; i < n; i++) {\n    auto& re = solution[i];\n    cout << re[0] << \" \" << re[1] << \" \" << re[2] << \" \" << re[3] << \"\\n\";\n  }\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int si, sj;\n  cin >> si >> sj;\n  vector<vector<int>> T(50, vector<int>(50));\n  int maxt = 0;\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) {\n      cin >> T[i][j];\n      if (T[i][j] > maxt) maxt = T[i][j];\n    }\n  int M = maxt + 1;\n  vector<vector<int>> P(50, vector<int>(50));\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) cin >> P[i][j];\n\n  const int dr[] = {-1, 1, 0, 0};\n  const int dc[] = {0, 0, -1, 1};\n  const char dirchar[] = {'U', 'D', 'L', 'R'};\n\n  string best_str = \"\";\n  long long best_sc = -1;\n  const int TRIALS = 1024;\n  const int MAX_TOP = 3;\n  srand(time(NULL));\n\n  for (int trial = 0; trial < TRIALS; trial++) {\n    vector<char> vis(M, 0);\n    int st = T[si][sj];\n    vis[st] = 1;\n    long long score = P[si][sj];\n    int cr = si, cc = sj;\n    string moves = \"\";\n    while (true) {\n      vector<tuple<int, int, int, int>> cands;\n      for (int d = 0; d < 4; d++) {\n        int nr = cr + dr[d];\n        int nc = cc + dc[d];\n        if (nr < 0 || nr >= 50 || nc < 0 || nc >= 50) continue;\n        int nt = T[nr][nc];\n        if (vis[nt]) continue;\n        int deg = 0;\n        for (int dd = 0; dd < 4; dd++) {\n          int mr = nr + dr[dd];\n          int mc = nc + dc[dd];\n          if (mr >= 0 && mr < 50 && mc >= 0 && mc < 50) {\n            int mt = T[mr][mc];\n            if (!vis[mt] && mt != nt) deg++;\n          }\n        }\n        int pp = P[nr][nc];\n        int hashh = nr * 51 + nc;\n        cands.emplace_back(deg, -pp, d, hashh);\n      }\n      size_t ncand = cands.size();\n      if (ncand == 0) break;\n      sort(cands.begin(), cands.end());\n      int nsel = min((int)ncand, MAX_TOP);\n      int pick = rand() % nsel;\n      auto [fdeg, fp, fdir, fhash] = cands[pick];\n      int nr = cr + dr[fdir];\n      int nc = cc + dc[fdir];\n      moves += dirchar[fdir];\n      vis[T[nr][nc]] = 1;\n      score += P[nr][nc];\n      cr = nr;\n      cc = nc;\n    }\n    if (score > best_sc) {\n      best_sc = score;\n      best_str = moves;\n    }\n  }\n  cout << best_str << '\\n';\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  const int N = 30;\n  auto nodef = [&](int i, int j) -> int { return i * N + j; };\n  auto geti = [&](int u) -> int { return u / N; };\n  auto getj = [&](int u) -> int { return u % N; };\n  vector<vector<double>> h(N, vector<double>(N - 1, 5000.0));\n  vector<vector<double>> vv(N - 1, vector<double>(N, 5000.0));\n  for (int q = 0; q < 1000; ++q) {\n    int si, sj, ti, tj;\n    cin >> si >> sj >> ti >> tj;\n    int ss = nodef(si, sj);\n    int tt = nodef(ti, tj);\n    vector<double> dist(N * N, 1e18);\n    vector<int> prevv(N * N, -1);\n    dist[ss] = 0.0;\n    priority_queue<pair<double, int>, vector<pair<double, int>>, greater<pair<double, int>>> pq;\n    pq.push({0.0, ss});\n    while (!pq.empty()) {\n      auto [cost, u] = pq.top();\n      pq.pop();\n      if (cost > dist[u]) continue;\n      int i = geti(u), j = getj(u);\n      // right\n      if (j < N - 1) {\n        int v = nodef(i, j + 1);\n        double w = h[i][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // left\n      if (j > 0) {\n        int v = nodef(i, j - 1);\n        double w = h[i][j - 1];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // down\n      if (i < N - 1) {\n        int v = nodef(i + 1, j);\n        double w = vv[i][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // up\n      if (i > 0) {\n        int v = nodef(i - 1, j);\n        double w = vv[i - 1][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n    }\n    double predicted = dist[tt];\n    // reconstruct path\n    vector<int> path_nodes;\n    for (int cur = tt; cur != ss; cur = prevv[cur]) {\n      path_nodes.push_back(cur);\n      assert(prevv[cur] != -1); // for safety, remove in prod\n    }\n    path_nodes.push_back(ss);\n    reverse(path_nodes.begin(), path_nodes.end());\n    // build path_str\n    string path_str;\n    for (size_t k = 0; k + 1 < path_nodes.size(); ++k) {\n      int u = path_nodes[k], v = path_nodes[k + 1];\n      int ui = geti(u), uj = getj(u), vi = geti(v), vj = getj(v);\n      int di = vi - ui, dj = vj - uj;\n      char ch;\n      if (di == -1 && dj == 0) ch = 'U';\n      else if (di == 1 && dj == 0) ch = 'D';\n      else if (di == 0 && dj == -1) ch = 'L';\n      else if (di == 0 && dj == 1) ch = 'R';\n      else assert(false); // error\n      path_str += ch;\n    }\n    cout << path_str << '\\n';\n    cout.flush();\n    int obs;\n    cin >> obs;\n    // update estimates multiplicatively\n    double factor = (predicted > 1e-9 ? (double)obs / predicted : 1.0);\n    int num_e = path_nodes.size() - 1;\n    for (int k = 0; k < num_e; ++k) {\n      int u = path_nodes[k], v = path_nodes[k + 1];\n      int ui = geti(u), uj = getj(u), vi = geti(v), vj = getj(v);\n      if (ui == vi) {  // horiz\n        int lj = min(uj, vj);\n        h[ui][lj] *= factor;\n        h[ui][lj] = max(200.0, min(20000.0, h[ui][lj]));\n      } else {  // vert\n        int ti_ = min(ui, vi);\n        vv[ti_][uj] *= factor;\n        vv[ti_][uj] = max(200.0, min(20000.0, vv[ti_][uj]));\n      }\n    }\n  }\n  return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N = 20;\nint M;\nstring SS[805];\nint Lens[805];\nchar grid[20][20];\nchar best_grid[20][20];\nchar chars[8] = {'A','B','C','D','E','F','G','H'};\n\nint get_covered(char g[20][20]) {\n  static char dblr[20][41];\n  static char dblc[20][41];\n  for (int r = 0; r < N; ++r) {\n    memcpy(dblr[r], g[r], N);\n    memcpy(dblr[r] + N, g[r], N);\n  }\n  for (int c = 0; c < N; ++c) {\n    for (int r = 0; r < N; ++r) dblc[c][r] = g[r][c];\n    memcpy(dblc[c] + N, dblc[c], N);\n  }\n  int cnt = 0;\n  for (int si = 0; si < M; ++si) {\n    int k = Lens[si];\n    const char* pat = SS[si].c_str();\n    bool ok = false;\n    // rows\n    for (int r = 0; r < N && !ok; ++r) {\n      const char* dbl = dblr[r];\n      for (int st = 0; st < N; ++st) {\n        bool match = true;\n        for (int p = 0; p < k; ++p) {\n          if (dbl[st + p] != pat[p]) {\n            match = false;\n            break;\n          }\n        }\n        if (match) {\n          ok = true;\n          break;\n        }\n      }\n    }\n    if (!ok) {\n      // cols\n      for (int c = 0; c < N && !ok; ++c) {\n        const char* dbl = dblc[c];\n        for (int st = 0; st < N; ++st) {\n          bool match = true;\n          for (int p = 0; p < k; ++p) {\n            if (dbl[st + p] != pat[p]) {\n              match = false;\n              break;\n            }\n          }\n          if (match) {\n            ok = true;\n            break;\n          }\n        }\n      }\n    }\n    if (ok) ++cnt;\n  }\n  return cnt;\n}\n\nvector<bool> get_covered_vec(char g[20][20]) {\n  static char dblr[20][41];\n  static char dblc[20][41];\n  for (int r = 0; r < N; ++r) {\n    memcpy(dblr[r], g[r], N);\n    memcpy(dblr[r] + N, g[r], N);\n  }\n  for (int c = 0; c < N; ++c) {\n    for (int r = 0; r < N; ++r) dblc[c][r] = g[r][c];\n    memcpy(dblc[c] + N, dblc[c], N);\n  }\n  vector<bool> cov(M, false);\n  for (int si = 0; si < M; ++si) {\n    int k = Lens[si];\n    const char* pat = SS[si].c_str();\n    bool ok = false;\n    // rows\n    for (int r = 0; r < N && !ok; ++r) {\n      const char* dbl = dblr[r];\n      for (int st = 0; st < N; ++st) {\n        bool match = true;\n        for (int p = 0; p < k; ++p) {\n          if (dbl[st + p] != pat[p]) {\n            match = false;\n            break;\n          }\n        }\n        if (match) {\n          ok = true;\n          break;\n        }\n      }\n    }\n    if (!ok) {\n      // cols\n      for (int c = 0; c < N && !ok; ++c) {\n        const char* dbl = dblc[c];\n        for (int st = 0; st < N; ++st) {\n          bool match = true;\n          for (int p = 0; p < k; ++p) {\n            if (dbl[st + p] != pat[p]) {\n              match = false;\n              break;\n            }\n          }\n          if (match) {\n            ok = true;\n            break;\n          }\n        }\n      }\n    }\n    cov[si] = ok;\n  }\n  return cov;\n}\n\nvoid do_sa() {\n  memcpy(best_grid, grid, sizeof(grid));\n  int best_c = get_covered(grid);\n  int curr_c = best_c;\n  double temp = 32.0;\n  double cool_rate = 0.9998;\n  int iters = 0;\n  const int max_iters = 2000000;\n  srand(time(NULL));\n  while (iters < max_iters && temp > 0.05 && curr_c < M) {\n    int ri = rand() % N;\n    int ci = rand() % N;\n    char old_ch = grid[ri][ci];\n    int ch_idx = rand() % 8;\n    char new_ch = chars[ch_idx];\n    if (new_ch == old_ch) continue;\n    grid[ri][ci] = new_ch;\n    int new_c = get_covered(grid);\n    double delta = new_c - curr_c;\n    bool accept = (delta > 0);\n    if (!accept && temp > 0) {\n      double prob = exp(delta / temp);\n      if (prob > ((double)rand() / RAND_MAX)) accept = true;\n    }\n    if (accept) {\n      curr_c = new_c;\n      if (curr_c > best_c) {\n        best_c = curr_c;\n        memcpy(best_grid, grid, sizeof(grid));\n      }\n    } else {\n      grid[ri][ci] = old_ch;\n    }\n    temp *= cool_rate;\n    ++iters;\n  }\n  // copy back best\n  memcpy(grid, best_grid, sizeof(grid));\n}\n\nint main() {\n  srand(42);\n  cin >> N >> M;\n  for (int i = 0; i < M; ++i) {\n    cin >> SS[i];\n    Lens[i] = SS[i].size();\n    fill(grid[i], grid[i] + N, '.');\n  }\n  // greedy passes\n  int passes = 0;\n  bool changed = true;\n  while (changed && passes++ < 20) {\n    changed = false;\n    auto cov = get_covered_vec(grid);\n    vector<int> unc;\n    for (int si = 0; si < M; ++si) {\n      if (!cov[si]) unc.push_back(si);\n    }\n    if (unc.empty()) break;\n    // sort unc by len desc\n    sort(unc.begin(), unc.end(), [](int a, int b) {\n      return Lens[a] > Lens[b];\n    });\n    for (int si : unc) {\n      const string& s = SS[si];\n      int k = Lens[si];\n      int best_cost = INT_MAX / 2;\n      int best_ndot = -1;\n      int best_dir = -1, best_fix = -1, best_st = -1;\n      for (int dir = 0; dir < 2; ++dir) {\n        for (int fix = 0; fix < N; ++fix) {\n          for (int st = 0; st < N; ++st) {\n            int cost = 0;\n            int ndot = 0;\n            for (int p = 0; p < k; ++p) {\n              int rr = dir ? (st + p) % N : fix;\n              int cc = dir ? fix : (st + p) % N;\n              char cur = grid[rr][cc];\n              if (cur != '.' && cur != s[p]) ++cost;\n              if (cur == '.') ++ndot;\n            }\n            if (cost < best_cost || (cost == best_cost && ndot > best_ndot)) {\n              best_cost = cost;\n              best_ndot = ndot;\n              best_dir = dir;\n              best_fix = fix;\n              best_st = st;\n            }\n          }\n        }\n      }\n      if (best_cost == 0) {\n        // place\n        int dir = best_dir, fix = best_fix, st = best_st;\n        for (int p = 0; p < k; ++p) {\n          int rr = dir ? (st + p) % N : fix;\n          int cc = dir ? fix : (st + p) % N;\n          grid[rr][cc] = s[p];\n        }\n        changed = true;\n      }\n    }\n  }\n  // fill dots safely\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      if (grid[i][j] == '.') grid[i][j] = 'A';\n    }\n  }\n  int final_c = get_covered(grid);\n  if (final_c < M) {\n    do_sa();\n  }\n  // output\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      cout << grid[i][j];\n    }\n    cout << '\\n';\n  }\n  return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nchar get_move(int fi, int fj, int ti, int tj) {\n    int delx = ti - fi;\n    int dely = tj - fj;\n    if (delx == -1 && dely == 0) return 'U';\n    if (delx == 1 && dely == 0) return 'D';\n    if (dely == 1 && delx == 0) return 'R';\n    if (dely == -1 && delx == 0) return 'L';\n    assert(false);\n    return '?';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n    vector<vector<bool>> road(N, vector<bool>(N, false));\n    vector<vector<int>> enter(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                road[i][j] = true;\n                enter[i][j] = grid[i][j] - '0';\n            }\n        }\n    }\n    vector<pair<int, int>> h_reps, v_reps;\n    for (int i = 0; i < N; ++i) {\n        int j = 0;\n        while (j < N) {\n            if (!road[i][j]) {\n                ++j;\n                continue;\n            }\n            int lj = j;\n            while (j < N && road[i][j]) ++j;\n            int rj = j - 1;\n            int mj = (lj + rj) / 2;\n            h_reps.emplace_back(i, mj);\n        }\n    }\n    for (int j = 0; j < N; ++j) {\n        int i = 0;\n        while (i < N) {\n            if (!road[i][j]) {\n                ++i;\n                continue;\n            }\n            int ti = i;\n            while (i < N && road[i][j]) ++i;\n            int bi = i - 1;\n            int mi = (ti + bi) / 2;\n            v_reps.emplace_back(mi, j);\n        }\n    }\n    vector<pair<int, int>> terms;\n    if (h_reps.size() <= v_reps.size()) {\n        terms = h_reps;\n    } else {\n        terms = v_reps;\n    }\n    terms.emplace_back(si, sj);\n    int nt = terms.size();\n    // build cells and cellid\n    vector<pair<int, int>> cells;\n    vector<vector<int>> cellid(N, vector<int>(N, -1));\n    int numcells = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (road[i][j]) {\n                cellid[i][j] = numcells;\n                cells.emplace_back(i, j);\n                ++numcells;\n            }\n        }\n    }\n    // graph directed\n    vector<vector<pair<int, int>>> graph(numcells);\n    int dx[4] = {-1, 0, 1, 0};\n    int dy[4] = {0, 1, 0, -1};\n    for (int u = 0; u < numcells; ++u) {\n        auto [i, j] = cells[u];\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + dx[d];\n            int nj = j + dy[d];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && road[ni][nj]) {\n                int v = cellid[ni][nj];\n                int cost = enter[ni][nj];\n                graph[u].emplace_back(v, cost);\n            }\n        }\n    }\n    // termids\n    vector<int> termids(nt);\n    for (int k = 0; k < nt; ++k) {\n        auto [x, y] = terms[k];\n        termids[k] = cellid[x][y];\n    }\n    const ll INF = 1LL << 60;\n    vector<vector<ll>> dists(nt, vector<ll>(nt, INF));\n    vector<vector<string>> pathstr(nt, vector<string>(nt));\n    for (int s = 0; s < nt; ++s) {\n        int sid = termids[s];\n        vector<ll> d(numcells, INF);\n        d[sid] = 0;\n        vector<int> pred(numcells, -1);\n        priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;\n        pq.emplace(0, sid);\n        while (!pq.empty()) {\n            auto [dc, u] = pq.top();\n            pq.pop();\n            if (dc > d[u]) continue;\n            for (auto [v, wc] : graph[u]) {\n                ll nc = d[u] + wc;\n                if (nc < d[v]) {\n                    d[v] = nc;\n                    pred[v] = u;\n                    pq.emplace(nc, v);\n                }\n            }\n        }\n        for (int t = 0; t < nt; ++t) {\n            int tid = termids[t];\n            dists[s][t] = d[tid];\n            string& pth = pathstr[s][t];\n            int cur = tid;\n            while (cur != sid) {\n                int prv = pred[cur];\n                if (prv == -1) break;\n                auto [pi, pj] = cells[prv];\n                auto [ci, cj] = cells[cur];\n                pth += get_move(pi, pj, ci, cj);\n                cur = prv;\n            }\n            reverse(pth.begin(), pth.end());\n        }\n    }\n    // now MST on terms\n    vector<tuple<ll, int, int>> term_edges;\n    for (int a = 0; a < nt; ++a) {\n        for (int b = a + 1; b < nt; ++b) {\n            ll wc = dists[a][b] + dists[b][a];\n            if (wc >= INF / 2) continue;\n            term_edges.emplace_back(wc, a, b);\n        }\n    }\n    sort(term_edges.begin(), term_edges.end());\n    vector<int> tpar(nt);\n    for (int i = 0; i < nt; ++i) tpar[i] = i;\n    auto tfind = [&](auto&& self, int x) -> int {\n        return tpar[x] == x ? x : tpar[x] = self(self, tpar[x]);\n    };\n    vector<vector<int>> tadj(nt);\n    int num_tedges = 0;\n    for (auto& e : term_edges) {\n        ll w;\n        int a, b;\n        tie(w, a, b) = e;\n        int pa = tfind(tfind, a);\n        int pb = tfind(tfind, b);\n        if (pa != pb) {\n            tpar[pa] = pb;\n            tadj[a].push_back(b);\n            tadj[b].push_back(a);\n            ++num_tedges;\n            if (num_tedges == nt - 1) break;\n        }\n    }\n    // now dfs\n    string moves;\n    moves.reserve(200000);\n    int start_tid = nt - 1;\n    function<void(int, int)> dfs_term = [&](int ta, int tp) {\n        for (int tb : tadj[ta]) {\n            if (tb == tp) continue;\n            moves += pathstr[ta][tb];\n            dfs_term(tb, ta);\n            moves += pathstr[tb][ta];\n        }\n    };\n    dfs_term(start_tid, -1);\n    cout << moves << '\\n';\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout << fixed << setprecision(10);\n  int N, M, K, R;\n  cin >> N >> M >> K >> R;\n  vector<vector<int>> D(N + 1, vector<int>(K));\n  vector<double> avg_d(K, 0.0);\n  for (int i = 1; i <= N; ++i) {\n    for (int k = 0; k < K; ++k) {\n      cin >> D[i][k];\n      avg_d[k] += D[i][k];\n    }\n  }\n  for (int k = 0; k < K; ++k) {\n    avg_d[k] /= N;\n  }\n  vector<vector<int>> adj(N + 1);\n  vector<int> pending(N + 1, 0);\n  for (int r = 0; r < R; ++r) {\n    int u, v;\n    cin >> u >> v;\n    adj[u].push_back(v);\n    ++pending[v];\n  }\n  vector<int> crit(N + 1, 0);\n  auto get_crit = [&](auto&& self, int i) -> int {\n    if (crit[i] != 0) return crit[i];\n    int mx = 0;\n    for (int suc : adj[i]) {\n      mx = max(mx, self(self, suc));\n    }\n    crit[i] = 1 + mx;\n    return crit[i];\n  };\n  for (int i = 1; i <= N; ++i) {\n    get_crit(get_crit, i);\n  }\n  vector<vector<double>> est_s(M + 1, vector<double>(K, 0.0));\n  vector<int> obs_count(M + 1, 0);\n  for (int j = 1; j <= M; ++j) {\n    for (int k = 0; k < K; ++k) {\n      est_s[j][k] = avg_d[k] * 1.6;\n    }\n  }\n  vector<int> task_worker(N + 1, 0);\n  vector<int> task_start(N + 1, 0);\n  vector<bool> task_completed(N + 1, false);\n  vector<int> worker_task(M + 1, 0);\n  set<int> ready_set;\n  for (int i = 1; i <= N; ++i) {\n    if (pending[i] == 0) {\n      ready_set.insert(i);\n    }\n  }\n  int day = 0;\n  while (true) {\n    ++day;\n    vector<int> idles;\n    for (int j = 1; j <= M; ++j) {\n      if (worker_task[j] == 0) {\n        idles.push_back(j);\n      }\n    }\n    vector<int> readies_vec(ready_set.begin(), ready_set.end());\n    if (idles.empty() || readies_vec.empty()) {\n      cout << 0 << '\\n';\n      cout.flush();\n    } else {\n      vector<pair<int, double>> ready_list;\n      for (int ti : readies_vec) {\n        double min_pt = 1e100;\n        for (int j : idles) {\n          double w = 0.0;\n          for (int k = 0; k < K; ++k) {\n            w += max(0.0, (double)D[ti][k] - est_s[j][k]);\n          }\n          double pt = (w <= 0 ? 1.0 : max(1.0, w));\n          if (pt < min_pt) min_pt = pt;\n        }\n        ready_list.emplace_back(ti, min_pt);\n      }\n      sort(ready_list.begin(), ready_list.end(), [&](const pair<int, double>& a, const pair<int, double>& b) {\n        if (crit[a.first] != crit[b.first]) return crit[a.first] > crit[b.first];\n        if (fabs(a.second - b.second) > 1e-9) return a.second < b.second;\n        return a.first < b.first;\n      });\n      set<int> avail(idles.begin(), idles.end());\n      vector<pair<int, int>> assignment;\n      for (auto [ti, mpt] : ready_list) {\n        if (avail.empty()) break;\n        double best_pt = 1e100;\n        int best_j = -1;\n        for (int j : avail) {\n          double w = 0.0;\n          for (int k = 0; k < K; ++k) {\n            w += max(0.0, (double)D[ti][k] - est_s[j][k]);\n          }\n          double pt = (w <= 0 ? 1.0 : max(1.0, w));\n          if (pt < best_pt || (fabs(pt - best_pt) < 1e-9 && j < best_j)) {\n            best_pt = pt;\n            best_j = j;\n          }\n        }\n        if (best_j != -1) {\n          assignment.emplace_back(best_j, ti);\n          avail.erase(best_j);\n        }\n      }\n      cout << assignment.size();\n      for (auto p : assignment) {\n        cout << \" \" << p.first << \" \" << p.second;\n      }\n      cout << '\\n';\n      cout.flush();\n      for (auto [wj, ti] : assignment) {\n        task_worker[ti] = wj;\n        task_start[ti] = day;\n        worker_task[wj] = ti;\n        ready_set.erase(ti);\n      }\n    }\n    int n;\n    cin >> n;\n    if (n == -1) {\n      return 0;\n    }\n    vector<int> finished_workers(n);\n    for (int i = 0; i < n; ++i) {\n      cin >> finished_workers[i];\n    }\n    for (int jj : finished_workers) {\n      int tsk = worker_task[jj];\n      if (tsk == 0) continue;\n      int t_obs = day - task_start[tsk] + 1;\n      double w_est = max(0.0, (double)t_obs - 1.0);\n      ++obs_count[jj];\n      double alpha = 1.0 / obs_count[jj];\n      double current_w = 0.0;\n      vector<double> contrib(K, 0.0);\n      for (int k = 0; k < K; ++k) {\n        double defk = max(0.0, (double)D[tsk][k] - est_s[jj][k]);\n        contrib[k] = defk;\n        current_w += defk;\n      }\n      double error = current_w - w_est;\n      if (current_w > 1e-6) {\n        for (int k = 0; k < K; ++k) {\n          if (contrib[k] > 1e-6) {\n            double frac = contrib[k] / current_w;\n            double delta = alpha * error * frac;\n            est_s[jj][k] += delta;\n            if (est_s[jj][k] < 0.0) est_s[jj][k] = 0.0;\n          }\n        }\n      } else if (w_est > 1.0) {\n        double total_d = 0.0;\n        for (int k = 0; k < K; ++k) total_d += D[tsk][k];\n        if (total_d > 0) {\n          double delta = -alpha * (w_est / (double)K);\n          for (int k = 0; k < K; ++k) {\n            est_s[jj][k] += delta;\n            if (est_s[jj][k] < 0.0) est_s[jj][k] = 0.0;\n          }\n        }\n      }\n      task_completed[tsk] = true;\n      task_worker[tsk] = 0;\n      worker_task[jj] = 0;\n      for (int suc : adj[tsk]) {\n        --pending[suc];\n        if (pending[suc] == 0 && task_worker[suc] == 0 && !task_completed[suc]) {\n          ready_set.insert(suc);\n        }\n      }\n    }\n  }\n  return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int xx = 0, int yy = 0) : x(xx), y(yy) {}\n};\n\nint dist(Point a, Point b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\ndouble get_angle(const Point& pp) {\n    return atan2(pp.y - 400, pp.x - 400);\n}\n\nstruct Order {\n    Point p, d;\n    int id;\n    int len() const { return dist(p, d); }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    vector<Order> orders(1000);\n    Point O(400, 400);\n    for (int i = 0; i < 1000; i++) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        orders[i].p = {a, b};\n        orders[i].d = {c, d};\n        orders[i].id = i + 1;\n    }\n    const int N = 50;\n\n    // Forward greedy\n    vector<int> fsel;\n    bool fused[1000] = {};\n    Point fcurr = O;\n    for (int k = 0; k < N; k++) {\n        int best = -1;\n        int md = INT_MAX;\n        for (int u = 0; u < 1000; u++) {\n            if (fused[u]) continue;\n            int dd = dist(fcurr, orders[u].p);\n            if (dd < md || (dd == md && orders[u].len() < orders[best].len())) {\n                md = dd;\n                best = u;\n            }\n        }\n        fsel.push_back(best);\n        fused[best] = true;\n        fcurr = orders[best].d;\n    }\n\n    // Reverse greedy\n    vector<int> rsel;\n    bool rused[1000] = {};\n    Point rcurr = O;\n    for (int k = 0; k < N; k++) {\n        int best = -1;\n        int md = INT_MAX;\n        for (int u = 0; u < 1000; u++) {\n            if (rused[u]) continue;\n            int dd = dist(orders[u].d, rcurr);\n            if (dd < md || (dd == md && dist(orders[u].p, O) < dist(orders[best].p, O))) {\n                md = dd;\n                best = u;\n            }\n        }\n        rsel.push_back(best);\n        rused[best] = true;\n        rcurr = orders[best].p;\n    }\n    reverse(rsel.begin(), rsel.end());\n\n    // Compute full costs for both\n    auto compute_full = [&](const vector<int>& sel) -> pair<int, int> {\n        int suml = 0;\n        for (int oi : sel) suml += orders[oi].len();\n        int varc = dist(O, orders[sel[0]].p);\n        for (int i = 0; i < N - 1; i++) {\n            varc += dist(orders[sel[i]].d, orders[sel[i + 1]].p);\n        }\n        varc += dist(orders[sel.back()].d, O);\n        return {varc + suml, varc};\n    };\n\n    auto [ffull, fvar] = compute_full(fsel);\n    auto [rfull, rvar] = compute_full(rsel);\n\n    vector<int> sel = (ffull <= rfull ? fsel : rsel);\n    int initial_fixed_var = (ffull <= rfull ? fvar : rvar);\n\n    // Now build Ps, Ds, ids from sel\n    vector<Point> Ps(N), Ds(N);\n    vector<int> ids(N);\n    for (int i = 0; i < N; i++) {\n        int oi = sel[i];\n        Ps[i] = orders[oi].p;\n        Ds[i] = orders[oi].d;\n        ids[i] = orders[oi].id;\n    }\n\n    // get_var_cost\n    auto get_var_cost = [&](const vector<int>& perm) -> int {\n        if (perm.empty()) return 0;\n        int res = dist(O, Ps[perm[0]]);\n        for (size_t i = 0; i + 1 < perm.size(); ++i) {\n            res += dist(Ds[perm[i]], Ps[perm[(size_t)i + 1]]);\n        }\n        res += dist(Ds[perm.back()], O);\n        return res;\n    };\n\n    // Three initials\n    vector<vector<int>> inits(3);\n    // 1: identity (greedy)\n    inits[0].resize(N);\n    iota(inits[0].begin(), inits[0].end(), 0);\n    // 2: angle sort on P\n    {\n        vector<pair<double, int>> ang(N);\n        for (int i = 0; i < N; i++) ang[i] = {get_angle(Ps[i]), i};\n        sort(ang.begin(), ang.end());\n        inits[1].resize(N);\n        for (int i = 0; i < N; i++) inits[1][i] = ang[i].second;\n    }\n    // 3: manh coord sort on P (u=x+y, v=x-y)\n    {\n        vector<pair<pair<int, int>, int>> mng(N);\n        for (int i = 0; i < N; i++) {\n            int u = Ps[i].x + Ps[i].y;\n            int v = Ps[i].x - Ps[i].y;\n            mng[i] = {{u, v}, i};\n        }\n        sort(mng.begin(), mng.end());\n        inits[2].resize(N);\n        for (int i = 0; i < N; i++) inits[2][i] = mng[i].second;\n    }\n\n    vector<int> path = inits[0];\n    int current_cost = get_var_cost(path);\n    int bestcost = current_cost;\n    vector<int> bestpath = path;\n    for (int ii = 1; ii < 3; ii++) {\n        int cc = get_var_cost(inits[ii]);\n        if (cc < bestcost) {\n            bestcost = cc;\n            bestpath = inits[ii];\n            path = inits[ii];\n            current_cost = cc;\n        }\n    }\n\n    // SA\n    mt19937 gen(random_device{}());\n    uniform_int_distribution<int> randpos(0, N - 1);\n    uniform_real_distribution<double> rdis(0.0, 1.0);\n    double Tstart = 4000.0;\n    double T = Tstart;\n    double cool_rate = 0.9999;\n    const int MAX_ATT = 8000000;\n    for (int att = 0; att < MAX_ATT; att++) {\n        int i = randpos(gen);\n        int j = randpos(gen);\n        if (i == j) continue;\n        if (i > j) swap(i, j);\n        vector<int> newp = path;\n        swap(newp[i], newp[j]);\n        int nc = get_var_cost(newp);\n        int delta = nc - current_cost;\n        if (delta < 0 || rdis(gen) < exp(-double(delta) / T)) {\n            path = std::move(newp);\n            current_cost = nc;\n            if (nc < bestcost) {\n                bestcost = nc;\n                bestpath = path;\n            }\n        }\n        T *= cool_rate;\n        if (T < 0.1) break;\n    }\n\n    // Build output\n    vector<Point> route;\n    route.reserve(102);\n    route.push_back(O);\n    for (int pi : bestpath) {\n        route.push_back(Ps[pi]);\n        route.push_back(Ds[pi]);\n    }\n    route.push_back(O);\n\n    vector<int> out_ids(N);\n    for (int i = 0; i < N; i++) {\n        out_ids[i] = ids[bestpath[i]];\n    }\n    sort(out_ids.begin(), out_ids.end());\n\n    cout << N;\n    for (int r : out_ids) cout << ' ' << r;\n    cout << '\\n';\n    cout << route.size();\n    for (const auto& pt : route) {\n        cout << ' ' << pt.x << ' ' << pt.y;\n    }\n    cout << '\\n';\n\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    vector<int> X(N), Y(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> X[i] >> Y[i];\n    }\n\n    vector<pair<int, int>> Edge(M);\n    vector<int> D(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        Edge[i] = {u, v};\n        double dx = X[u] - X[v];\n        double dy = Y[u] - Y[v];\n        D[i] = (int)round(hypot(dx, dy));\n    }\n\n    vector<int> par(N), sz(N, 1);\n    vector<double> cminx(N), cmaxx(N), cminy(N), cmaxy(N);\n    for (int i = 0; i < N; ++i) {\n        par[i] = i;\n        cminx[i] = cmaxx[i] = X[i];\n        cminy[i] = cmaxy[i] = Y[i];\n    }\n\n    auto find = [&](auto&& self, int x) -> int {\n        return par[x] == x ? x : par[x] = self(self, par[x]);\n    };\n\n    auto rect_dist = [&](int c1, int c2) -> double {\n        double dx = max({0.0, cminx[c1] - cmaxx[c2], cminx[c2] - cmaxx[c1]});\n        double dy = max({0.0, cminy[c1] - cmaxy[c2], cminy[c2] - cmaxy[c1]});\n        return hypot(dx, dy);\n    };\n\n    auto unite = [&](int a, int b) {\n        a = find(find, a);\n        b = find(find, b);\n        if (a == b) return;\n        if (sz[a] < sz[b]) swap(a, b);\n        par[b] = a;\n        sz[a] += sz[b];\n        cminx[a] = min(cminx[a], cminx[b]);\n        cmaxx[a] = max(cmaxx[a], cmaxx[b]);\n        cminy[a] = min(cminy[a], cminy[b]);\n        cmaxy[a] = max(cmaxy[a], cmaxy[b]);\n    };\n\n    int cur_comp = N;\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;\n\n        int u = Edge[i].first, v = Edge[i].second;\n        int pu = find(find, u), pv = find(find, v);\n        if (pu == pv) {\n            cout << 0 << '\\n' << flush;\n            continue;\n        }\n\n        int s1 = sz[pu], s2 = sz[pv];\n        int smin = min(s1, s2);\n        double sepd = rect_dist(pu, pv);\n        bool separated = (sepd > 1e-6);\n        double ratio = (double)l / D[i];\n\n        // Scan for future only when necessary\n        double min_fut_d = 1e9;\n        bool need_scan = (smin >= 12) && separated && (cur_comp > 20) && (i < M - 20);\n        if (need_scan) {\n            for (int j = i + 1; j < M; ++j) {\n                int qu = find(find, Edge[j].first);\n                int qv = find(find, Edge[j].second);\n                if ((qu == pu && qv == pv) || (qu == pv && qv == pu)) {\n                    min_fut_d = min(min_fut_d, (double)D[j]);\n                }\n            }\n        }\n        double est_sep = (min_fut_d < 5e8) ? min_fut_d : sepd;\n\n        bool too_bad = (ratio > 2.7);\n        bool is_small = (smin <= 32);\n        bool good_dist = !separated || (l <= 1.85 * est_sep + 2.5);\n\n        bool take = !too_bad && (is_small || good_dist);\n\n        // Urgency\n        int remaining = M - i - 1;\n        int needed = cur_comp - 1;\n        double urgency_ratio = (double)needed / max(1, remaining);\n        bool large_comps = (s1 >= 50 && s2 >= 50);\n        bool urgent = (remaining <= needed * 1.8) || (needed <= 15) || (urgency_ratio > 0.20) ||\n                      (large_comps && urgency_ratio > 0.15);\n        if (urgent) {\n            take = !too_bad;\n        }\n\n        if (take) {\n            unite(u, v);\n            --cur_comp;\n            cout << 1 << '\\n' << flush;\n        } else {\n            cout << 0 << '\\n' << flush;\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef pair<int, int> pii;\n\nconst int SZ = 30;\nbool passable[31][31];\nint DX[4] = {-1, 1, 0, 0};\nint DY[4] = {0, 0, -1, 1};\nchar WALLC[4] = {'u', 'd', 'l', 'r'};\nchar MOVEC[4] = {'U', 'D', 'L', 'R'};\n\nbool in_bound(int x, int y) {\n  return x >= 1 && x <= SZ && y >= 1 && y <= SZ;\n}\n\nbool can_wall(const vector<pii>& hpos, const vector<pii>& ppos, int hi, int d, int NN, int MM) {\n  int hx = hpos[hi].first;\n  int hy = hpos[hi].second;\n  int tx = hx + DX[d];\n  int ty = hy + DY[d];\n  if (!in_bound(tx, ty)) return false;\n  // occupied by human\n  for (int k = 0; k < MM; k++) {\n    if (hpos[k].first == tx && hpos[k].second == ty) return false;\n  }\n  // occupied by pet\n  for (int k = 0; k < NN; k++) {\n    if (ppos[k].first == tx && ppos[k].second == ty) return false;\n  }\n  // adjacent has pet\n  for (int dd = 0; dd < 4; dd++) {\n    int ax = tx + DX[dd];\n    int ay = ty + DY[dd];\n    if (!in_bound(ax, ay)) continue;\n    for (int k = 0; k < NN; k++) {\n      if (ppos[k].first == ax && ppos[k].second == ay) return false;\n    }\n  }\n  return true;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n\n  int N;\n  cin >> N;\n  vector<pii> ppos(N);\n  vector<int> ptype(N);\n  for (int i = 0; i < N; i++) {\n    int x, y, t;\n    cin >> x >> y >> t;\n    ppos[i] = {x, y};\n    ptype[i] = t;\n  }\n  int M;\n  cin >> M;\n  vector<pii> hpos(M);\n  for (int i = 0; i < M; i++) {\n    int x, y;\n    cin >> x >> y;\n    hpos[i] = {x, y};\n  }\n\n  // init grid\n  memset(passable, 0, sizeof(passable));\n  for (int i = 1; i <= SZ; i++)\n    for (int j = 1; j <= SZ; j++) passable[i][j] = true;\n\n  vector<double> pet_threat(N);\n  for (int i = 0; i < N; i++) {\n    pet_threat[i] = 1.0;\n    if (ptype[i] == 4) pet_threat[i] = 20.0;\n    else if (ptype[i] == 3) pet_threat[i] = 5.0;\n    else if (ptype[i] == 2) pet_threat[i] = 2.0;\n    else if (ptype[i] == 5) pet_threat[i] = 1.5;\n  }\n\n  int dista[31][31];\n\n  for (int turn = 0; turn < 300; turn++) {\n    // compute current center and spread\n    int sumx = 0, sumy = 0;\n    for (auto& hp : hpos) {\n      sumx += hp.first;\n      sumy += hp.second;\n    }\n    int cur_cx = sumx / M;\n    int cur_cy = sumy / M;\n    int spread = 0;\n    for (auto& hp : hpos) {\n      int dd = abs(hp.first - cur_cx) + abs(hp.second - cur_cy);\n      spread = max(spread, dd);\n    }\n\n    bool wall_mode = (spread <= 3);\n\n    pii target = {cur_cx, cur_cy};\n    if (!wall_mode) {\n      // compute dist to nearest pet\n      memset(dista, -1, sizeof(dista));\n      queue<pii> q;\n      for (int i = 0; i < N; i++) {\n        auto [px, py] = ppos[i];\n        if (passable[px][py]) {\n          dista[px][py] = 0;\n          q.push({px, py});\n        }\n      }\n      while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop();\n        for (int d = 0; d < 4; d++) {\n          int nx = x + DX[d];\n          int ny = y + DY[d];\n          if (in_bound(nx, ny) && passable[nx][ny] && dista[nx][ny] == -1) {\n            dista[nx][ny] = dista[x][y] + 1;\n            q.push({nx, ny});\n          }\n        }\n      }\n      // find best target: max dist, tie min dist to cur center\n      int maxd = -1;\n      int min_tie = INT_MAX / 2;\n      pii best_target = {1, 1};\n      for (int i = 1; i <= SZ; i++) {\n        for (int j = 1; j <= SZ; j++) {\n          if (!passable[i][j]) continue;\n          int dd = dista[i][j];\n          if (dd == -1) dd = 999;\n          int tie_dist = abs(i - cur_cx) + abs(j - cur_cy);\n          if (dd > maxd || (dd == maxd && tie_dist < min_tie)) {\n            maxd = dd;\n            min_tie = tie_dist;\n            best_target = {i, j};\n          }\n        }\n      }\n      target = best_target;\n    }\n    int tx = target.first;\n    int ty = target.second;\n\n    // decide actions\n    string action(M, '.');\n    if (wall_mode) {\n      // wall mode: choose highest threat adj square\n      for (int hi = 0; hi < M; hi++) {\n        int bestd = -1;\n        double bsc = -1e100;\n        auto [hx, hy] = hpos[hi];\n        for (int d = 0; d < 4; d++) {\n          if (!can_wall(hpos, ppos, hi, d, N, M)) continue;\n          int wtx = hx + DX[d];\n          int wty = hy + DY[d];\n          double sc = 0.0;\n          for (int pi = 0; pi < N; pi++) {\n            auto [px, py] = ppos[pi];\n            int pdist = abs(wtx - px) + abs(wty - py);\n            sc += pet_threat[pi] / (pdist + 1.0);\n          }\n          if (sc > bsc) {\n            bsc = sc;\n            bestd = d;\n          }\n        }\n        if (bestd != -1) {\n          action[hi] = WALLC[bestd];\n        }\n      }\n    } else {\n      // move mode: move towards target\n      for (int hi = 0; hi < M; hi++) {\n        auto [hx, hy] = hpos[hi];\n        int mdist = abs(hx - tx) + abs(hy - ty);\n        if (mdist == 0) continue;\n        int best_red = -1;\n        int bestd = -1;\n        for (int d = 0; d < 4; d++) {\n          int nx = hx + DX[d];\n          int ny = hy + DY[d];\n          if (!in_bound(nx, ny) || !passable[nx][ny]) continue;\n          int nmdist = abs(nx - tx) + abs(ny - ty);\n          int red = mdist - nmdist;\n          if (red > best_red) {\n            best_red = red;\n            bestd = d;\n          }\n        }\n        if (bestd != -1) {\n          action[hi] = MOVEC[bestd];\n        }\n      }\n    }\n\n    // output\n    cout << \"#\" << turn << \" spread:\" << spread << \" mode:\" << (wall_mode ? \"wall\" : \"move\");\n    if (!wall_mode) cout << \" target(\" << tx << \",\" << ty << \")\";\n    cout << endl;\n    cout << action << endl;\n    cout.flush();\n\n    // update pets\n    for (int i = 0; i < N; i++) {\n      string s;\n      cin >> s;\n      int x = ppos[i].first;\n      int y = ppos[i].second;\n      for (char c : s) {\n        int dx = 0, dy = 0;\n        if (c == 'U')\n          dx = -1;\n        else if (c == 'D')\n          dx = 1;\n        else if (c == 'L')\n          dy = -1;\n        else if (c == 'R')\n          dy = 1;\n        else\n          continue;\n        x += dx;\n        y += dy;\n      }\n      ppos[i] = {x, y};\n    }\n\n    // update humans and walls\n    for (int hi = 0; hi < M; hi++) {\n      char c = action[hi];\n      if (c == '.') continue;\n      int dd = -1;\n      bool is_move = isupper((unsigned char)c);\n      if (is_move) {\n        if (c == 'U')\n          dd = 0;\n        else if (c == 'D')\n          dd = 1;\n        else if (c == 'L')\n          dd = 2;\n        else if (c == 'R')\n          dd = 3;\n        hpos[hi].first += DX[dd];\n        hpos[hi].second += DY[dd];\n      } else {\n        if (c == 'u')\n          dd = 0;\n        else if (c == 'd')\n          dd = 1;\n        else if (c == 'l')\n          dd = 2;\n        else if (c == 'r')\n          dd = 3;\n        int wtx = hpos[hi].first + DX[dd];\n        int wty = hpos[hi].second + DY[dd];\n        if (in_bound(wtx, wty)) {\n          passable[wtx][wty] = false;\n        }\n      }\n    }\n  }\n  return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int ROWS = 20;\nconst int COLS = 20;\nconst int N = ROWS * COLS;\n\nint get_row(int pos) { return pos / COLS; }\nint get_col(int pos) { return pos % COLS; }\n\nint attempt_move(int cur_pos, char direction, const vector<string>& h_walls, const vector<string>& v_walls) {\n  int r = get_row(cur_pos);\n  int c = get_col(cur_pos);\n  int dr = 0, dc = 0;\n  switch (direction) {\n    case 'U': dr = -1; break;\n    case 'D': dr = 1; break;\n    case 'L': dc = -1; break;\n    case 'R': dc = 1; break;\n    default: return cur_pos;\n  }\n  int nr = r + dr;\n  int nc = c + dc;\n  if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) {\n    return cur_pos;\n  }\n  if (dr != 0) {\n    if (dr > 0) {\n      if (v_walls[r][c] == '1') return cur_pos;\n    } else {\n      if (v_walls[r - 1][c] == '1') return cur_pos;\n    }\n  } else {\n    if (dc > 0) {\n      if (h_walls[r][c] == '1') return cur_pos;\n    } else {\n      if (h_walls[r][c - 1] == '1') return cur_pos;\n    }\n  }\n  return nr * COLS + nc;\n}\n\nstring shortest_path(int start_pos, int target_pos, const vector<string>& h_walls, const vector<string>& v_walls) {\n  vector<int> dist(N, -1);\n  vector<int> parent(N, -1);\n  dist[start_pos] = 0;\n  queue<int> q;\n  q.push(start_pos);\n  while (!q.empty()) {\n    int u = q.front();\n    q.pop();\n    if (u == target_pos) break;\n    for (char dch : {'U', 'D', 'L', 'R'}) {\n      int v = attempt_move(u, dch, h_walls, v_walls);\n      if (dist[v] == -1) {\n        dist[v] = dist[u] + 1;\n        parent[v] = u;\n        q.push(v);\n      }\n    }\n  }\n  if (dist[target_pos] == -1) {\n    return \"\";  // Should not happen\n  }\n  string path_str;\n  int cur = target_pos;\n  while (cur != start_pos) {\n    int prev = parent[cur];\n    int pr = get_row(prev), pc = get_col(prev);\n    int cr = get_row(cur), cc = get_col(cur);\n    char dch;\n    if (cr == pr + 1) dch = 'D';\n    else if (cr == pr - 1) dch = 'U';\n    else if (cc == pc + 1) dch = 'R';\n    else if (cc == pc - 1) dch = 'L';\n    else assert(false);\n    path_str += dch;\n    cur = prev;\n  }\n  reverse(path_str.begin(), path_str.end());\n  return path_str;\n}\n\ndouble evaluate(const string& path_str, double forget_p, int start_pos, int target_pos,\n                const vector<string>& h_walls, const vector<string>& v_walls) {\n  if (start_pos == target_pos) return 401.0;\n  int L = path_str.size();\n  vector<double> curr_prob(N, 0.0);\n  curr_prob[start_pos] = 1.0;\n  double total_es = 0.0;\n  for (int t = 0; t < L; ++t) {\n    char ch = path_str[t];\n    vector<double> next_prob(N, 0.0);\n    double arr_this = 0.0;\n    for (int ps = 0; ps < N; ++ps) {\n      double pr = curr_prob[ps];\n      if (pr < 1e-12) continue;\n      // stay\n      int stay_pos = ps;\n      if (stay_pos == target_pos) {\n        arr_this += pr * forget_p;\n      } else {\n        next_prob[stay_pos] += pr * forget_p;\n      }\n      // move\n      int move_pos = attempt_move(ps, ch, h_walls, v_walls);\n      if (move_pos == target_pos) {\n        arr_this += pr * (1.0 - forget_p);\n      } else {\n        next_prob[move_pos] += pr * (1.0 - forget_p);\n      }\n    }\n    total_es += arr_this * (401.0 - (t + 1));\n    curr_prob = std::move(next_prob);\n  }\n  return total_es;\n}\n\nstruct Cand {\n  string path;\n  double es;\n};\n\nint main() {\n  int si, sj, ti, tj;\n  double forget_p;\n  cin >> si >> sj >> ti >> tj >> forget_p;\n  vector<string> h_walls(20);\n  for (auto& s : h_walls) cin >> s;\n  vector<string> v_walls(19);\n  for (auto& s : v_walls) cin >> s;\n  int start_pos = si * COLS + sj;\n  int target_pos = ti * COLS + tj;\n  if (start_pos == target_pos) {\n    cout << \"\" << endl;\n    return 0;\n  }\n  string sp = shortest_path(start_pos, target_pos, h_walls, v_walls);\n  vector<Cand> candidates;\n  // per-move repeats\n  for (int rpm = 2; rpm <= 6; ++rpm) {\n    string cand;\n    cand.reserve(sp.size() * rpm);\n    for (char ch : sp) {\n      cand.append(rpm, ch);\n      if (cand.size() > 200) break;\n    }\n    if (cand.size() > 200 || cand.empty()) continue;\n    double esc = evaluate(cand, forget_p, start_pos, target_pos, h_walls, v_walls);\n    candidates.push_back({cand, esc});\n  }\n  // whole path repeats\n  for (int cycles = 1; cycles <= 5; ++cycles) {\n    string cand;\n    cand.reserve(sp.size() * cycles);\n    for (int i = 0; i < cycles; ++i) {\n      cand += sp;\n      if (cand.size() > 200) break;\n    }\n    if (cand.size() > 200 || cand.empty()) continue;\n    double esc = evaluate(cand, forget_p, start_pos, target_pos, h_walls, v_walls);\n    candidates.push_back({cand, esc});\n  }\n  // single shortest\n  {\n    double esc = evaluate(sp, forget_p, start_pos, target_pos, h_walls, v_walls);\n    candidates.push_back({sp, esc});\n  }\n  // select top for beam\n  sort(candidates.begin(), candidates.end(),\n       [](const Cand& a, const Cand& b) { return a.es > b.es; });\n  string best_path = candidates[0].path;\n  double best_es = candidates[0].es;\n  const int BEAM_SIZE = 10;\n  vector<Cand> curr_beam;\n  for (size_t i = 0; i < min((size_t)BEAM_SIZE, candidates.size()); ++i) {\n    curr_beam.push_back(candidates[i]);\n  }\n  string chars = \"UDLR\";\n  for (int clen = curr_beam[0].path.size(); clen < 200; ++clen) {\n    vector<Cand> next_beam;\n    for (const auto& cb : curr_beam) {\n      for (char dch : chars) {\n        string npath = cb.path + dch;\n        double nes = evaluate(npath, forget_p, start_pos, target_pos, h_walls, v_walls);\n        next_beam.push_back({npath, nes});\n        if (nes > best_es) {\n          best_es = nes;\n          best_path = npath;\n        }\n      }\n    }\n    sort(next_beam.begin(), next_beam.end(),\n         [](const Cand& a, const Cand& b) { return a.es > b.es; });\n    next_beam.resize(BEAM_SIZE);\n    bool improve = false;\n    for (const auto& nc : next_beam) {\n      if (nc.es > best_es) {\n        best_es = nc.es;\n        best_path = nc.path;\n        improve = true;\n      }\n    }\n    curr_beam = std::move(next_beam);\n    if (!improve || curr_beam[0].es < best_es * 0.98) {\n      break;\n    }\n  }\n  cout << best_path << endl;\n  return 0;\n}","ahc010":"","ahc011":"","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Line {\n  ll px, py, qx, qy;\n};\n\nint side(const Line& l, ll x, ll y) {\n  ll dx1 = l.qx - l.px;\n  ll dy1 = l.qy - l.py;\n  ll dx2 = x - l.px;\n  ll dy2 = y - l.py;\n  ll cross = dx1 * dy2 - dy1 * dx2;\n  if (cross == 0) return 0;\n  return cross > 0 ? 1 : -1;\n}\n\ntuple<ll, ll, ll> exgcd(ll a, ll b) {\n  if (b == 0) return {a, 1, 0};\n  auto [g, x, y] = exgcd(b, a % b);\n  return {g, y, x - (a / b) * y};\n}\n\nint eval_add(const Line& cand, const vector<vector<int>>& groups, const vector<pair<ll, ll>>& points, const vector<int>& a) {\n  vector<int> tent_b(11, 0);\n  for (const auto& grp : groups) {\n    int L = 0, R = 0;\n    for (int id : grp) {\n      int s = side(cand, points[id].first, points[id].second);\n      if (s == 1) ++L;\n      else if (s == -1) ++R;\n    }\n    if (L >= 1 && L <= 10) ++tent_b[L];\n    if (R >= 1 && R <= 10) ++tent_b[R];\n  }\n  int sc = 0;\n  for (int d = 1; d <= 10; ++d) {\n    sc += min(a[d], tent_b[d]);\n  }\n  return sc;\n}\n\nvoid add_line(vector<Line>& lines, vector<vector<int>>& groups, const vector<pair<ll, ll>>& points, const Line& newline) {\n  vector<vector<int>> newgroups;\n  newgroups.reserve(groups.size() * 2);\n  for (auto grp : groups) {\n    vector<int> left, right;\n    for (int id : grp) {\n      int s = side(newline, points[id].first, points[id].second);\n      if (s == 1) left.push_back(id);\n      else if (s == -1) right.push_back(id);\n    }\n    if (!left.empty()) newgroups.push_back(move(left));\n    if (!right.empty()) newgroups.push_back(move(right));\n  }\n  groups = move(newgroups);\n  lines.push_back(newline);\n}\n\nvector<Line> generate_cands(const vector<vector<int>>& groups, const vector<pair<ll, ll>>& points) {\n  vector<Line> cands;\n  const int MAX_CANDS = 50;\n  cands.reserve(MAX_CANDS);\n  for (const auto& grp : groups) {\n    int gsz = grp.size();\n    if (gsz < 2) continue;\n    if ((int)cands.size() >= MAX_CANDS) break;\n    int minid = *min_element(grp.begin(), grp.end());\n    int maxid = *max_element(grp.begin(), grp.end());\n    mt19937_64 rng((ll)minid + (ll)maxid * 12345LL);\n    int ngen = min(20, gsz);\n    int range = 100;\n    for (int tr = 0; tr < ngen; ++tr) {\n      if ((int)cands.size() >= MAX_CANDS) break;\n      ll aa = (rng() % (2LL * range + 1)) - range;\n      ll bb = (rng() % (2LL * range + 1)) - range;\n      if (aa == 0 && bb == 0) continue;\n      ll gg = __gcd(abs(aa), abs(bb));\n      aa /= gg;\n      bb /= gg;\n      vector<pair<ll, int>> projs;\n      projs.reserve(gsz);\n      for (int id : grp) {\n        ll x = points[id].first;\n        ll y = points[id].second;\n        ll pr = aa * x + bb * y;\n        projs.emplace_back(pr, id);\n      }\n      sort(projs.begin(), projs.end());\n      int gm = min(10, gsz - 1);\n      for (int m = 1; m <= gm; ++m) {\n        if ((int)cands.size() >= MAX_CANDS) break;\n        ll ml = projs[m - 1].first;\n        ll mr = projs[m].first;\n        if (ml + 1 >= mr) continue;\n        ll kk = ml + 1;\n        ll dd = kk;\n        auto [g, x, y] = exgcd(aa, bb);\n        if (g < 0) {\n          g = -g;\n          x = -x;\n          y = -y;\n        }\n        if (dd % g != 0) continue;\n        ll mul = dd / g;\n        ll xx_ = x * mul;\n        ll yy_ = y * mul;\n        ll dirx_ = bb;\n        ll diry_ = -aa;\n        ll ppx = xx_;\n        ll ppy = yy_;\n        if (bb != 0) {\n          ll tt = -xx_ / bb;\n          ppx = xx_ + bb * tt;\n          ppy = yy_ - aa * tt;\n        }\n        ll qqx = ppx + dirx_;\n        ll qqy = ppy + diry_;\n        if (abs(ppx) > 1000000000LL || abs(ppy) > 1000000000LL || abs(qqx) > 1000000000LL ||\n            abs(qqy) > 1000000000LL)\n          continue;\n        if (ppx == qqx && ppy == qqy) continue;\n        cands.push_back({ppx, ppy, qqx, qqy});\n      }\n    }\n  }\n  return cands;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, K;\n  cin >> N >> K;\n  vector<int> a(11, 0);\n  for (int d = 1; d <= 10; ++d) {\n    cin >> a[d];\n  }\n  vector<pair<ll, ll>> points(N);\n  for (auto& p : points) {\n    cin >> p.first >> p.second;\n  }\n  vector<vector<int>> groups(1, vector<int>(N));\n  iota(groups[0].begin(), groups[0].end(), 0);\n  vector<Line> curr_lines;\n  while ((int)curr_lines.size() < K) {\n    auto cands = generate_cands(groups, points);\n    if (cands.empty()) break;\n    Line best_cand;\n    int best_new_sc = -1;\n    bool improved = false;\n    for (const auto& cand : cands) {\n      int nsc = eval_add(cand, groups, points, a);\n      if (nsc > best_new_sc) {\n        best_new_sc = nsc;\n        best_cand = cand;\n        improved = true;\n      }\n    }\n    if (!improved) break;\n    add_line(curr_lines, groups, points, best_cand);\n  }\n  cout << curr_lines.size() << '\\n';\n  for (const auto& l : curr_lines) {\n    cout << l.px << ' ' << l.py << ' ' << l.qx << ' ' << l.qy << '\\n';\n  }\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 64;\nbool occupied[MAXN][MAXN];\nbool used_h[MAXN][MAXN];\nbool used_v[MAXN][MAXN];\nbool used_ne[MAXN][MAXN];\nbool used_nw[MAXN][MAXN];\nint N, c;\nint M;\n\nstruct Move {\n    int x1, y1, x2, y2, x3, y3, x4, y4;\n    long long prio;\n};\n\nvector<Move> cands;\nvector<Move> ans_moves;\n\nlong long distsq(int x, int y) {\n    long long dx = x - c;\n    long long dy = y - c;\n    return dx * dx + dy * dy;\n}\n\npair<int, int> getxy(int uu, int vv) {\n    int xx = (uu + vv) / 2;\n    int yy = (uu - vv) / 2;\n    return {xx, yy};\n}\n\nbool in_grid(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool check_clean(int x0, int y0, int x1, int y1) {\n    int dx = x1 - x0;\n    int dy = y1 - y0;\n    int adx = abs(dx);\n    int ady = abs(dy);\n    if (adx == 0 && ady == 0) return false;\n    if ((adx != 0 && ady != 0 && adx != ady)) return false;\n    int k = max(adx, ady);\n    int stepx = (dx > 0 ? 1 : (dx < 0 ? -1 : 0));\n    int stepy = (dy > 0 ? 1 : (dy < 0 ? -1 : 0));\n\n    // interiors\n    for (int i = 1; i < k; ++i) {\n        int xx = x0 + i * stepx;\n        int yy = y0 + i * stepy;\n        if (!in_grid(xx, yy) || occupied[xx][yy]) return false;\n    }\n\n    // units\n    for (int i = 0; i < k; ++i) {\n        int xx = x0 + i * stepx;\n        int yy = y0 + i * stepy;\n        int nx = xx + stepx;\n        int ny = yy + stepy;\n        if (!in_grid(xx, yy) || !in_grid(nx, ny)) return false;\n\n        int mx = min(xx, nx);\n        int yleft = (xx == mx ? yy : ny);\n        int yright = (nx == mx ? ny : yy);\n\n        if (stepx == 0) {  // vert\n            int miny = min(yy, ny);\n            if (miny < 0 || miny >= N - 1 || used_v[xx][miny]) return false;\n        } else if (stepy == 0) {  // horiz\n            if (mx < 0 || mx >= N - 1 || used_h[yy][mx]) return false;\n        } else {  // diag\n            if (yright == yleft + 1) {\n                if (mx < 0 || mx >= N - 1 || yleft < 0 || yleft >= N - 1 || used_ne[mx][yleft]) return false;\n            } else if (yright == yleft - 1) {\n                if (mx < 0 || mx >= N - 1 || yleft < 1 || yleft >= N || used_nw[mx][yleft]) return false;\n            } else {\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nvoid mark_side(int x0, int y0, int x1, int y1) {\n    int dx = x1 - x0;\n    int dy = y1 - y0;\n    int adx = abs(dx);\n    int ady = abs(dy);\n    if (adx == 0 && ady == 0) return;\n    int k = max(adx, ady);\n    int stepx = (dx > 0 ? 1 : (dx < 0 ? -1 : 0));\n    int stepy = (dy > 0 ? 1 : (dy < 0 ? -1 : 0));\n\n    // mark units only\n    for (int i = 0; i < k; ++i) {\n        int xx = x0 + i * stepx;\n        int yy = y0 + i * stepy;\n        int nx = xx + stepx;\n        int ny = yy + stepy;\n\n        int mx = min(xx, nx);\n        int yleft = (xx == mx ? yy : ny);\n        int yright = (nx == mx ? ny : yy);\n\n        if (stepx == 0) {  // vert\n            int miny = min(yy, ny);\n            used_v[xx][miny] = true;\n        } else if (stepy == 0) {  // horiz\n            used_h[yy][mx] = true;\n        } else {  // diag\n            if (yright == yleft + 1) {\n                used_ne[mx][yleft] = true;\n            } else if (yright == yleft - 1) {\n                used_nw[mx][yleft] = true;\n            }\n        }\n    }\n}\n\nvoid scan_axis() {\n    for (int xl = 0; xl < N; ++xl) {\n        for (int xr = xl + 1; xr < N; ++xr) {\n            for (int yb = 0; yb < N; ++yb) {\n                for (int yt = yb + 1; yt < N; ++yt) {\n                    vector<pair<int, int>> corns = {\n                        {xl, yb}, {xr, yb}, {xr, yt}, {xl, yt}\n                    };\n                    int cnt = 0;\n                    for (auto& p : corns) {\n                        if (occupied[p.first][p.second]) ++cnt;\n                    }\n                    if (cnt != 3) continue;\n                    pair<int, int> p1;\n                    int miss_idx = -1;\n                    for (int ii = 0; ii < 4; ++ii) {\n                        if (!occupied[corns[ii].first][corns[ii].second]) {\n                            p1 = corns[ii];\n                            miss_idx = ii;\n                            break;\n                        }\n                    }\n                    if (occupied[p1.first][p1.second]) continue;\n\n                    // check cleans\n                    if (!check_clean(corns[0].first, corns[0].second, corns[1].first, corns[1].second) ||\n                        !check_clean(corns[1].first, corns[1].second, corns[2].first, corns[2].second) ||\n                        !check_clean(corns[2].first, corns[2].second, corns[3].first, corns[3].second) ||\n                        !check_clean(corns[3].first, corns[3].second, corns[0].first, corns[0].second)) continue;\n\n                    // order\n                    int idx2 = (miss_idx + 1) % 4;\n                    int idx3 = (miss_idx + 2) % 4;\n                    int idx4 = (miss_idx + 3) % 4;\n                    Move m{\n                        p1.first, p1.second,\n                        corns[idx2].first, corns[idx2].second,\n                        corns[idx3].first, corns[idx3].second,\n                        corns[idx4].first, corns[idx4].second\n                    };\n                    m.prio = distsq(p1.first, p1.second);\n                    cands.push_back(m);\n                }\n            }\n        }\n    }\n}\n\nvoid scan_45(int parity) {\n    vector<int> us;\n    for (int uu = parity; uu <= 2 * (N - 1); uu += 2) us.push_back(uu);\n    vector<int> vs;\n    int v_start = parity ? -(N - 2) : -(N - 1);\n    for (int vv = v_start; vv <= N - 1; vv += 2) vs.push_back(vv);\n    if (us.empty() || vs.empty()) return;\n    for (size_t i = 0; i < us.size(); ++i) {\n        for (size_t j = i + 1; j < us.size(); ++j) {\n            int u1 = us[i], u2 = us[j];\n            for (size_t kk = 0; kk < vs.size(); ++kk) {\n                for (size_t l = kk + 1; l < vs.size(); ++l) {\n                    int v1 = vs[kk], v2 = vs[l];\n                    auto c0 = getxy(u1, v1);\n                    if (!in_grid(c0.first, c0.second)) continue;\n                    auto c1 = getxy(u1, v2);\n                    if (!in_grid(c1.first, c1.second)) continue;\n                    auto c2 = getxy(u2, v2);\n                    if (!in_grid(c2.first, c2.second)) continue;\n                    auto c3 = getxy(u2, v1);\n                    if (!in_grid(c3.first, c3.second)) continue;\n\n                    vector<pair<int, int>> corns = {c0, c1, c2, c3};\n                    int cnt = 0;\n                    for (auto& p : corns) {\n                        if (occupied[p.first][p.second]) ++cnt;\n                    }\n                    if (cnt != 3) continue;\n                    pair<int, int> p1;\n                    int miss_idx = -1;\n                    for (int ii = 0; ii < 4; ++ii) {\n                        if (!occupied[corns[ii].first][corns[ii].second]) {\n                            p1 = corns[ii];\n                            miss_idx = ii;\n                            break;\n                        }\n                    }\n                    if (occupied[p1.first][p1.second]) continue;\n\n                    // check cleans: 0-1, 1-2, 2-3, 3-0\n                    if (!check_clean(corns[0].first, corns[0].second, corns[1].first, corns[1].second) ||\n                        !check_clean(corns[1].first, corns[1].second, corns[2].first, corns[2].second) ||\n                        !check_clean(corns[2].first, corns[2].second, corns[3].first, corns[3].second) ||\n                        !check_clean(corns[3].first, corns[3].second, corns[0].first, corns[0].second)) continue;\n\n                    // order\n                    int idx2 = (miss_idx + 1) % 4;\n                    int idx3 = (miss_idx + 2) % 4;\n                    int idx4 = (miss_idx + 3) % 4;\n                    Move m{\n                        p1.first, p1.second,\n                        corns[idx2].first, corns[idx2].second,\n                        corns[idx3].first, corns[idx3].second,\n                        corns[idx4].first, corns[idx4].second\n                    };\n                    m.prio = distsq(p1.first, p1.second);\n                    cands.push_back(m);\n                }\n            }\n        }\n    }\n}\n\nvoid do_scan() {\n    cands.clear();\n    scan_axis();\n    scan_45(0);  // even\n    scan_45(1);  // odd\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    clock_t start_clk = clock();\n\n    cin >> N >> M;\n    c = (N - 1) / 2;\n    memset(occupied, 0, sizeof(occupied));\n    memset(used_h, 0, sizeof(used_h));\n    memset(used_v, 0, sizeof(used_v));\n    memset(used_ne, 0, sizeof(used_ne));\n    memset(used_nw, 0, sizeof(used_nw));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        occupied[x][y] = true;\n    }\n\n    int max_iters = 10000;\n    int iter = 0;\n    while (iter++ < max_iters) {\n        double timet = (clock() - start_clk) / (double)CLOCKS_PER_SEC;\n        if (timet > 4.2) break;\n\n        do_scan();\n        if (cands.empty()) break;\n\n        sort(cands.begin(), cands.end(), [](const Move& a, const Move& b) {\n            return a.prio > b.prio;\n        });\n\n        for (auto& mv : cands) {\n            double timet2 = (clock() - start_clk) / (double)CLOCKS_PER_SEC;\n            if (timet2 > 4.4) break;\n\n            if (occupied[mv.x1][mv.y1]) continue;\n\n            if (check_clean(mv.x1, mv.y1, mv.x2, mv.y2) &&\n                check_clean(mv.x2, mv.y2, mv.x3, mv.y3) &&\n                check_clean(mv.x3, mv.y3, mv.x4, mv.y4) &&\n                check_clean(mv.x4, mv.y4, mv.x1, mv.y1)) {\n                ans_moves.push_back(mv);\n                occupied[mv.x1][mv.y1] = true;\n                mark_side(mv.x1, mv.y1, mv.x2, mv.y2);\n                mark_side(mv.x2, mv.y2, mv.x3, mv.y3);\n                mark_side(mv.x3, mv.y3, mv.x4, mv.y4);\n                mark_side(mv.x4, mv.y4, mv.x1, mv.y1);\n            }\n        }\n    }\n\n    cout << ans_moves.size() << '\\n';\n    for (auto& m : ans_moves) {\n        cout << m.x1 << ' ' << m.y1 << ' ' << m.x2 << ' ' << m.y2\n             << ' ' << m.x3 << ' ' << m.y3 << ' ' << m.x4 << ' ' << m.y4 << '\\n';\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int, int>;\nusing vv = vector<vector<int>>;\n\npair<int, int> get_new_pos(const vv& g, int pr, int pc, char dir) {\n    int nr = pr, nc = pc;\n    if (dir == 'L') {\n        int rank_left = 0;\n        for (int c = 0; c < pc; ++c) if (g[pr][c] != 0) ++rank_left;\n        nc = rank_left;\n    } else if (dir == 'R') {\n        int total = 0;\n        for (int c = 0; c < 10; ++c) if (g[pr][c] != 0) ++total;\n        int rank_left = 0;\n        for (int c = 0; c < pc; ++c) if (g[pr][c] != 0) ++rank_left;\n        nc = (10 - total) + rank_left;\n    } else if (dir == 'F') {\n        int rank_top = 0;\n        for (int r = 0; r < pr; ++r) if (g[r][pc] != 0) ++rank_top;\n        nr = rank_top;\n    } else if (dir == 'B') {\n        int total = 0;\n        for (int r = 0; r < 10; ++r) if (g[r][pc] != 0) ++total;\n        int rank_top = 0;\n        for (int r = 0; r < pr; ++r) if (g[r][pc] != 0) ++rank_top;\n        nr = (10 - total) + rank_top;\n    }\n    return {nr, nc};\n}\n\nvoid simulate(vv& g, char dir) {\n    if (dir == 'F') {\n        for (int c = 0; c < 10; ++c) {\n            vector<int> lis;\n            for (int r = 0; r < 10; ++r) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            for (int r = 0; r < sz; ++r) g[r][c] = lis[r];\n            for (int r = sz; r < 10; ++r) g[r][c] = 0;\n        }\n    } else if (dir == 'B') {\n        for (int c = 0; c < 10; ++c) {\n            vector<int> lis;\n            for (int r = 0; r < 10; ++r) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            int off = 10 - sz;\n            for (int r = 0; r < off; ++r) g[r][c] = 0;\n            for (int r = 0; r < sz; ++r) g[off + r][c] = lis[r];\n        }\n    } else if (dir == 'L') {\n        for (int r = 0; r < 10; ++r) {\n            vector<int> lis;\n            for (int c = 0; c < 10; ++c) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            for (int c = 0; c < sz; ++c) g[r][c] = lis[c];\n            for (int c = sz; c < 10; ++c) g[r][c] = 0;\n        }\n    } else if (dir == 'R') {\n        for (int r = 0; r < 10; ++r) {\n            vector<int> lis;\n            for (int c = 0; c < 10; ++c) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            int off = 10 - sz;\n            for (int c = 0; c < off; ++c) g[r][c] = 0;\n            for (int c = 0; c < sz; ++c) g[r][off + c] = lis[c];\n        }\n    }\n}\n\nlong long compute(const vv& g) {\n    bool vis[10][10] = {};\n    int dr[] = {-1, 0, 1, 0};\n    int dc[] = {0, 1, 0, -1};\n    long long sumsq = 0;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            if (g[r][c] != 0 && !vis[r][c]) {\n                int flav = g[r][c];\n                queue<pii> q;\n                q.emplace(r, c);\n                vis[r][c] = true;\n                int sz = 1;\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    for (int d = 0; d < 4; ++d) {\n                        int nr = x + dr[d];\n                        int nc = y + dc[d];\n                        if (nr >= 0 && nr < 10 && nc >= 0 && nc < 10 &&\n                            !vis[nr][nc] && g[nr][nc] == flav) {\n                            vis[nr][nc] = true;\n                            q.emplace(nr, nc);\n                            ++sz;\n                        }\n                    }\n                }\n                sumsq += 1LL * sz * sz;\n            }\n        }\n    }\n    return sumsq;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    vector<int> f(101);\n    for (int i = 1; i <= 100; ++i) {\n        cin >> f[i];\n    }\n    vv grid(10, vector<int>(10, 0));\n    set<pii> empties;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            empties.emplace(r, c);\n        }\n    }\n    string dirs = \"FBLR\";\n    for (int t = 1; t <= 100; ++t) {\n        int p;\n        cin >> p;\n        auto it = empties.begin();\n        advance(it, p - 1);\n        auto [pr, pc] = *it;\n        grid[pr][pc] = f[t];\n        empties.erase(it);\n        int flav = f[t];\n\n        long long best_sc = -1;\n        int best_md = 999;\n        char best_dir = 'Z';\n        for (char d : dirs) {\n            vv temp = grid;\n            simulate(temp, d);\n            long long sc = compute(temp);\n            auto [nr, nc] = get_new_pos(grid, pr, pc, d);\n            int mind = 11;\n            for (int i = 0; i < 10; ++i) {\n                for (int j = 0; j < 10; ++j) {\n                    if (temp[i][j] == flav && (i != nr || j != nc)) {\n                        int dd = abs(i - nr) + abs(j - nc);\n                        if (dd < mind) mind = dd;\n                    }\n                }\n            }\n            if (sc > best_sc ||\n                (sc == best_sc && mind < best_md) ||\n                (sc == best_sc && mind == best_md && d < best_dir)) {\n                best_sc = sc;\n                best_md = mind;\n                best_dir = d;\n            }\n        }\n        cout << best_dir << endl;\n        simulate(grid, best_dir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <limits>\nusing namespace std;\n\nusing Eigen::MatrixXd;\nusing Eigen::SelfAdjointEigenSolver;\nusing Eigen::VectorXd;\n\nstring make_clique(int s, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  if (s < 2) return g;\n  s = min(s, N);\n  for (int i = 0; i < s; ++i) {\n    for (int j = i + 1; j < s; ++j) {\n      int pos = 0;\n      for (int a = 0; a < i; ++a) {\n        pos += N - 1 - a;\n      }\n      pos += j - i - 1;\n      g[pos] = '1';\n    }\n  }\n  return g;\n}\n\nstring make_star(int leaves, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  if (leaves < 1) return g;\n  leaves = min(leaves, N - 1);\n  for (int lv = 1; lv <= leaves; ++lv) {\n    int i = 0;\n    int j = lv;\n    int pos = 0;\n    for (int a = 0; a < i; ++a) {\n      pos += N - 1 - a;\n    }\n    pos += j - i - 1;\n    g[pos] = '1';\n  }\n  return g;\n}\n\nvector<double> get_sorted_lambda(const string& s, int N) {\n  int B = N * (N - 1) / 2;\n  MatrixXd A(N, N);\n  A.setZero();\n  int pos = 0;\n  for (int i = 0; i < N; ++i) {\n    for (int j = i + 1; j < N; ++j) {\n      double val = s[pos++] - '0';\n      A(i, j) = val;\n      A(j, i) = val;\n    }\n  }\n  SelfAdjointEigenSolver<MatrixXd> solver(A);\n  VectorXd ev = solver.eigenvalues();\n  vector<double> lambda(N);\n  for (int i = 0; i < N; ++i) {\n    lambda[i] = ev(i);\n  }\n  sort(lambda.rbegin(), lambda.rend());\n  return lambda;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n  int M;\n  double eps;\n  cin >> M >> eps;\n  int N = max(4, min(100, M));\n  cout << N << '\\n';\n\n  // Generate candidates\n  vector<string> cand_repr;\n  vector<vector<double>> cand_lamb;\n  // Cliques\n  for (int s = 1; s <= N; ++s) {\n    string g = make_clique(s, N);\n    cand_repr.push_back(g);\n    cand_lamb.push_back(get_sorted_lambda(g, N));\n  }\n  // Stars\n  for (int l = 1; l < N; ++l) {\n    string g = make_star(l, N);\n    cand_repr.push_back(g);\n    cand_lamb.push_back(get_sorted_lambda(g, N));\n  }\n  int nc = cand_repr.size();\n  vector<bool> used(nc, false);\n  vector<int> chosen;\n  for (int ck = 0; ck < M; ++ck) {\n    int best_ci = -1;\n    double max_mind = -1.0;\n    for (int ci = 0; ci < nc; ++ci) {\n      if (used[ci]) continue;\n      double mind = numeric_limits<double>::infinity();\n      for (int pi : chosen) {\n        double dd = 0.0;\n        const auto& l1 = cand_lamb[ci];\n        const auto& l2 = cand_lamb[pi];\n        for (int j = 0; j < N; ++j) {\n          double dif = l1[j] - l2[j];\n          dd += dif * dif;\n        }\n        if (dd < mind) mind = dd;\n      }\n      if (chosen.empty()) mind = 1e30;\n      if (mind > max_mind) {\n        max_mind = mind;\n        best_ci = ci;\n      }\n    }\n    assert(best_ci != -1);\n    used[best_ci] = true;\n    chosen.push_back(best_ci);\n  }\n\n  // Output graphs and store lambdas\n  vector<vector<double>> codebook_lamb(M);\n  for (int k = 0; k < M; ++k) {\n    int ci = chosen[k];\n    cout << cand_repr[ci] << '\\n';\n    codebook_lamb[k] = cand_lamb[ci];\n  }\n  cout << flush;\n\n  // Process queries\n  for (int q = 0; q < 100; ++q) {\n    string H;\n    cin >> H;\n    auto lh = get_sorted_lambda(H, N);\n    double best_d = numeric_limits<double>::infinity();\n    int tk = 0;\n    for (int k = 0; k < M; ++k) {\n      double dd = 0.0;\n      for (int j = 0; j < N; ++j) {\n        double dif = lh[j] - codebook_lamb[k][j];\n        dd += dif * dif;\n      }\n      if (dd < best_d) {\n        best_d = dd;\n        tk = k;\n      }\n    }\n    cout << tk << '\\n' << flush;\n  }\n  return 0;\n}","ahc017":"","ahc019":"","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Edge {\n    int u, v, id;\n    ll w;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    cin >> N >> M >> K;\n    vector<ll> xs(N + 1), ys(N + 1);\n    for (int i = 1; i <= N; ++i) {\n        cin >> xs[i] >> ys[i];\n    }\n    vector<Edge> edgs(M);\n    for (int j = 0; j < M; ++j) {\n        int u, v;\n        ll w;\n        cin >> u >> v >> w;\n        edgs[j] = {u, v, j + 1, w};\n    }\n    vector<ll> as(K + 1), bs(K + 1);\n    for (int k = 1; k <= K; ++k) {\n        cin >> as[k] >> bs[k];\n    }\n    // precompute distsq\n    vector<vector<ll>> distsq(N + 1, vector<ll>(K + 1));\n    for (int i = 1; i <= N; ++i) {\n        for (int k = 1; k <= K; ++k) {\n            ll dx = xs[i] - as[k];\n            ll dy = ys[i] - bs[k];\n            distsq[i][k] = dx * dx + dy * dy;\n        }\n    }\n    // terminals\n    set<int> terms;\n    terms.insert(1);\n    vector<int> assignn(K + 1);\n    for (int k = 1; k <= K; ++k) {\n        ll md = distsq[1][k];\n        int bi = 1;\n        for (int i = 2; i <= N; ++i) {\n            ll d2 = distsq[i][k];\n            if (d2 < md) {\n                md = d2;\n                bi = i;\n            }\n        }\n        assignn[k] = bi;\n        terms.insert(bi);\n    }\n    // UF\n    vector<int> par(N + 1);\n    for (int i = 0; i <= N; ++i) par[i] = i;\n    auto findf = [&](auto&& self, int x) -> int {\n        return par[x] == x ? x : par[x] = self(self, par[x]);\n    };\n    auto unitef = [&](int a, int b) {\n        int pa = findf(findf, a);\n        int pb = findf(findf, b);\n        if (pa == pb) return;\n        par[pa] = pb;\n    };\n    // MST\n    vector<int> B(M + 1, 0);\n    vector<Edge> sorted_edgs = edgs;\n    sort(sorted_edgs.begin(), sorted_edgs.end(), [](const Edge& a, const Edge& b) {\n        return a.w < b.w;\n    });\n    ll edge_cost = 0;\n    vector<int> mst_ids;\n    for (auto& e : sorted_edgs) {\n        int pu = findf(findf, e.u);\n        int pv = findf(findf, e.v);\n        if (pu != pv) {\n            unitef(e.u, e.v);\n            B[e.id] = 1;\n            edge_cost += e.w;\n            mst_ids.push_back(e.id);\n        }\n    }\n    // tree_adj\n    vector<vector<pair<int, int>>> tree_adj(N + 1);\n    for (int eid : mst_ids) {\n        const Edge& e = edgs[eid - 1];\n        tree_adj[e.u].emplace_back(e.v, eid);\n        tree_adj[e.v].emplace_back(e.u, eid);\n    }\n    // degrees\n    vector<int> deg(N + 1);\n    for (int i = 1; i <= N; ++i) {\n        deg[i] = tree_adj[i].size();\n    }\n    // prune queue\n    queue<int> to_prune;\n    for (int i = 1; i <= N; ++i) {\n        if (deg[i] == 1 && i != 1 && terms.find(i) == terms.end()) {\n            to_prune.push(i);\n        }\n    }\n    while (!to_prune.empty()) {\n        int u = to_prune.front();\n        to_prune.pop();\n        if (deg[u] != 1 || u == 1) continue;\n        if (terms.find(u) != terms.end()) continue;\n        // prune\n        auto [pu, eid] = tree_adj[u][0];\n        B[eid] = 0;\n        edge_cost -= edgs[eid - 1].w;\n        // update deg\n        deg[u] = 0;\n        deg[pu]--;\n        // check if pu becomes leaf\n        if (deg[pu] == 1 && pu != 1 && terms.find(pu) == terms.end()) {\n            to_prune.push(pu);\n        }\n    }\n    // now compute current component\n    vector<bool> vis(N + 1, false);\n    queue<int> qcomp;\n    qcomp.push(1);\n    vis[1] = true;\n    while (!qcomp.empty()) {\n        int u = qcomp.front();\n        qcomp.pop();\n        for (int jj = 1; jj <= M; ++jj) {\n            if (B[jj] == 0) continue;\n            const Edge& ee = edgs[jj - 1];\n            int vv = (ee.u == u ? ee.v : ee.u);\n            if (!vis[vv]) {\n                vis[vv] = true;\n                qcomp.push(vv);\n            }\n        }\n    }\n    vector<int> comp;\n    for (int i = 1; i <= N; ++i) {\n        if (vis[i]) comp.push_back(i);\n    }\n    // now assign needs\n    vector<ll> need(N + 1, 0);\n    for (int k = 1; k <= K; ++k) {\n        ll md2 = LLONG_MAX / 2;\n        int bi = -1;\n        for (int i : comp) {\n            ll d2 = distsq[i][k];\n            if (d2 < md2) {\n                md2 = d2;\n                bi = i;\n            }\n        }\n        need[bi] = max(need[bi], md2);\n    }\n    // calc P\n    auto calc_p = [](ll d2) -> int {\n        if (d2 == 0) return 0;\n        double sd = sqrt((double)d2);\n        int p = (int)ceil(sd);\n        while ((ll)p * p < d2) ++p;\n        while (p > 0 && (ll)(p - 1) * (p - 1) >= d2) --p;\n        return p;\n    };\n    vector<int> PP(N + 1, 0);\n    ll cov_cost = 0;\n    for (int i = 1; i <= N; ++i) {\n        if (need[i] > 0) {\n            PP[i] = calc_p(need[i]);\n            cov_cost += (ll)PP[i] * PP[i];\n        }\n    }\n    // output\n    for (int i = 1; i <= N; ++i) {\n        cout << PP[i];\n        cout << (i < N ? \" \" : \"\\n\");\n    }\n    for (int j = 1; j <= M; ++j) {\n        cout << B[j];\n        cout << (j < M ? \" \" : \"\\n\");\n    }\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int, int>;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N = 30;\n  int total = N * (N + 1) / 2;\n  vector<int> cum(N + 1, 0);\n  for (int i = 1; i <= N; ++i) {\n    cum[i] = cum[i - 1] + i;\n  }\n  vector<pii> coord(total);\n  vector<vector<int>> flat_pos(N, vector<int>(N));\n  for (int x = 0; x < N; ++x) {\n    for (int y = 0; y <= x; ++y) {\n      int id = cum[x] + y;\n      coord[id] = {x, y};\n      flat_pos[x][y] = id;\n    }\n  }\n  vector<int> a(total);\n  for (int i = 0; i < total; ++i) {\n    cin >> a[i];\n  }\n  vector<vector<int>> childs(total);\n  for (int x = 0; x < N - 1; ++x) {\n    for (int y = 0; y <= x; ++y) {\n      int p = flat_pos[x][y];\n      int l = flat_pos[x + 1][y];\n      int r = flat_pos[x + 1][y + 1];\n      childs[p] = {l, r};\n    }\n  }\n  // Simulate to choose best direction\n  auto get_swap_count = [&](bool ltr) -> int {\n    vector<int> arr = a;\n    int swaps = 0;\n    auto siftdown = [&](auto&& self, int node) -> void {\n      while (true) {\n        const auto& ch = childs[node];\n        if (ch.empty()) return;\n        int l = ch[0], r = ch[1];\n        int sm = node;\n        if (arr[l] < arr[sm]) sm = l;\n        if (arr[r] < arr[sm]) sm = r;\n        if (sm == node) return;\n        swap(arr[node], arr[sm]);\n        ++swaps;\n        node = sm;\n      }\n    };\n    for (int xx = N - 2; xx >= 0; --xx) {\n      if (ltr) {\n        for (int yy = 0; yy <= xx; ++yy) {\n          int node = flat_pos[xx][yy];\n          siftdown(siftdown, node);\n        }\n      } else {\n        for (int yy = xx; yy >= 0; --yy) {\n          int node = flat_pos[xx][yy];\n          siftdown(siftdown, node);\n        }\n      }\n    }\n    return swaps;\n  };\n  int cnt1 = get_swap_count(true);\n  int cnt2 = get_swap_count(false);\n  bool use_ltr = (cnt1 <= cnt2);\n  // Now perform the real one\n  vector<int> cur_a = a;\n  vector<vector<int>> ops;\n  auto real_siftdown = [&](auto&& self, int node) -> void {\n    while (true) {\n      const auto& ch = childs[node];\n      if (ch.empty()) return;\n      int l = ch[0], r = ch[1];\n      int sm = node;\n      if (cur_a[l] < cur_a[sm]) sm = l;\n      if (cur_a[r] < cur_a[sm]) sm = r;\n      if (sm == node) return;\n      swap(cur_a[node], cur_a[sm]);\n      int p1 = node, p2 = sm;\n      auto [x1, y1] = coord[p1];\n      auto [x2, y2] = coord[p2];\n      ops.push_back({x1, y1, x2, y2});\n      node = sm;\n    }\n  };\n  for (int xx = N - 2; xx >= 0; --xx) {\n    if (use_ltr) {\n      for (int yy = 0; yy <= xx; ++yy) {\n        int node = flat_pos[xx][yy];\n        real_siftdown(real_siftdown, node);\n      }\n    } else {\n      for (int yy = xx; yy >= 0; --yy) {\n        int node = flat_pos[xx][yy];\n        real_siftdown(real_siftdown, node);\n      }\n    }\n  }\n  cout << ops.size() << '\\n';\n  for (auto& op : ops) {\n    cout << op[0] << ' ' << op[1] << ' ' << op[2] << ' ' << op[3] << '\\n';\n  }\n}","toyota2023summer-final":"","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n, m;\n  cin >> n >> m;\n  vector<vector<int>> grid(n, vector<int>(n));\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      cin >> grid[i][j];\n    }\n  }\n  vector<vector<int>> touches0(m + 1, false);\n  vector<pair<int, int>> anchor(m + 1, make_pair(-1, -1));\n  vector<int> cursize(m + 1, 0);\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      int c = grid[i][j];\n      cursize[c]++;\n      if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {\n        touches0[c] = true;\n        if (anchor[c].first == -1) {\n          anchor[c] = {i, j};\n        }\n      }\n    }\n  }\n  vector<vector<int>> cnt(m + 1, vector<int>(m + 1, 0));\n  // horizontal\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n - 1; ++j) {\n      int a = grid[i][j], b = grid[i][j + 1];\n      if (a != b) {\n        int u = min(a, b), v = max(a, b);\n        cnt[u][v]++;\n      }\n    }\n  }\n  // vertical\n  for (int i = 0; i < n - 1; ++i) {\n    for (int j = 0; j < n; ++j) {\n      int a = grid[i][j], b = grid[i + 1][j];\n      if (a != b) {\n        int u = min(a, b), v = max(a, b);\n        cnt[u][v]++;\n      }\n    }\n  }\n\n  vector<pair<int, int>> dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n  auto peel = [&](vector<vector<int>> g, const vector<int>& init_size, auto&& self) -> pair<vector<vector<int>>, int> {\n    vector<vector<int>> out = g;\n    vector<int> size = init_size;\n    auto cnte = cnt;  // copy\n    bool changed = true;\n    while (changed) {\n      changed = false;\n      for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n          if (out[i][j] == 0) continue;\n          int c = out[i][j];\n          if (anchor[c].first == i && anchor[c].second == j) continue;\n          if (size[c] == 1) continue;\n          int same_n = 0;\n          bool can_zero = (i == 0 || i == n - 1 || j == 0 || j == n - 1);\n          bool safe_adj = true;\n          bool would_hurt_i = false;\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) continue;\n            int nc = out[ni][nj];\n            if (nc == c) ++same_n;\n            else if (nc == 0) can_zero = true;\n            else {\n              int u = min(c, nc), v = max(c, nc);\n              if (cnte[u][v] == 1) safe_adj = false;\n              if (!touches0[nc]) would_hurt_i = true;\n            }\n          }\n          if (same_n > 1 || !safe_adj || !can_zero || would_hurt_i) continue;\n          // remove\n          out[i][j] = 0;\n          size[c]--;\n          // update cnt\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n              int nc = out[ni][nj];\n              if (nc > 0 && nc != c) {\n                int u = min(c, nc), v = max(c, nc);\n                cnte[u][v]--;\n              }\n            }\n          }\n          changed = true;\n        }\n      }\n    }\n    int zeros = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        if (out[i][j] == 0) ++zeros;\n      }\n    }\n    return {out, zeros};\n  };\n\n  // first peel normal\n  auto [out1, z1] = peel(grid, cursize, peel);\n\n  // second peel reverse order\n  vector<vector<int>> grid_rev = grid;  // same\n  // but change scan to reverse\n  auto peel_rev = [&](vector<vector<int>> g, const vector<int>& init_size, auto&& self) -> pair<vector<vector<int>>, int> {\n    vector<vector<int>> out = g;\n    vector<int> size = init_size;\n    auto cnte = cnt;\n    bool changed = true;\n    while (changed) {\n      changed = false;\n      for (int i = n - 1; i >= 0; --i) {\n        for (int j = n - 1; j >= 0; --j) {\n          if (out[i][j] == 0) continue;\n          int c = out[i][j];\n          if (anchor[c].first == i && anchor[c].second == j) continue;\n          if (size[c] == 1) continue;\n          int same_n = 0;\n          bool can_zero = (i == 0 || i == n - 1 || j == 0 || j == n - 1);\n          bool safe_adj = true;\n          bool would_hurt_i = false;\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) continue;\n            int nc = out[ni][nj];\n            if (nc == c) ++same_n;\n            else if (nc == 0) can_zero = true;\n            else {\n              int u = min(c, nc), v = max(c, nc);\n              if (cnte[u][v] == 1) safe_adj = false;\n              if (!touches0[nc]) would_hurt_i = true;\n            }\n          }\n          if (same_n > 1 || !safe_adj || !can_zero || would_hurt_i) continue;\n          // remove\n          out[i][j] = 0;\n          size[c]--;\n          // update cnt\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n              int nc = out[ni][nj];\n              if (nc > 0 && nc != c) {\n                int u = min(c, nc), v = max(c, nc);\n                cnte[u][v]--;\n              }\n            }\n          }\n          changed = true;\n        }\n      }\n    }\n    int zeros = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        if (out[i][j] == 0) ++zeros;\n      }\n    }\n    return {out, zeros};\n  };\n  auto [out2, z2] = peel_rev(grid, cursize, peel_rev);\n\n  // pick the better one\n  vector<vector<int>> final_out = (z1 >= z2 ? out1 : out2);\n\n  // output\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      cout << final_out[i][j];\n      if (j < n - 1) cout << \" \";\n      else cout << \"\\n\";\n    }\n  }\n  return 0;\n}","ahc025":"","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n, m;\n  cin >> n >> m;\n  vector<vector<int>> stacks(m);\n  vector<int> location(n + 1, -1);\n  int h = n / m;\n  for (int i = 0; i < m; i++) {\n    stacks[i].resize(h);\n    for (int j = 0; j < h; j++) {\n      cin >> stacks[i][j];\n      location[stacks[i][j]] = i;\n    }\n  }\n  vector<pair<int, int>> ops;\n  int next_box = 1;\n  const int INF = INT_MAX / 2;\n  while (next_box <= n) {\n    int s = location[next_box];\n    if (s != -1 && !stacks[s].empty() && stacks[s].back() == next_box) {\n      // carry out\n      ops.emplace_back(next_box, 0);\n      stacks[s].pop_back();\n      location[next_box] = -1;\n      next_box++;\n      continue;\n    }\n    // expose by moving pile above\n    auto& stk = stacks[s];\n    auto it = find(stk.begin(), stk.end(), next_box);\n    size_t p = it - stk.begin();\n    size_t start_idx = p + 1;\n    int v_move = stk[start_idx];\n    int pile_top = stk.back();\n    // find best dest\n    int best_d = -1;\n    int best_score = -1;\n    for (int d = 0; d < m; d++) {\n      if (d == s) continue;\n      const auto& dstk = stacks[d];\n      bool is_empty = dstk.empty();\n      int tt = is_empty ? INF : dstk.back();\n      bool acceptable = is_empty || (tt > pile_top);\n      if (acceptable) {\n        int sc = tt;\n        if (sc > best_score) {\n          best_score = sc;\n          best_d = d;\n        }\n      }\n    }\n    if (best_d == -1) {\n      // fallback: max anywhere\n      best_score = -1;\n      for (int d = 0; d < m; d++) {\n        if (d == s) continue;\n        const auto& dstk = stacks[d];\n        int sc = dstk.empty() ? INF : dstk.back();\n        if (sc > best_score) {\n          best_score = sc;\n          best_d = d;\n        }\n      }\n    }\n    // perform move\n    auto& dstk = stacks[best_d];\n    vector<int> pile(stk.begin() + start_idx, stk.end());\n    stk.resize(start_idx);\n    dstk.insert(dstk.end(), pile.begin(), pile.end());\n    for (int b : pile) {\n      location[b] = best_d;\n    }\n    ops.emplace_back(v_move, best_d + 1);\n  }\n  for (auto [v, i] : ops) {\n    cout << v << ' ' << i << '\\n';\n  }\n}","ahc027":"","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing pii = pair<int, int>;\nint manh(int x1, int y1, int x2, int y2) { return abs(x1 - x2) + abs(y1 - y2); }\n\nstruct Emb {\n  array<pii, 5> seq;\n  int intd;\n};\n\nint compute_connect(const vector<int>& ord, const vector<Emb>& embs, pii init_pos, int M) {\n  int sumd = manh(init_pos.first, init_pos.second, embs[ord[0]].seq[0].first, embs[ord[0]].seq[0].second);\n  for (int i = 0; i < M - 1; ++i) {\n    sumd += manh(embs[ord[i]].seq[4].first, embs[ord[i]].seq[4].second,\n                 embs[ord[i + 1]].seq[0].first, embs[ord[i + 1]].seq[0].second);\n  }\n  return sumd;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M;\n  cin >> N >> M;\n  int si, sj;\n  cin >> si >> sj;\n  pii init_pos = {si, sj};\n  vector<string> grid(N);\n  for (auto& s : grid) cin >> s;\n  vector<vector<pii>> pos(26);\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      int c = grid[i][j] - 'A';\n      pos[c].emplace_back(i, j);\n    }\n  }\n  vector<string> ts(M);\n  for (auto& s : ts) cin >> s;\n  vector<Emb> embs(M);\n  const int INF = 1e9 + 5;\n  for (int k = 0; k < M; ++k) {\n    string t = ts[k];\n    vector<vector<pii>> cand(5);\n    for (int l = 0; l < 5; ++l) {\n      cand[l] = pos[t[l] - 'A'];\n    }\n    int sz[5];\n    for (int l = 0; l < 5; ++l) sz[l] = cand[l].size();\n    int min_d = INF;\n    Emb best;\n    for (int a0 = 0; a0 < sz[0]; ++a0) {\n      pii p0 = cand[0][a0];\n      for (int a1 = 0; a1 < sz[1]; ++a1) {\n        pii p1 = cand[1][a1];\n        int d01 = manh(p0.first, p0.second, p1.first, p1.second);\n        for (int a2 = 0; a2 < sz[2]; ++a2) {\n          pii p2 = cand[2][a2];\n          int d12 = manh(p1.first, p1.second, p2.first, p2.second);\n          int cd = d01 + d12;\n          if (cd >= min_d) continue;\n          for (int a3 = 0; a3 < sz[3]; ++a3) {\n            pii p3 = cand[3][a3];\n            int d23 = manh(p2.first, p2.second, p3.first, p3.second);\n            int cd2 = cd + d23;\n            if (cd2 >= min_d) continue;\n            for (int a4 = 0; a4 < sz[4]; ++a4) {\n              pii p4 = cand[4][a4];\n              int d34 = manh(p3.first, p3.second, p4.first, p4.second);\n              int tot = cd2 + d34;\n              if (tot < min_d) {\n                min_d = tot;\n                best.seq = {p0, p1, p2, p3, p4};\n                best.intd = tot;\n              }\n            }\n          }\n        }\n      }\n    }\n    embs[k] = best;\n  }\n  // NN greedy\n  vector<int> order_nn(M);\n  vector<bool> used(M, false);\n  pii curr = init_pos;\n  for (int st = 0; st < M; ++st) {\n    int bestk = -1;\n    int mindd = INF;\n    for (int k = 0; k < M; ++k) {\n      if (used[k]) continue;\n      pii stp = embs[k].seq[0];\n      int dd = manh(curr.first, curr.second, stp.first, stp.second);\n      if (dd < mindd || (dd == mindd && k < bestk)) {\n        mindd = dd;\n        bestk = k;\n      }\n    }\n    order_nn[st] = bestk;\n    used[bestk] = true;\n    curr = embs[bestk].seq[4];\n  }\n  vector<int> order1 = order_nn;\n  // 2-opt on order1\n  {\n    bool improved;\n    int passes = 0;\n    do {\n      improved = false;\n      for (int a = 0; a < M; ++a) {\n        for (int b = a + 1; b < M; ++b) {\n          pii prev_end = (a == 0 ? init_pos : embs[order1[a - 1]].seq[4]);\n          pii s_a = embs[order1[a]].seq[0];\n          int old1 = manh(prev_end.first, prev_end.second, s_a.first, s_a.second);\n          int old2 = (b == M - 1 ? 0\n                          : manh(embs[order1[b]].seq[4].first, embs[order1[b]].seq[4].second,\n                                 embs[order1[b + 1]].seq[0].first, embs[order1[b + 1]].seq[0].second));\n          pii s_b = embs[order1[b]].seq[0];\n          int new1 = manh(prev_end.first, prev_end.second, s_b.first, s_b.second);\n          pii e_a = embs[order1[a]].seq[4];\n          int new2 = (b == M - 1 ? 0\n                          : manh(e_a.first, e_a.second,\n                                 embs[order1[b + 1]].seq[0].first, embs[order1[b + 1]].seq[0].second));\n          int delta = new1 + new2 - old1 - old2;\n          if (delta < 0) {\n            reverse(order1.begin() + a, order1.begin() + b + 1);\n            improved = true;\n          }\n        }\n      }\n    } while (improved && ++passes < 200);\n  }\n  // Sorted order\n  vector<int> order2(M);\n  iota(order2.begin(), order2.end(), 0);\n  sort(order2.begin(), order2.end(), [&](int aa, int bb) {\n    int cia = (embs[aa].seq[0].first + embs[aa].seq[4].first) / 2;\n    int cja = (embs[aa].seq[0].second + embs[aa].seq[4].second) / 2;\n    int cib = (embs[bb].seq[0].first + embs[bb].seq[4].first) / 2;\n    int cjb = (embs[bb].seq[0].second + embs[bb].seq[4].second) / 2;\n    return cia * N + cja < cib * N + cjb;\n  });\n  vector<int> order3 = order2;\n  // 2-opt on order3\n  {\n    bool improved;\n    int passes = 0;\n    do {\n      improved = false;\n      for (int a = 0; a < M; ++a) {\n        for (int b = a + 1; b < M; ++b) {\n          pii prev_end = (a == 0 ? init_pos : embs[order3[a - 1]].seq[4]);\n          pii s_a = embs[order3[a]].seq[0];\n          int old1 = manh(prev_end.first, prev_end.second, s_a.first, s_a.second);\n          int old2 = (b == M - 1 ? 0\n                          : manh(embs[order3[b]].seq[4].first, embs[order3[b]].seq[4].second,\n                                 embs[order3[b + 1]].seq[0].first, embs[order3[b + 1]].seq[0].second));\n          pii s_b = embs[order3[b]].seq[0];\n          int new1 = manh(prev_end.first, prev_end.second, s_b.first, s_b.second);\n          pii e_a = embs[order3[a]].seq[4];\n          int new2 = (b == M - 1 ? 0\n                          : manh(e_a.first, e_a.second,\n                                 embs[order3[b + 1]].seq[0].first, embs[order3[b + 1]].seq[0].second));\n          int delta = new1 + new2 - old1 - old2;\n          if (delta < 0) {\n            reverse(order3.begin() + a, order3.begin() + b + 1);\n            improved = true;\n          }\n        }\n      }\n    } while (improved && ++passes < 200);\n  }\n  // Pick the best\n  int c1 = compute_connect(order1, embs, init_pos, M);\n  int c2 = compute_connect(order3, embs, init_pos, M);\n  vector<int> best_order = (c1 <= c2 ? order1 : order3);\n  // Build path\n  vector<pii> path;\n  for (int idx : best_order) {\n    for (auto p : embs[idx].seq) {\n      path.push_back(p);\n    }\n  }\n  // Output\n  for (auto [i, j] : path) {\n    cout << i << \" \" << j << '\\n';\n  }\n}","ahc030":"#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <random>\n#include <chrono>\n#include <cstdio>\n#include <cstring>\nusing namespace std;\nusing namespace Eigen;\n\nstruct State {\n    double score;\n    vector<int> choice;\n};\n\nstruct Placement {\n    int di, dj;\n    double score;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n    vector<vector<pair<int, int>>> shapes(M);\n    for (int m = 0; m < M; ++m) {\n        int d;\n        cin >> d;\n        shapes[m].resize(d);\n        for (int l = 0; l < d; ++l) {\n            cin >> shapes[m][l].first >> shapes[m][l].second;\n        }\n    }\n    int NN = N * N;\n    const int MAXNN = 400;\n    assert(NN <= MAXNN);\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    int QQ = NN / 2;\n    int kk_base = max(2, NN / 3);\n    double alpha = 1.0 - 2 * eps;\n    vector<double> ys(QQ);\n    vector<int> ks(QQ);\n    MatrixXd A(QQ, NN);\n    A.setZero();\n    for (int q = 0; q < QQ; ++q) {\n        vector<int> all_cells(NN);\n        iota(all_cells.begin(), all_cells.end(), 0);\n        shuffle(all_cells.begin(), all_cells.end(), rng);\n        vector<int> this_subset;\n        this_subset.reserve(kk_base);\n        int actual_k = min(kk_base, NN);\n        for (int t = 0; t < actual_k; ++t) {\n            this_subset.push_back(all_cells[t]);\n        }\n        printf(\"q %d\", (int)this_subset.size());\n        for (int cc : this_subset) {\n            printf(\" %d %d\", cc / N, cc % N);\n        }\n        printf(\"\\n\");\n        fflush(stdout);\n        int y;\n        cin >> y;\n        ys[q] = y;\n        ks[q] = this_subset.size();\n        for (int cc : this_subset) {\n            A(q, cc) = 1.0;\n        }\n    }\n    VectorXd sh(QQ);\n    for (int q = 0; q < QQ; ++q) {\n        double bq = eps * ks[q];\n        sh(q) = max(0.0, (ys[q] - bq) / alpha);\n    }\n    ColPivHouseholderQR<MatrixXd> decomp(A);\n    VectorXd vhat_raw = decomp.solve(sh);\n    vector<double> vhat_grid(NN);\n    for (int c = 0; c < NN; ++c) {\n        vhat_grid[c] = max(0.0, vhat_raw(c));\n    }\n    // Top placements\n    int LL = 12;\n    vector<vector<Placement>> top_placements(M);\n    for (int m = 0; m < M; ++m) {\n        const auto& shp = shapes[m];\n        int d = shp.size();\n        int hmax = 0, wmax = 0;\n        for (auto [ii, jj] : shp) {\n            hmax = max(hmax, ii);\n            wmax = max(wmax, jj);\n        }\n        int ndi = N - hmax;\n        int ndj = N - wmax;\n        vector<tuple<double, int, int>> cand;\n        cand.reserve((size_t)ndi * ndj);\n        for (int di = 0; di < ndi; ++di) {\n            for (int dj = 0; dj < ndj; ++dj) {\n                double sc = 0.0;\n                for (auto [ri, rj] : shp) {\n                    int x = di + ri;\n                    int y = dj + rj;\n                    sc += vhat_grid[x * N + y];\n                }\n                double avg_sc = sc / d;\n                cand.emplace_back(-avg_sc, di, dj);\n            }\n        }\n        sort(cand.begin(), cand.end());\n        int tk = min(LL, (int)cand.size());\n        top_placements[m].reserve(tk);\n        for (int l = 0; l < tk; ++l) {\n            auto [nsc, di, dj] = cand[l];\n            top_placements[m].push_back({di, dj, -nsc});\n        }\n    }\n    // Order by size desc\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return shapes[a].size() > shapes[b].size();\n    });\n    // Beam search\n    int BB = 100;\n    double lambda = 0.5;\n    int temp_cover[MAXNN];\n    vector<State> current_beam;\n    current_beam.reserve(BB);\n    current_beam.push_back({0.0, vector<int>(M, -1)});\n    for (int s = 0; s < M; ++s) {\n        int fld = order[s];\n        vector<State> next_beam;\n        next_beam.reserve(current_beam.size() * (size_t)LL);\n        for (const auto& st : current_beam) {\n            const auto& tpls = top_placements[fld];\n            for (size_t l = 0; l < tpls.size(); ++l) {\n                State nst = st;\n                nst.choice[fld] = (int)l;\n                memset(temp_cover, 0, (size_t)NN * sizeof(int));\n                for (int ff = 0; ff < M; ++ff) {\n                    int cl = nst.choice[ff];\n                    if (cl < 0) continue;\n                    const auto& pl = top_placements[ff][cl];\n                    const auto& shp = shapes[ff];\n                    for (auto p : shp) {\n                        int x = pl.di + p.first;\n                        int y = pl.dj + p.second;\n                        temp_cover[x * N + y]++;\n                    }\n                }\n                double sc = 0.0;\n                for (int c = 0; c < NN; ++c) {\n                    int cv = temp_cover[c];\n                    sc += vhat_grid[c] * cv - lambda * cv * (double)cv;\n                }\n                nst.score = sc;\n                next_beam.push_back(std::move(nst));\n            }\n        }\n        sort(next_beam.begin(), next_beam.end(), [](const State& aa, const State& bb) {\n            return aa.score > bb.score;\n        });\n        current_beam.clear();\n        current_beam.reserve(BB);\n        int nb = min(BB, (int)next_beam.size());\n        for (int bi = 0; bi < nb; ++bi) {\n            current_beam.push_back(std::move(next_beam[bi]));\n        }\n    }\n    const State& best = current_beam[0];\n    set<pair<int, int>> union_set;\n    for (int ff = 0; ff < M; ++ff) {\n        int cl = best.choice[ff];\n        if (cl < 0) continue;\n        const auto& pl = top_placements[ff][cl];\n        const auto& shp = shapes[ff];\n        for (auto p : shp) {\n            union_set.emplace(pl.di + p.first, pl.dj + p.second);\n        }\n    }\n    vector<pair<int, int>> ans(union_set.begin(), union_set.end());\n    printf(\"a %zu\", ans.size());\n    for (auto [i, j] : ans) {\n        printf(\" %d %d\", i, j);\n    }\n    printf(\"\\n\");\n    fflush(stdout);\n    int ver;\n    cin >> ver;\n    if (ver == 1) {\n        return 0;\n    }\n    // Fallback: drill all\n    vector<pair<int, int>> all_oil;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            printf(\"q 1 %d %d\\n\", i, j);\n            fflush(stdout);\n            int vv;\n            cin >> vv;\n            if (vv > 0) {\n                all_oil.emplace_back(i, j);\n            }\n        }\n    }\n    printf(\"a %zu\", all_oil.size());\n    for (auto [i, j] : all_oil) {\n        printf(\" %d %d\", i, j);\n    }\n    printf(\"\\n\");\n    fflush(stdout);\n    return 0;\n}","ahc031":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int W, D, N;\n  cin >> W >> D >> N;\n  vector<vector<int>> A(D, vector<int>(N));\n  for (int d = 0; d < D; ++d) {\n    for (int k = 0; k < N; ++k) {\n      cin >> A[d][k];\n    }\n  }\n  vector<long long> maxa(N, 0);\n  for (int k = 0; k < N; ++k) {\n    for (int d = 0; d < D; ++d) {\n      maxa[k] = max(maxa[k], (long long)A[d][k]);\n    }\n  }\n  vector<int> minw(N);\n  double total_minw = 0.0;\n  for (int k = 0; k < N; ++k) {\n    minw[k] = (maxa[k] + 999LL) / 1000LL;\n    total_minw += minw[k];\n  }\n  vector<int> width(N);\n  vector<int> order(N);\n  iota(order.begin(), order.end(), 0);\n  if (total_minw <= W) {\n    width = minw;\n  } else {\n    double scale = (double)W / total_minw;\n    for (int k = 0; k < N; ++k) {\n      width[k] = max(1, (int)(minw[k] * scale + 0.499999));\n    }\n  }\n  // Compute sumw\n  int sumw = 0;\n  for (int ww : width) sumw += ww;\n  int diff = W - sumw;\n  // Sort order by maxa descending for adding\n  sort(order.begin(), order.end(), [&](int x, int y) {\n    if (maxa[x] != maxa[y]) return maxa[x] > maxa[y];\n    return x < y;\n  });\n  // Distribute diff: add to largest if positive, subtract if negative\n  if (diff > 0) {\n    for (int i = 0; i < N && diff > 0; ++i) {\n      ++width[order[i]];\n      --diff;\n    }\n  } else if (diff < 0) {\n    // Sort order by maxa ascending for subtracting\n    sort(order.begin(), order.end(), [&](int x, int y) {\n      if (maxa[x] != maxa[y]) return maxa[x] < maxa[y];\n      return x < y;\n    });\n    for (int i = 0; i < N && diff < 0; ++i) {\n      if (width[order[i]] > 1) {\n        --width[order[i]];\n        ++diff;\n      }\n    }\n  }\n  // Now sum should be exactly W\n  vector<int> left_pos(N + 1, 0);\n  for (int k = 0; k < N; ++k) {\n    left_pos[k + 1] = left_pos[k] + width[k];\n  }\n  // Output\n  for (int d = 0; d < D; ++d) {\n    for (int k = 0; k < N; ++k) {\n      long long need = A[d][k];\n      long long ww = width[k];\n      long long h_need = (need + ww - 1) / ww;\n      int hh = min((long long)W, h_need);\n      int r1 = 0;\n      int c1 = left_pos[k];\n      int r2 = r1 + hh;\n      int c2 = left_pos[k + 1];\n      cout << r1 << ' ' << c1 << ' ' << r2 << ' ' << c2 << '\\n';\n    }\n  }\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll MOD = 998244353LL;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N = 9, M = 20, K = 81;\n  vector<vector<ll>> A(N, vector<ll>(N));\n  for (int i = 0; i < N; i++)\n    for (int j = 0; j < N; j++)\n      cin >> A[i][j];\n  vector<vector<vector<ll>>> stamps(M, vector<vector<ll>>(3, vector<ll>(3)));\n  for (int m = 0; m < M; m++) {\n    for (int i = 0; i < 3; i++)\n      for (int j = 0; j < 3; j++)\n        cin >> stamps[m][i][j];\n  }\n  vector<vector<ll>> current = A;\n  vector<tuple<int, int, int>> ops;\n  while ((int)ops.size() < K) {\n    ll best_delta = LLONG_MIN / 2;\n    int best_m = -1, best_p = -1, best_q = -1;\n    for (int m = 0; m < M; m++) {\n      for (int p = 0; p <= 6; p++) {\n        for (int q = 0; q <= 6; q++) {\n          ll delta = 0;\n          for (int di = 0; di < 3; di++) {\n            for (int dj = 0; dj < 3; dj++) {\n              int x = p + di, y = q + dj;\n              ll s = stamps[m][di][dj];\n              ll r = current[x][y];\n              ll nr = (r + s) % MOD;\n              delta += nr - r;\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    // Always add the best one, even if negative\n    ops.emplace_back(best_m, best_p, best_q);\n    for (int di = 0; di < 3; di++) {\n      for (int dj = 0; dj < 3; dj++) {\n        int x = best_p + di, y = best_q + dj;\n        ll s = stamps[best_m][di][dj];\n        current[x][y] = (current[x][y] + s) % MOD;\n      }\n    }\n  }\n  cout << ops.size() << '\\n';\n  for (auto [m, p, q] : ops) {\n    cout << m << ' ' << p << ' ' << q << '\\n';\n  }\n}","ahc033":"","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<string> get_moves(int r1, int c1, int r2, int c2) {\n    vector<string> res;\n    int dr = r2 - r1;\n    int dc = c2 - c1;\n    string vdir = \"\";\n    if (dr > 0) vdir = \"D\";\n    else if (dr < 0) vdir = \"U\";\n    string hdir = \"\";\n    if (dc > 0) hdir = \"R\";\n    else if (dc < 0) hdir = \"L\";\n    for (int i = 0; i < abs(dr); ++i) {\n        res.push_back(vdir);\n    }\n    for (int i = 0; i < abs(dc); ++i) {\n        res.push_back(hdir);\n    }\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    cin >> N;\n    vector<vector<int>> height(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> height[i][j];\n        }\n    }\n    vector<string> ops;\n    int cur_r = 0, cur_c = 0;\n    long long current_load = 0;\n    while (ops.size() < 95000) {\n        // check if done\n        bool is_done = (current_load == 0);\n        if (is_done) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (height[i][j] != 0) {\n                        is_done = false;\n                        goto next;\n                    }\n                }\n            }\n        }\n    next:;\n        if (is_done) break;\n\n        double best_score = 1e100;\n        int best_secondary = -1;\n        int best_r = -1, best_c = -1;\n        if (current_load > 0) {\n            // find best sink (closest, tie largest need)\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (height[i][j] < 0) {\n                        double dist = abs(i - cur_r) + abs(j - cur_c);\n                        int camt = -height[i][j];\n                        double cscore = dist;\n                        if (cscore < best_score || (cscore == best_score && camt > best_secondary)) {\n                            best_score = cscore;\n                            best_secondary = camt;\n                            best_r = i;\n                            best_c = j;\n                        }\n                    }\n                }\n            }\n        } else {\n            // find best source (min est_cost = D*100 + min_ds*(100 + amt), tie largest amt)\n            for (int sr = 0; sr < N; ++sr) {\n                for (int sc = 0; sc < N; ++sc) {\n                    if (height[sr][sc] > 0) {\n                        int camt = height[sr][sc];\n                        double D = abs(sr - cur_r) + abs(sc - cur_c);\n                        double min_ds = 1e9;\n                        int sink_sec = -1;\n                        for (int tr = 0; tr < N; ++tr) {\n                            for (int tc = 0; tc < N; ++tc) {\n                                if (height[tr][tc] < 0) {\n                                    double ds = abs(tr - sr) + abs(tc - sc);\n                                    int ssamt = -height[tr][tc];\n                                    if (ds < min_ds || (ds == min_ds && ssamt > sink_sec)) {\n                                        min_ds = ds;\n                                        sink_sec = ssamt;\n                                    }\n                                }\n                            }\n                        }\n                        double cscore = D * 100.0 + min_ds * (100.0 + (double)camt);\n                        if (cscore < best_score || (cscore == best_score && camt > best_secondary)) {\n                            best_score = cscore;\n                            best_secondary = camt;\n                            best_r = sr;\n                            best_c = sc;\n                        }\n                    }\n                }\n            }\n        }\n        if (best_r == -1) break;\n\n        // move\n        auto path = get_moves(cur_r, cur_c, best_r, best_c);\n        for (auto& p : path) {\n            ops.push_back(p);\n        }\n        cur_r = best_r;\n        cur_c = best_c;\n\n        // act\n        if (current_load > 0) {\n            // unload\n            long long need = -(long long)height[best_r][best_c];\n            long long d = min(current_load, need);\n            ops.push_back(\"-\" + to_string(d));\n            height[best_r][best_c] += (int)d;\n            current_load -= d;\n        } else {\n            // load\n            long long d = height[best_r][best_c];\n            ops.push_back(\"+\" + to_string(d));\n            height[best_r][best_c] -= (int)d;\n            current_load += d;\n        }\n    }\n    for (auto& s : ops) {\n        cout << s << '\\n';\n    }\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int N, M, T;\n    cin >> N >> M >> T;\n    const int P = N * N; // 36\n    const int S = 2 * N * (N - 1); // 60\n    vector<vector<int>> cur(S, vector<int>(M));\n    for (int k = 0; k < S; k++) {\n        for (int j = 0; j < M; j++) {\n            cin >> cur[k][j];\n        }\n    }\n\n    auto pid = [N](int i, int j) { return i * N + j; };\n\n    // adjacency list for positions 0..35\n    vector<vector<int>> adj(P);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N - 1; j++) {\n            int u = pid(i, j), v = pid(i, j + 1);\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n    }\n    for (int i = 0; i < N - 1; i++) {\n        for (int j = 0; j < N; j++) {\n            int u = pid(i, j), v = pid(i + 1, j);\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n    }\n\n    // edges for initial score computation\n    vector<pair<int, int>> edges;\n    for (int u = 0; u < P; u++) {\n        for (int v : adj[u]) {\n            if (v > u) {\n                edges.emplace_back(u, v);\n            }\n        }\n    }\n    assert((int)edges.size() == S);\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> uni_pos(0, P - 1);\n    uniform_real_distribution<double> uni_prob(0.0, 1.0);\n\n    for (int t = 0; t < T; t++) {\n        // compute values\n        vector<long long> val(S, 0);\n        for (int k = 0; k < S; k++) {\n            for (int j = 0; j < M; j++) {\n                val[k] += cur[k][j];\n            }\n        }\n\n        // top 36 global indices, sorted by val desc, then index\n        vector<int> idx(S);\n        iota(idx.begin(), idx.end(), 0);\n        sort(idx.begin(), idx.end(), [&](int a, int b) {\n            if (val[a] != val[b]) return val[a] > val[b];\n            return a < b;\n        });\n        vector<int> top36;\n        for (int i = 0; i < P; i++) top36.push_back(idx[i]);\n\n        // local seeds values\n        vector<vector<int>> loc(P, vector<int>(M));\n        vector<long long> local_val(P);\n        for (int li = 0; li < P; li++) {\n            int gi = top36[li];\n            local_val[li] = val[gi];\n            for (int m = 0; m < M; m++) {\n                loc[li][m] = cur[gi][m];\n            }\n        }\n\n        // sort local ids by local_val desc\n        vector<int> local_order(P);\n        iota(local_order.begin(), local_order.end(), 0);\n        sort(local_order.begin(), local_order.end(), [&](int a, int b) {\n            if (local_val[a] != local_val[b]) return local_val[a] > local_val[b];\n            return a < b;\n        });\n\n        // initial assignment: row-major order of sorted local\n        vector<int> assignment(P);\n        int pp = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                assignment[pid(i, j)] = local_order[pp++];\n            }\n        }\n\n        // supersum lambda\n        auto supersum = [&](int lid1, int lid2) -> int {\n            int s = 0;\n            for (int m = 0; m < M; m++) {\n                s += max(loc[lid1][m], loc[lid2][m]);\n            }\n            return s;\n        };\n\n        // initial score\n        long long score = 0;\n        for (auto [u, v] : edges) {\n            score += supersum(assignment[u], assignment[v]);\n        }\n\n        // SA parameters\n        const int MAX_ITER = 300000;\n        const double TEMP_START = 8000.0;\n        const double COOL_RATE = 0.9993;\n        double cur_temp = TEMP_START;\n\n        for (int iter = 0; iter < MAX_ITER; iter++) {\n            int a = uni_pos(rng);\n            int b = uni_pos(rng);\n            if (a == b) continue;\n\n            int sidA = assignment[a];\n            int sidB = assignment[b];\n\n            long long delta = 0;\n\n            // neighbors of a except b\n            for (int n : adj[a]) {\n                if (n == b) continue;\n                int sidN = assignment[n];\n                delta += supersum(sidB, sidN) - supersum(sidA, sidN);\n            }\n            // neighbors of b except a\n            for (int n : adj[b]) {\n                if (n == a) continue;\n                int sidN = assignment[n];\n                delta += supersum(sidA, sidN) - supersum(sidB, sidN);\n            }\n\n            bool accept = false;\n            if (delta >= 0) {\n                accept = true;\n            } else {\n                double p = exp((double)delta / cur_temp);\n                if (uni_prob(rng) < p) {\n                    accept = true;\n                }\n            }\n            if (accept) {\n                swap(assignment[a], assignment[b]);\n                score += delta;\n            }\n\n            cur_temp *= COOL_RATE;\n            if (cur_temp < 1.0) break;\n        }\n\n        // build grid\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                int pos = pid(i, j);\n                int lid = assignment[pos];\n                grid[i][j] = top36[lid];\n            }\n        }\n\n        // output\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << grid[i][j];\n                if (j + 1 < N) cout << \" \";\n                else cout << \"\\n\";\n            }\n        }\n        cout.flush();\n\n        // read new seeds\n        for (int k = 0; k < S; k++) {\n            for (int m = 0; m < M; m++) {\n                cin >> cur[k][m];\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, V;\n  cin >> N >> M >> V;\n  vector<string> S(N), T(N);\n  for (auto& str : S) cin >> str;\n  for (auto& str : T) cin >> str;\n  vector<vector<int>> has(N, vector<int>(N, 0));\n  vector<vector<int>> targ(N, vector<int>(N, 0));\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      has[i][j] = S[i][j] - '0';\n      targ[i][j] = T[i][j] - '0';\n    }\n  }\n\n  // Compute center for initial position\n  int sumx = 0, sumy = 0, cnt = 0;\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      if (has[i][j]) {\n        sumx += i;\n        sumy += j;\n        ++cnt;\n      }\n    }\n  }\n  int rx = cnt ? sumx / cnt : N / 2;\n  int ry = cnt ? sumy / cnt : N / 2;\n  rx = max(0, min(N - 1, rx));\n  ry = max(0, min(N - 1, ry));\n\n  // Design simple tree: V' = 2, length N/2\n  int Vp = 2;\n  int L = max(1, N / 2);\n  cout << Vp << '\\n';\n  cout << 0 << \" \" << L << '\\n';\n  cout << rx << \" \" << ry << '\\n';\n\n  // Simulation state\n  vector<pair<int, int>> extras, holes;\n  bool dirty = true;\n  auto rebuild = [&]() {\n    extras.clear();\n    holes.clear();\n    for (int i = 0; i < N; ++i) {\n      for (int j = 0; j < N; ++j) {\n        if (has[i][j] && !targ[i][j]) extras.emplace_back(i, j);\n        if (!has[i][j] && targ[i][j]) holes.emplace_back(i, j);\n      }\n    }\n    dirty = false;\n  };\n\n  // Directions: 0=R,1=D,2=L,3=U\n  int dir_dx[4] = {0, 1, 0, -1};\n  int dir_dy[4] = {1, 0, -1, 0};\n\n  // Current state\n  int cur_rx = rx, cur_ry = ry;\n  int edir = 0;\n  bool holding = false;\n\n  vector<string> ops;\n  const int MAX_TURNS = 100000;\n  while (ops.size() < MAX_TURNS) {\n    if (dirty) rebuild();\n\n    // Current finger position\n    int fx = cur_rx + L * dir_dx[edir];\n    int fy = cur_ry + L * dir_dy[edir];\n\n    // Find best_target pos\n    pair<int, int> best_target{-1, -1};\n    int best_dist = INT_MAX;\n    int best_lex = INT_MAX;\n    bool target_empty = false;\n    if (holding) {\n      if (holes.empty()) {\n        target_empty = true;\n      } else {\n        for (auto p : holes) {\n          int i = p.first, j = p.second;\n          int d = abs(fx - i) + abs(fy - j);\n          int lex = i * N + j;\n          if (d < best_dist || (d == best_dist && lex < best_lex)) {\n            best_dist = d;\n            best_lex = lex;\n            best_target = p;\n          }\n        }\n      }\n    } else {\n      if (extras.empty()) {\n        target_empty = true;\n      } else {\n        for (auto p : extras) {\n          int i = p.first, j = p.second;\n          int d = abs(fx - i) + abs(fy - j);\n          int lex = i * N + j;\n          if (d < best_dist || (d == best_dist && lex < best_lex)) {\n            best_dist = d;\n            best_lex = lex;\n            best_target = p;\n          }\n        }\n      }\n    }\n    if (target_empty) {\n      best_target = {fx, fy};\n      best_dist = 0;\n    }\n\n    // Lambda for ndist after action\n    auto get_ndist = [&](int px, int py, bool hld) -> int {\n      if (!(0 <= px && px < N && 0 <= py && py < N)) return 999;\n      auto& lst = hld ? holes : extras;\n      if (lst.empty()) return 0;\n      int md = INT_MAX;\n      for (auto p : lst) {\n        md = min(md, abs(px - p.first) + abs(py - p.second));\n      }\n      return md;\n    };\n\n    // Try all actions\n    char best_mv = '.', best_rt = '.', best_pk = '.';\n    int best_score = INT_MIN;\n    string mv_opts = \".UDLR\";\n    string rt_opts = \".LR\";\n    string pk_opts = \".P\";\n    for (char mv : mv_opts) {\n      int nrx = cur_rx, nry = cur_ry;\n      int ddx = 0, ddy = 0;\n      if (mv == 'U') {\n        ddx = -1;\n      } else if (mv == 'D') {\n        ddx = 1;\n      } else if (mv == 'L') {\n        ddy = -1;\n      } else if (mv == 'R') {\n        ddy = 1;\n      }\n      nrx += ddx;\n      nry += ddy;\n      if (nrx < 0 || nrx >= N || nry < 0 || nry >= N) continue;\n\n      for (char rt : rt_opts) {\n        int rdelta = 0;\n        if (rt == 'R') rdelta = 1;\n        else if (rt == 'L') rdelta = 3;\n        int nedir = (edir + rdelta) % 4;\n\n        int nfx = nrx + L * dir_dx[nedir];\n        int nfy = nry + L * dir_dy[nedir];\n        bool inb = (0 <= nfx && nfx < N && 0 <= nfy && nfy < N);\n\n        for (char pk : pk_opts) {\n          // Compute new_holding\n          bool new_holding = holding;\n          bool act_success = false;\n          bool good_act = false;\n          if (pk == 'P' && inb) {\n            if (holding) {\n              // try place\n              if (has[nfx][nfy] == 0) {\n                act_success = true;\n                new_holding = false;\n                if (targ[nfx][nfy]) good_act = true;\n              }\n            } else {\n              // try grab\n              if (has[nfx][nfy] == 1) {\n                act_success = true;\n                new_holding = true;\n                if (!targ[nfx][nfy]) good_act = true;\n              }\n            }\n          }\n\n          // ndist\n          int ndist = get_ndist(nfx, nfy, new_holding);\n\n          // target dist\n          int tdist = (best_target.first < 0 ? 0 : abs(nfx - best_target.first) + abs(nfy - best_target.second));\n\n          int score = -ndist * 100 - tdist * 5;\n          if (act_success && good_act) score += 50000;\n          else if (act_success) score += 5000;\n          if (inb) score += 100;\n\n          // action cost\n          if (mv != '.') score -= 3;\n          if (rt != '.') score -= 3;\n          if (pk != '.') score -= 1;\n\n          if (score > best_score) {\n            best_score = score;\n            best_mv = mv;\n            best_rt = rt;\n            best_pk = pk;\n          }\n        }\n      }\n    }\n\n    // Output op\n    string op(4, '.');\n    op[0] = best_mv;\n    op[1] = best_rt;\n    op[3] = best_pk;\n    cout << op << '\\n';\n    ops.push_back(op);\n\n    // Apply\n    int ddx = 0, ddy = 0;\n    if (best_mv == 'U') ddx = -1;\n    else if (best_mv == 'D') ddx = 1;\n    else if (best_mv == 'L') ddy = -1;\n    else if (best_mv == 'R') ddy = 1;\n    cur_rx += ddx;\n    cur_ry += ddy;\n\n    int rdelta = 0;\n    if (best_rt == 'R') rdelta = 1;\n    else if (best_rt == 'L') rdelta = 3;\n    edir = (edir + rdelta) % 4;\n\n    int nfx = cur_rx + L * dir_dx[edir];\n    int nfy = cur_ry + L * dir_dy[edir];\n    bool inb = (0 <= nfx && nfx < N && 0 <= nfy && nfy < N);\n    if (best_pk == 'P' && inb) {\n      if (holding) {\n        if (has[nfx][nfy] == 0) {\n          has[nfx][nfy] = 1;\n          holding = false;\n          dirty = true;\n        }\n      } else {\n        if (has[nfx][nfy] == 1) {\n          has[nfx][nfy] = 0;\n          holding = true;\n          dirty = true;\n        }\n      }\n    }\n\n    // Check done\n    if (extras.empty() && !holding) break;\n  }\n\n  return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n};\n\nvector<Point> make_small_rect(const Point& p) {\n    vector<Point> res(4);\n    bool right_ok = (p.x < 100000);\n    bool up_ok = (p.y < 100000);\n    bool left_ok = (p.x > 0);\n    bool down_ok = (p.y > 0);\n\n    int lx = p.x;\n    int rx = right_ok ? p.x + 1 : p.x;\n    if (lx == rx && left_ok) {\n        lx = p.x - 1;\n    }\n    int ly = p.y;\n    int ry = up_ok ? p.y + 1 : p.y;\n    if (ly == ry && down_ok) {\n        ly = p.y - 1;\n    }\n    res[0] = {lx, ly};\n    res[1] = {rx, ly};\n    res[2] = {rx, ry};\n    res[3] = {lx, ry};\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<Point> mack(N);\n    for (auto& p : mack) {\n        cin >> p.x >> p.y;\n    }\n    vector<Point> sard(N);\n    for (auto& p : sard) {\n        cin >> p.x >> p.y;\n    }\n\n    // Compute global BB\n    int gminx = INT_MAX, gmaxx = INT_MIN, gmin_y = INT_MAX, gmax_y = INT_MIN;\n    for (const auto& p : mack) {\n        gminx = min(gminx, p.x);\n        gmaxx = max(gmaxx, p.x);\n        gmin_y = min(gmin_y, p.y);\n        gmax_y = max(gmax_y, p.y);\n    }\n    int g_b = 0;\n    for (const auto& s : sard) {\n        if (gminx <= s.x && s.x <= gmaxx && gmin_y <= s.y && s.y <= gmax_y) g_b++;\n    }\n    int g_prof = N - g_b;\n\n    // Best so far\n    int best_profit = 1;  // For small rect, a-b=1\n    int best_min_x = mack[0].x;\n    int best_max_x = mack[0].x;\n    int best_min_y = mack[0].y;\n    int best_max_y = mack[0].y;\n    // Update with global if better and valid\n    if (g_prof > best_profit && gmaxx > gminx && gmax_y > gmin_y) {\n        best_profit = g_prof;\n        best_min_x = gminx;\n        best_max_x = gmaxx;\n        best_min_y = gmin_y;\n        best_max_y = gmax_y;\n    }\n\n    vector<int> thresholds = {500, 1000, 2000, 3000, 4000, 5000, 6000, 8000, 10000, 12000, 15000, 20000, 30000};\n\n    // X-sorted\n    {\n        auto mack_sort = mack;\n        sort(mack_sort.begin(), mack_sort.end(), [](const Point& a, const Point& b) {\n            return a.x < b.x || (a.x == b.x && a.y < b.y);\n        });\n        for (int th : thresholds) {\n            int ii = 0;\n            while (ii < N) {\n                int jj = ii;\n                while (jj + 1 < N && mack_sort[jj + 1].x - mack_sort[jj].x <= th) ++jj;\n                int aa = jj - ii + 1;\n                if (aa >= 1) {\n                    int mx1 = mack_sort[ii].x;\n                    int mx2 = mack_sort[jj].x;\n                    int my1 = INT_MAX, my2 = INT_MIN;\n                    for (int k = ii; k <= jj; ++k) {\n                        my1 = min(my1, mack_sort[k].y);\n                        my2 = max(my2, mack_sort[k].y);\n                    }\n                    int bb_cnt = 0;\n                    for (const auto& s : sard) {\n                        if (mx1 <= s.x && s.x <= mx2 && my1 <= s.y && s.y <= my2) ++bb_cnt;\n                    }\n                    int prof = aa - bb_cnt;\n                    if (prof > best_profit && mx2 > mx1 && my2 > my1) {\n                        best_profit = prof;\n                        best_min_x = mx1;\n                        best_max_x = mx2;\n                        best_min_y = my1;\n                        best_max_y = my2;\n                    }\n                }\n                ii = jj + 1;\n            }\n        }\n    }\n\n    // Y-sorted\n    {\n        auto mack_sort = mack;\n        sort(mack_sort.begin(), mack_sort.end(), [](const Point& a, const Point& b) {\n            return a.y < b.y || (a.y == b.y && a.x < b.x);\n        });\n        for (int th : thresholds) {\n            int ii = 0;\n            while (ii < N) {\n                int jj = ii;\n                while (jj + 1 < N && mack_sort[jj + 1].y - mack_sort[jj].y <= th) ++jj;\n                int aa = jj - ii + 1;\n                if (aa >= 1) {\n                    int my1 = mack_sort[ii].y;\n                    int my2 = mack_sort[jj].y;\n                    int mx1 = INT_MAX, mx2 = INT_MIN;\n                    for (int k = ii; k <= jj; ++k) {\n                        mx1 = min(mx1, mack_sort[k].x);\n                        mx2 = max(mx2, mack_sort[k].x);\n                    }\n                    int bb_cnt = 0;\n                    for (const auto& s : sard) {\n                        if (mx1 <= s.x && s.x <= mx2 && my1 <= s.y && s.y <= my2) ++bb_cnt;\n                    }\n                    int prof = aa - bb_cnt;\n                    if (prof > best_profit && mx2 > mx1 && my2 > my1) {\n                        best_profit = prof;\n                        best_min_x = mx1;\n                        best_max_x = mx2;\n                        best_min_y = my1;\n                        best_max_y = my2;\n                    }\n                }\n                ii = jj + 1;\n            }\n        }\n    }\n\n    // Fallback check: if best is degenerate, make small rect\n    if (best_max_x == best_min_x || best_max_y == best_min_y) {\n        vector<Point> small = make_small_rect(mack[0]);\n        best_min_x = min({small[0].x, small[1].x, small[2].x, small[3].x});\n        best_max_x = max({small[0].x, small[1].x, small[2].x, small[3].x});\n        best_min_y = min({small[0].y, small[1].y, small[2].y, small[3].y});\n        best_max_y = max({small[0].y, small[1].y, small[2].y, small[3].y});\n    }\n\n    // Output\n    cout << 4 << '\\n';\n    cout << best_min_x << \" \" << best_min_y << '\\n';\n    cout << best_max_x << \" \" << best_min_y << '\\n';\n    cout << best_max_x << \" \" << best_max_y << '\\n';\n    cout << best_min_x << \" \" << best_max_y << '\\n';\n\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Rect {\n    ll xl, xr, yt, yb;\n};\n\nstruct State {\n    vector<Rect> pos;\n    vector<array<int, 4>> placed_seq;\n    int next_id;\n    ll cur_maxw, cur_maxh, penalty;\n};\n\nll get_score(const State& s) {\n    return s.cur_maxw + s.cur_maxh + s.penalty;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int N, T;\n    ll sigma;\n    cin >> N >> T >> sigma;\n    vector<ll> est_w(N), est_h(N);\n    for (int i = 0; i < N; i++) {\n        cin >> est_w[i] >> est_h[i];\n    }\n\n    const int BEAM_SIZE = 30;\n    vector<State> beam(1);\n    beam[0].pos.assign(N, Rect{-1, -1, -1, -1});\n    beam[0].placed_seq.clear();\n    beam[0].next_id = 0;\n    beam[0].cur_maxw = 0;\n    beam[0].cur_maxh = 0;\n    beam[0].penalty = 0;\n\n    for (int step = 0; step < N; step++) {\n        vector<State> next_beam;\n        next_beam.reserve(20000);\n        for (const auto& st : beam) {\n            int nid = st.next_id;\n            if (nid == N) continue;\n\n            // Skip option\n            {\n                State news = st;\n                news.penalty += est_w[nid] + est_h[nid];\n                news.next_id++;\n                next_beam.push_back(news);\n            }\n\n            // Place options\n            vector<int> poss_b;\n            poss_b.reserve(N);\n            poss_b.push_back(-1);\n            for (int j = 0; j < nid; j++) {\n                if (st.pos[j].xl >= 0) {\n                    poss_b.push_back(j);\n                }\n            }\n            for (int rot = 0; rot < 2; rot++) {\n                ll ww = (rot ? est_h[nid] : est_w[nid]);\n                ll hh = (rot ? est_w[nid] : est_h[nid]);\n                for (int dd = 0; dd < 2; dd++) {\n                    for (int ibb : poss_b) {\n                        int bb = ibb;\n                        ll xl_, xr_, yt_, yb_;\n                        if (dd == 0) {  // U\n                            xl_ = (bb == -1 ? 0LL : st.pos[bb].xr);\n                            xr_ = xl_ + ww;\n                            yt_ = 0;\n                            for (int j = 0; j < nid; j++) {\n                                if (st.pos[j].xl < 0) continue;\n                                ll lx = max(st.pos[j].xl, xl_);\n                                ll rx = min(st.pos[j].xr, xr_);\n                                if (lx < rx) {\n                                    yt_ = max(yt_, st.pos[j].yb);\n                                }\n                            }\n                            yb_ = yt_ + hh;\n                        } else {  // L\n                            yt_ = (bb == -1 ? 0LL : st.pos[bb].yb);\n                            yb_ = yt_ + hh;\n                            xl_ = 0;\n                            for (int j = 0; j < nid; j++) {\n                                if (st.pos[j].xl < 0) continue;\n                                ll ty = max(st.pos[j].yt, yt_);\n                                ll by_ = min(st.pos[j].yb, yb_);\n                                if (ty < by_) {\n                                    xl_ = max(xl_, st.pos[j].xr);\n                                }\n                            }\n                            xr_ = xl_ + ww;\n                        }\n                        State news = st;\n                        news.pos[nid] = {xl_, xr_, yt_, yb_};\n                        news.next_id++;\n                        news.cur_maxw = max(st.cur_maxw, xr_);\n                        news.cur_maxh = max(st.cur_maxh, yb_);\n                        news.placed_seq.push_back({nid, rot, dd, bb});\n                        next_beam.push_back(news);\n                    }\n                }\n            }\n        }\n        // Sort by score ascending\n        sort(next_beam.begin(), next_beam.end(), [](const State& a, const State& b) {\n            return get_score(a) < get_score(b);\n        });\n        // Keep top BEAM_SIZE\n        beam.clear();\n        beam.reserve(BEAM_SIZE);\n        int keep_cnt = min(BEAM_SIZE, (int)next_beam.size());\n        for (int k = 0; k < keep_cnt; k++) {\n            beam.push_back(std::move(next_beam[k]));\n        }\n    }\n\n    // Best config\n    State best_st = beam[0];\n    auto& config = best_st.placed_seq;\n    int nn = config.size();\n\n    // Now repeat for T turns\n    for (int t = 0; t < T; t++) {\n        cout << nn << '\\n';\n        for (const auto& arr : config) {\n            cout << arr[0] << ' ' << arr[1] << ' ' << (arr[2] == 0 ? \"U\" : \"L\") << ' ' << arr[3] << '\\n';\n        }\n        cout.flush();\n        ll Wp, Hp;\n        cin >> Wp >> Hp;\n    }\n    return 0;\n}","ahc041":"","ahc042":"#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 = 20;\n    vector<string> board(N);\n    vector<vector<char>> has_x(N, vector<char>(N, 0));\n    int total_x = 0;\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                has_x[i][j] = 1;\n                ++total_x;\n            }\n        }\n    }\n    \n    // Precompute kmax\n    vector<int> row_left_kmax(N), row_right_kmax(N);\n    for (int r = 0; r < N; ++r) {\n        int first_o = N;\n        for (int j = 0; j < N; ++j) {\n            if (board[r][j] == 'o') {\n                first_o = j;\n                break;\n            }\n        }\n        row_left_kmax[r] = first_o;\n        \n        int last_o = -1;\n        for (int j = N - 1; j >= 0; --j) {\n            if (board[r][j] == 'o') {\n                last_o = j;\n                break;\n            }\n        }\n        row_right_kmax[r] = N - (last_o + 1);\n    }\n    \n    vector<int> col_up_kmax(N), col_down_kmax(N);\n    for (int c = 0; c < N; ++c) {\n        int first_o = N;\n        for (int i = 0; i < N; ++i) {\n            if (board[i][c] == 'o') {\n                first_o = i;\n                break;\n            }\n        }\n        col_up_kmax[c] = first_o;\n        \n        int last_o = -1;\n        for (int i = N - 1; i >= 0; --i) {\n            if (board[i][c] == 'o') {\n                last_o = i;\n                break;\n            }\n        }\n        col_down_kmax[c] = N - (last_o + 1);\n    }\n    \n    using Op = pair<char, int>;\n    vector<Op> best_ops;\n    size_t best_t = SIZE_MAX;\n    \n    for (int var_id = 0; var_id < 3; ++var_id) {\n        auto temp_board = has_x;\n        int rem = total_x;\n        vector<Op> ops;\n        while (rem > 0) {\n            double best_score = -1.0;\n            int best_cnt = 0;\n            int best_kk = 1000;\n            char best_d = ' ';\n            int best_p = -1;\n            \n            // Row left\n            for (int r = 0; r < N; ++r) {\n                int kmaxx = row_left_kmax[r];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    for (int j = 0; j < kk; ++j) {\n                        if (temp_board[r][j]) ++cntt;\n                    }\n                    if (cntt == 0) continue;\n                    double ratio = static_cast<double>(cntt) / kk;\n                    double score;\n                    if (var_id == 0) {\n                        score = ratio;\n                    } else if (var_id == 1) {\n                        score = 10000.0 * cntt + ratio;\n                    } else {\n                        score = cntt * static_cast<double>(cntt) / kk;\n                    }\n                    bool better = false;\n                    if (score > best_score + 1e-9) {\n                        better = true;\n                    } else if (abs(score - best_score) < 1e-9) {\n                        if (cntt > best_cnt || (cntt == best_cnt && kk < best_kk)) {\n                            better = true;\n                        }\n                    }\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'L';\n                        best_p = r;\n                    }\n                }\n            }\n            \n            // Row right\n            for (int r = 0; r < N; ++r) {\n                int kmaxx = row_right_kmax[r];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    int startj = N - kk;\n                    for (int j = startj; j < N; ++j) {\n                        if (temp_board[r][j]) ++cntt;\n                    }\n                    if (cntt == 0) continue;\n                    double ratio = static_cast<double>(cntt) / kk;\n                    double score;\n                    if (var_id == 0) {\n                        score = ratio;\n                    } else if (var_id == 1) {\n                        score = 10000.0 * cntt + ratio;\n                    } else {\n                        score = cntt * static_cast<double>(cntt) / kk;\n                    }\n                    bool better = false;\n                    if (score > best_score + 1e-9) {\n                        better = true;\n                    } else if (abs(score - best_score) < 1e-9) {\n                        if (cntt > best_cnt || (cntt == best_cnt && kk < best_kk)) {\n                            better = true;\n                        }\n                    }\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'R';\n                        best_p = r;\n                    }\n                }\n            }\n            \n            // Col up\n            for (int c = 0; c < N; ++c) {\n                int kmaxx = col_up_kmax[c];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    for (int i = 0; i < kk; ++i) {\n                        if (temp_board[i][c]) ++cntt;\n                    }\n                    if (cntt == 0) continue;\n                    double ratio = static_cast<double>(cntt) / kk;\n                    double score;\n                    if (var_id == 0) {\n                        score = ratio;\n                    } else if (var_id == 1) {\n                        score = 10000.0 * cntt + ratio;\n                    } else {\n                        score = cntt * static_cast<double>(cntt) / kk;\n                    }\n                    bool better = false;\n                    if (score > best_score + 1e-9) {\n                        better = true;\n                    } else if (abs(score - best_score) < 1e-9) {\n                        if (cntt > best_cnt || (cntt == best_cnt && kk < best_kk)) {\n                            better = true;\n                        }\n                    }\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'U';\n                        best_p = c;\n                    }\n                }\n            }\n            \n            // Col down\n            for (int c = 0; c < N; ++c) {\n                int kmaxx = col_down_kmax[c];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    int starti = N - kk;\n                    for (int i = starti; i < N; ++i) {\n                        if (temp_board[i][c]) ++cntt;\n                    }\n                    if (cntt == 0) continue;\n                    double ratio = static_cast<double>(cntt) / kk;\n                    double score;\n                    if (var_id == 0) {\n                        score = ratio;\n                    } else if (var_id == 1) {\n                        score = 10000.0 * cntt + ratio;\n                    } else {\n                        score = cntt * static_cast<double>(cntt) / kk;\n                    }\n                    bool better = false;\n                    if (score > best_score + 1e-9) {\n                        better = true;\n                    } else if (abs(score - best_score) < 1e-9) {\n                        if (cntt > best_cnt || (cntt == best_cnt && kk < best_kk)) {\n                            better = true;\n                        }\n                    }\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'D';\n                        best_p = c;\n                    }\n                }\n            }\n            \n            // Apply\n            assert(best_d != ' ');\n            char dirr = best_d;\n            int pp = best_p;\n            int kuse = best_kk;\n            char opp_d;\n            if (dirr == 'L') opp_d = 'R';\n            else if (dirr == 'R') opp_d = 'L';\n            else if (dirr == 'U') opp_d = 'D';\n            else opp_d = 'U';\n            \n            for (int t = 0; t < kuse; ++t) {\n                ops.emplace_back(dirr, pp);\n            }\n            for (int t = 0; t < kuse; ++t) {\n                ops.emplace_back(opp_d, pp);\n            }\n            \n            // Update temp_board\n            if (dirr == 'L' || dirr == 'R') {\n                int rr = pp;\n                if (dirr == 'L') {\n                    for (int j = 0; j < kuse; ++j) {\n                        temp_board[rr][j] = 0;\n                    }\n                } else {\n                    int st = N - kuse;\n                    for (int j = st; j < N; ++j) {\n                        temp_board[rr][j] = 0;\n                    }\n                }\n            } else {\n                int cc = pp;\n                if (dirr == 'U') {\n                    for (int i = 0; i < kuse; ++i) {\n                        temp_board[i][cc] = 0;\n                    }\n                } else {\n                    int st = N - kuse;\n                    for (int i = st; i < N; ++i) {\n                        temp_board[i][cc] = 0;\n                    }\n                }\n            }\n            rem -= best_cnt;\n        }\n        size_t this_t = ops.size();\n        if (this_t < best_t) {\n            best_t = this_t;\n            best_ops = std::move(ops);\n        }\n    }\n    \n    // Output\n    for (const auto& op : best_ops) {\n        cout << op.first << ' ' << op.second << '\\n';\n    }\n    \n    return 0;\n}","ahc044":"","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing pii = pair<int, int>;\nusing vpii = vector<pii>;\n\nvoid get_mst(const vector<int>& C, vpii& mst_edges) {\n  int l = C.size();\n  cout << \"? \" << l;\n  for (int u : C) cout << \" \" << u;\n  cout << endl << flush;\n  mst_edges.resize(l - 1);\n  for (int i = 0; i < l - 1; i++) {\n    int a, b;\n    cin >> a >> b;\n    if (a > b) swap(a, b);\n    mst_edges[i] = {a, b};\n  }\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, Q, L, W;\n  cin >> N >> M >> Q >> L >> W;\n  vi G(M);\n  for (auto& g : G) cin >> g;\n  vi lx(N), rx(N), ly(N), ry(N);\n  vi cx(N), cy(N);\n  for (int i = 0; i < N; i++) {\n    cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    cx[i] = (lx[i] + rx[i]) / 2;\n    cy[i] = (ly[i] + ry[i]) / 2;\n  }\n  vi order(N);\n  iota(order.begin(), order.end(), 0);\n  auto cmp = [&](int i, int j) {\n    if (cx[i] != cx[j]) return cx[i] < cx[j];\n    return cy[i] < cy[j];\n  };\n  sort(order.begin(), order.end(), cmp);\n  vi cum(M + 1, 0);\n  for (int i = 1; i <= M; i++) {\n    cum[i] = cum[i - 1] + G[i - 1];\n  }\n  vvi groups(M);\n  for (int m = 0; m < M; m++) {\n    groups[m].assign(order.begin() + cum[m], order.begin() + cum[m + 1]);\n  }\n  vector<vpii> all_trees(M);\n  for (int m = 0; m < M; m++) {\n    int g = groups[m].size();\n    if (g < 2) {\n      all_trees[m] = {};\n      continue;\n    }\n    vi C = groups[m];\n    vpii candidates;\n    if (g <= L) {\n      vpii temp;\n      get_mst(C, temp);\n      candidates = std::move(temp);\n    } else {\n      int wsz = L;\n      int step = L - 1;\n      int pos = 0;\n      while (pos + wsz <= g) {\n        vi sub(C.begin() + pos, C.begin() + pos + wsz);\n        vpii temp;\n        get_mst(sub, temp);\n        for (auto e : temp) candidates.push_back(e);\n        pos += step;\n      }\n      if (pos < g) {\n        int rem = g - pos;\n        if (rem >= 2) {\n          int lsz = min(wsz, rem);\n          vi sub(C.begin() + pos, C.begin() + pos + lsz);\n          vpii temp;\n          get_mst(sub, temp);\n          for (auto e : temp) candidates.push_back(e);\n        }\n      }\n    }\n    if (g <= L) {\n      all_trees[m] = std::move(candidates);\n      continue;\n    }\n    // large group: add path edges\n    for (int i = 0; i < g - 1; i++) {\n      int u = C[i], v = C[i + 1];\n      if (u > v) swap(u, v);\n      candidates.emplace_back(u, v);\n    }\n    // build adj local\n    vi local_id(N, -1);\n    for (int loc = 0; loc < g; loc++) {\n      local_id[C[loc]] = loc;\n    }\n    vvi adj(g);\n    for (auto [a, b] : candidates) {\n      int la = local_id[a];\n      int lb = local_id[b];\n      adj[la].push_back(lb);\n      adj[lb].push_back(la);\n    }\n    // BFS tree from 0\n    vi parent(g, -1);\n    vector<char> vis(g, 0);\n    queue<int> qu;\n    qu.push(0);\n    vis[0] = 1;\n    int visited_cnt = 1;\n    while (!qu.empty()) {\n      int u = qu.front();\n      qu.pop();\n      for (int v : adj[u]) {\n        if (vis[v] == 0) {\n          vis[v] = 1;\n          parent[v] = u;\n          qu.push(v);\n          visited_cnt++;\n        }\n      }\n    }\n    // build tree edges\n    vpii tree_edges;\n    for (int loc = 1; loc < g; loc++) {\n      int pv = parent[loc];\n      int gu = C[loc], gpv = C[pv];\n      if (gu > gpv) swap(gu, gpv);\n      tree_edges.emplace_back(gu, gpv);\n    }\n    all_trees[m] = std::move(tree_edges);\n  }\n  cout << \"!\" << endl;\n  for (int m = 0; m < M; m++) {\n    for (size_t i = 0; i < groups[m].size(); ++i) {\n      if (i > 0) cout << \" \";\n      cout << groups[m][i];\n    }\n    cout << '\\n';\n    for (const auto& e : all_trees[m]) {\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\nconst int INF = 1e9 + 5;\nint dr[4] = {-1, 1, 0, 0};\nint dc[4] = {0, 0, -1, 1};\nchar dirch[4] = {'U', 'D', 'L', 'R'};\n\nvector<pair<char, char>> get_path(int sr, int sc, int tr, int tc, int N) {\n  int NN = N * N;\n  vector<int> dist(NN, INF);\n  vector<int> prevv(NN, -1);\n  vector<char> pactt(NN, 0);\n  vector<char> pdirr(NN, 0);\n  int sid = sr * N + sc;\n  int tid = tr * N + tc;\n  dist[sid] = 0;\n  queue<int> q;\n  q.push(sid);\n  while (!q.empty()) {\n    int id = q.front();\n    q.pop();\n    int cr = id / N;\n    int cc = id % N;\n    // moves\n    for (int d = 0; d < 4; d++) {\n      int nr = cr + dr[d];\n      int nc = cc + dc[d];\n      if (nr >= 0 && nr < N && nc >= 0 && nc < N) {\n        int nid = nr * N + nc;\n        if (dist[nid] == INF) {\n          dist[nid] = dist[id] + 1;\n          prevv[nid] = id;\n          pactt[nid] = 'M';\n          pdirr[nid] = dirch[d];\n          q.push(nid);\n        }\n      }\n    }\n    // slides\n    for (int d = 0; d < 4; d++) {\n      int er = cr;\n      int ec = cc;\n      int ddr = dr[d];\n      int ddc = dc[d];\n      while (true) {\n        int nr = er + ddr;\n        int nc = ec + ddc;\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N) break;\n        er = nr;\n        ec = nc;\n      }\n      int eid = er * N + ec;\n      if (dist[eid] == INF) {\n        dist[eid] = dist[id] + 1;\n        prevv[eid] = id;\n        pactt[eid] = 'S';\n        pdirr[eid] = dirch[d];\n        q.push(eid);\n      }\n    }\n  }\n  // reconstruct\n  vector<pair<char, char>> path;\n  if (dist[tid] == INF) return path;\n  int cur = tid;\n  while (cur != sid) {\n    char a = pactt[cur];\n    char dd = pdirr[cur];\n    path.emplace_back(a, dd);\n    cur = prevv[cur];\n  }\n  reverse(path.begin(), path.end());\n  return path;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M;\n  cin >> N >> M;\n  vector<pair<int, int>> pos(M);\n  for (int i = 0; i < M; i++) {\n    cin >> pos[i].first >> pos[i].second;\n  }\n  int cr = pos[0].first;\n  int cc = pos[0].second;\n  vector<pair<char, char>> total;\n  for (int k = 1; k < M; k++) {\n    auto pth = get_path(cr, cc, pos[k].first, pos[k].second, N);\n    for (auto pr : pth) {\n      total.push_back(pr);\n    }\n    cr = pos[k].first;\n    cc = pos[k].second;\n  }\n  for (auto [a, d] : total) {\n    cout << a << ' ' << d << '\\n';\n  }\n  return 0;\n}"},"4":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing u32 = uint32_t;\nusing A4 = array<int, 4>;\n\ninline bool overlaps_rect(int ax, int ay, int cx, int dy, int bx, int by, int dx, int ey) {\n  return ax < dx && cx > bx && ay < ey && dy > by;\n}\n\nbool overlaps(const vector<A4>& v, int a, int b, int c, int d) {\n  for (const auto& p : v) {\n    if (overlaps_rect(a, b, c, d, p[0], p[1], p[2], p[3])) return true;\n  }\n  return false;\n}\n\nbool overlaps_with(const vector<A4>& occ, const vector<A4>& ext, int a, int b, int c, int d) {\n  return overlaps(occ, a, b, c, d) || overlaps(ext, a, b, c, d);\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n;\n  cin >> n;\n  vector<int> X(n), Y(n), R(n);\n  for (int i = 0; i < n; i++) {\n    cin >> X[i] >> Y[i] >> R[i];\n  }\n  vector<A4> points(n);\n  for (int i = 0; i < n; i++) {\n    points[i] = {X[i], Y[i], X[i] + 1, Y[i] + 1};\n  }\n  vector<int> order(n);\n  iota(order.begin(), order.end(), 0);\n  sort(order.begin(), order.end(), [&](int i, int j) {\n    if (R[i] != R[j]) return R[i] > R[j];\n    return X[i] < X[j];\n  });\n  vector<A4> occupied;\n  vector<A4> solution(n);\n  for (int kk = 0; kk < n; kk++) {\n    int i = order[kk];\n    int xi = X[i], yi = Y[i];\n    ll rri = R[i];\n    vector<A4> extras;\n    for (int jj = kk + 1; jj < n; jj++) {\n      extras.push_back(points[order[jj]]);\n    }\n    int aa = xi, bb = yi, cc = xi + 1, dd = yi + 1;\n    bool min_free = !overlaps_with(occupied, extras, aa, bb, cc, dd);\n    if (min_free) {\n      int cura = xi, curb = yi, curc = xi + 1, curd = yi + 1;\n      const int MAX_ITER = 300;\n      for (int iter = 0; iter < MAX_ITER; iter++) {\n        int d_left = 0;\n        {\n          int lo = 0, hi = cura;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int na = cura - mid;\n            if (na >= 0 && !overlaps_with(occupied, extras, na, curb, curc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_left = lo;\n        }\n        int d_right = 0;\n        {\n          int lo = 0, hi = 10000 - curc;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nc = curc + mid;\n            if (nc <= 10000 && !overlaps_with(occupied, extras, cura, curb, nc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_right = lo;\n        }\n        int d_bot = 0;\n        {\n          int lo = 0, hi = curb;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nb = curb - mid;\n            if (nb >= 0 && !overlaps_with(occupied, extras, cura, nb, curc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_bot = lo;\n        }\n        int d_top = 0;\n        {\n          int lo = 0, hi = 10000 - curd;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nt = curd + mid;\n            if (nt <= 10000 && !overlaps_with(occupied, extras, cura, curb, curc, nt)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_top = lo;\n        }\n        ll h = (ll)(curd - curb);\n        ll w = (ll)(curc - cura);\n        ll gain_l = (ll)d_left * h;\n        ll gain_r = (ll)d_right * h;\n        ll gain_b = (ll)d_bot * w;\n        ll gain_t = (ll)d_top * w;\n        ll maxg = max({gain_l, gain_r, gain_b, gain_t});\n        if (maxg == 0) break;\n        int chdir = -1;\n        if (gain_l == maxg) chdir = 0;\n        else if (gain_r == maxg) chdir = 1;\n        else if (gain_b == maxg) chdir = 2;\n        else chdir = 3;\n        if (chdir == 0) cura -= d_left;\n        else if (chdir == 1) curc += d_right;\n        else if (chdir == 2) curb -= d_bot;\n        else curd += d_top;\n      }\n      int Wma = curc - cura;\n      int Hma = curd - curb;\n      double bestp = -1.0;\n      int best_sq = INT_MAX;\n      int best_ms = INT_MAX;\n      int besw = 1, besh = 1;\n      for (int ww = 1; ww <= Wma; ww++) {\n        double hhd = (double)rri / ww;\n        int hh = (int)round(hhd);\n        for (int dk = -2; dk <= 2; dk++) {\n          int hht = hh + dk;\n          hht = max(1, min(Hma, hht));\n          ll ss = (ll)ww * hht;\n          double ra = min((double)rri, (double)ss) / max((double)rri, (double)ss);\n          double pp = 2 * ra - ra * ra;\n          int sq = abs(ww - hht);\n          int ms = max(ww, hht);\n          if (pp > bestp || (fabs(pp - bestp) < 1e-10 && (sq < best_sq || (sq == best_sq && ms < best_ms)))) {\n            bestp = pp;\n            best_sq = sq;\n            best_ms = ms;\n            besw = ww;\n            besh = hht;\n          }\n        }\n      }\n      double cx = xi + 0.5;\n      double cy = yi + 0.5;\n      double hw = besw / 2.0;\n      double hh_ = besh / 2.0;\n      int a_ideal = (int)round(cx - hw);\n      int a = max(cura, min(a_ideal, curc - besw));\n      int b_ideal = (int)round(cy - hh_);\n      int b = max(curb, min(b_ideal, curd - besh));\n      int c2 = a + besw;\n      int d2 = b + besh;\n      solution[i] = {a, b, c2, d2};\n      occupied.push_back(solution[i]);\n    } else {\n      bool found = false;\n      u32 state = static_cast<u32>(i) * 1103515245u + 12345u;\n      const int MAX_ATT = 30000;\n      for (int att = 0; att < MAX_ATT; att++) {\n        u32 st = state;\n        state = state * 1103515245u + 12345u;\n        int px = static_cast<int>((st >> 16) % 10000u);\n        int py = static_cast<int>(st % 10000u);\n        if (!overlaps(occupied, px, py, px + 1, py + 1)) {\n          solution[i] = {px, py, px + 1, py + 1};\n          occupied.push_back(solution[i]);\n          found = true;\n          break;\n        }\n      }\n      if (!found) {\n        found = false;\n        for (int px = 9999; px >= 0 && !found; px -= 5) {\n          for (int py = 9999; py >= 0 && !found; py -= 5) {\n            if (!overlaps(occupied, px, py, px + 1, py + 1)) {\n              solution[i] = {px, py, px + 1, py + 1};\n              occupied.push_back(solution[i]);\n              found = true;\n              break;\n            }\n          }\n        }\n      }\n      if (!found) {\n        solution[i] = {0, 0, 1, 1};\n        occupied.push_back(solution[i]);\n      }\n    }\n  }\n  for (int i = 0; i < n; i++) {\n    auto& re = solution[i];\n    cout << re[0] << \" \" << re[1] << \" \" << re[2] << \" \" << re[3] << \"\\n\";\n  }\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int si, sj;\n  cin >> si >> sj;\n  vector<vector<int>> T(50, vector<int>(50));\n  int maxt = -1;\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) {\n      cin >> T[i][j];\n      maxt = max(maxt, T[i][j]);\n    }\n  int M = maxt + 1;\n  vector<vector<int>> P(50, vector<int>(50));\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) cin >> P[i][j];\n\n  // Precompute tile_maxp\n  vector<int> tile_maxp(M, 0);\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) {\n      tile_maxp[T[i][j]] = max(tile_maxp[T[i][j]], P[i][j]);\n    }\n\n  // Precompute static_deg (tile graph degree)\n  vector<unordered_set<int>> tile_adj(M);\n  const int dr[] = {-1, 1, 0, 0};\n  const int dc[] = {0, 0, -1, 1};\n  for (int i = 0; i < 50; i++) {\n    for (int j = 0; j < 50; j++) {\n      int t1 = T[i][j];\n      for (int d = 0; d < 4; d++) {\n        int ni = i + dr[d];\n        int nj = j + dc[d];\n        if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n          int t2 = T[ni][nj];\n          if (t1 != t2) {\n            tile_adj[t1].insert(t2);\n          }\n        }\n      }\n    }\n  }\n  vector<int> static_deg(M);\n  for (int t = 0; t < M; t++) {\n    static_deg[t] = tile_adj[t].size();\n  }\n\n  const char dirchar[] = {'U', 'D', 'L', 'R'};\n\n  string best_str = \"\";\n  long long best_sc = -1LL;\n  const int TRIALS = 32768;\n  const int MAX_TOP = 7;\n\n  mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n  for (int trial = 0; trial < TRIALS; trial++) {\n    vector<int> vis(M, 0);\n    int st = T[si][sj];\n    vis[st] = 1;\n    long long score = P[si][sj];\n    int cr = si, cc = sj;\n    string moves = \"\";\n    int local_mode = trial % 5;\n    while (true) {\n      vector<int> cand_dirs;\n      for (int d = 0; d < 4; d++) {\n        int nr = cr + dr[d];\n        int nc = cc + dc[d];\n        if (nr < 0 || nr >= 50 || nc < 0 || nc >= 50) continue;\n        int nt = T[nr][nc];\n        if (vis[nt]) continue;\n        cand_dirs.push_back(d);\n      }\n      size_t ncand = cand_dirs.size();\n      if (ncand == 0) break;\n\n      int fdir;\n      if (local_mode == 4) {\n        // Mode 4: uniform random\n        uniform_int_distribution<int> dist(0, ncand - 1);\n        int pick = dist(rng);\n        fdir = cand_dirs[pick];\n      } else {\n        // Other modes: score and sort\n        vector<tuple<int, int, int, int>> scored_cands; // k1 asc good, k2, k3, ci (index in cand_dirs)\n        for (size_t ci = 0; ci < ncand; ci++) {\n          int d = cand_dirs[ci];\n          int nr = cr + dr[d];\n          int nc = cc + dc[d];\n          int nt = T[nr][nc];\n\n          // Compute dynamic square deg\n          int deg = 0;\n          for (int dd = 0; dd < 4; dd++) {\n            int mr = nr + dr[dd];\n            int mc = nc + dc[dd];\n            if (mr >= 0 && mr < 50 && mc >= 0 && mc < 50) {\n              int mt = T[mr][mc];\n              if (!vis[mt] && mt != nt) deg++;\n            }\n          }\n\n          int pp = P[nr][nc];\n          int bonus = (pp == tile_maxp[nt] ? 50 : 0);\n          int pps = pp + bonus;\n          int sdeg = static_deg[nt];\n\n          // Mode-specific keys (low good for deg/static unless negated)\n          int k1, k2, k3;\n          if (local_mode == 0) { // lowS lowD highP\n            k1 = sdeg;\n            k2 = deg;\n            k3 = -pps;\n          } else if (local_mode == 1) { // lowS highD highP\n            k1 = sdeg;\n            k2 = -deg;\n            k3 = -pps;\n          } else if (local_mode == 2) { // highS lowD highP\n            k1 = -sdeg;\n            k2 = deg;\n            k3 = -pps;\n          } else { // local_mode==3: pure highP\n            k1 = 0;\n            k2 = 0;\n            k3 = -pps;\n          }\n          scored_cands.emplace_back(k1, k2, k3, (int)ci);\n        }\n        sort(scored_cands.begin(), scored_cands.end());\n        int nsel = min((int)ncand, MAX_TOP);\n        uniform_int_distribution<int> dist(0, nsel - 1);\n        int pick_ci = dist(rng);\n        auto [_, __, ___, fci] = scored_cands[pick_ci];\n        fdir = cand_dirs[fci];\n      }\n\n      int nr = cr + dr[fdir];\n      int nc = cc + dc[fdir];\n      moves += dirchar[fdir];\n      int nt = T[nr][nc];\n      vis[nt] = 1;\n      score += P[nr][nc];\n      cr = nr;\n      cc = nc;\n    }\n    if (score > best_sc) {\n      best_sc = score;\n      best_str = moves;\n    }\n  }\n  cout << best_str << '\\n';\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  const int N = 30;\n  auto nodef = [&](int i, int j) -> int { return i * N + j; };\n  auto geti = [&](int u) -> int { return u / N; };\n  auto getj = [&](int u) -> int { return u % N; };\n  vector<vector<double>> h(N, vector<double>(N - 1, 5000.0));\n  vector<vector<double>> vv(N - 1, vector<double>(N, 5000.0));\n  for (int q = 0; q < 1000; ++q) {\n    int si, sj, ti, tj;\n    cin >> si >> sj >> ti >> tj;\n    int ss = nodef(si, sj);\n    int tt = nodef(ti, tj);\n    vector<double> dist(N * N, 1e18);\n    vector<int> prevv(N * N, -1);\n    dist[ss] = 0.0;\n    priority_queue<pair<double, int>, vector<pair<double, int>>, greater<pair<double, int>>> pq;\n    pq.push({0.0, ss});\n    while (!pq.empty()) {\n      auto [cost, u] = pq.top();\n      pq.pop();\n      if (cost > dist[u]) continue;\n      int i = geti(u), j = getj(u);\n      // right\n      if (j < N - 1) {\n        int v = nodef(i, j + 1);\n        double w = h[i][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // left\n      if (j > 0) {\n        int v = nodef(i, j - 1);\n        double w = h[i][j - 1];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // down\n      if (i < N - 1) {\n        int v = nodef(i + 1, j);\n        double w = vv[i][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // up\n      if (i > 0) {\n        int v = nodef(i - 1, j);\n        double w = vv[i - 1][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n    }\n    double predicted = dist[tt];\n    // reconstruct path\n    vector<int> path_nodes;\n    for (int cur = tt; cur != ss; cur = prevv[cur]) {\n      path_nodes.push_back(cur);\n      assert(prevv[cur] != -1); // for safety, remove in prod\n    }\n    path_nodes.push_back(ss);\n    reverse(path_nodes.begin(), path_nodes.end());\n    // build path_str\n    string path_str;\n    for (size_t k = 0; k + 1 < path_nodes.size(); ++k) {\n      int u = path_nodes[k], v = path_nodes[k + 1];\n      int ui = geti(u), uj = getj(u), vi = geti(v), vj = getj(v);\n      int di = vi - ui, dj = vj - uj;\n      char ch;\n      if (di == -1 && dj == 0) ch = 'U';\n      else if (di == 1 && dj == 0) ch = 'D';\n      else if (di == 0 && dj == -1) ch = 'L';\n      else if (di == 0 && dj == 1) ch = 'R';\n      else assert(false); // error\n      path_str += ch;\n    }\n    cout << path_str << '\\n';\n    cout.flush();\n    int obs;\n    cin >> obs;\n    // update estimates multiplicatively\n    double factor = (predicted > 1e-9 ? (double)obs / predicted : 1.0);\n    int num_e = path_nodes.size() - 1;\n    for (int k = 0; k < num_e; ++k) {\n      int u = path_nodes[k], v = path_nodes[k + 1];\n      int ui = geti(u), uj = getj(u), vi = geti(v), vj = getj(v);\n      if (ui == vi) {  // horiz\n        int lj = min(uj, vj);\n        h[ui][lj] *= factor;\n        h[ui][lj] = max(200.0, min(20000.0, h[ui][lj]));\n      } else {  // vert\n        int ti_ = min(ui, vi);\n        vv[ti_][uj] *= factor;\n        vv[ti_][uj] = max(200.0, min(20000.0, vv[ti_][uj]));\n      }\n    }\n  }\n  return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N = 20;\nint M;\nstring SS[805];\nint Lens[805];\nchar grid[20][20];\nchar best_grid[20][20];\nchar chars[8] = {'A','B','C','D','E','F','G','H'};\n\nint get_covered(char g[20][20]) {\n  static char dblr[20][41];\n  static char dblc[20][41];\n  for (int r = 0; r < N; ++r) {\n    memcpy(dblr[r], g[r], N);\n    memcpy(dblr[r] + N, g[r], N);\n  }\n  for (int c = 0; c < N; ++c) {\n    for (int r = 0; r < N; ++r) dblc[c][r] = g[r][c];\n    memcpy(dblc[c] + N, dblc[c], N);\n  }\n  int cnt = 0;\n  for (int si = 0; si < M; ++si) {\n    int k = Lens[si];\n    const char* pat = SS[si].c_str();\n    bool ok = false;\n    // rows\n    for (int r = 0; r < N && !ok; ++r) {\n      const char* dbl = dblr[r];\n      for (int st = 0; st < N; ++st) {\n        bool match = true;\n        for (int p = 0; p < k; ++p) {\n          if (dbl[st + p] != pat[p]) {\n            match = false;\n            break;\n          }\n        }\n        if (match) {\n          ok = true;\n          break;\n        }\n      }\n    }\n    if (!ok) {\n      // cols\n      for (int c = 0; c < N && !ok; ++c) {\n        const char* dbl = dblc[c];\n        for (int st = 0; st < N; ++st) {\n          bool match = true;\n          for (int p = 0; p < k; ++p) {\n            if (dbl[st + p] != pat[p]) {\n              match = false;\n              break;\n            }\n          }\n          if (match) {\n            ok = true;\n            break;\n          }\n        }\n      }\n    }\n    if (ok) ++cnt;\n  }\n  return cnt;\n}\n\nvector<bool> get_covered_vec(char g[20][20]) {\n  static char dblr[20][41];\n  static char dblc[20][41];\n  for (int r = 0; r < N; ++r) {\n    memcpy(dblr[r], g[r], N);\n    memcpy(dblr[r] + N, g[r], N);\n  }\n  for (int c = 0; c < N; ++c) {\n    for (int r = 0; r < N; ++r) dblc[c][r] = g[r][c];\n    memcpy(dblc[c] + N, dblc[c], N);\n  }\n  vector<bool> cov(M, false);\n  for (int si = 0; si < M; ++si) {\n    int k = Lens[si];\n    const char* pat = SS[si].c_str();\n    bool ok = false;\n    // rows\n    for (int r = 0; r < N && !ok; ++r) {\n      const char* dbl = dblr[r];\n      for (int st = 0; st < N; ++st) {\n        bool match = true;\n        for (int p = 0; p < k; ++p) {\n          if (dbl[st + p] != pat[p]) {\n            match = false;\n            break;\n          }\n        }\n        if (match) {\n          ok = true;\n          break;\n        }\n      }\n    }\n    if (!ok) {\n      // cols\n      for (int c = 0; c < N && !ok; ++c) {\n        const char* dbl = dblc[c];\n        for (int st = 0; st < N; ++st) {\n          bool match = true;\n          for (int p = 0; p < k; ++p) {\n            if (dbl[st + p] != pat[p]) {\n              match = false;\n              break;\n            }\n          }\n          if (match) {\n            ok = true;\n            break;\n          }\n        }\n      }\n    }\n    cov[si] = ok;\n  }\n  return cov;\n}\n\nvoid do_sa() {\n  memcpy(best_grid, grid, sizeof(grid));\n  int best_c = get_covered(grid);\n  int curr_c = best_c;\n  double temp = 32.0;\n  double cool_rate = 0.9998;\n  int iters = 0;\n  const int max_iters = 2000000;\n  srand(time(NULL));\n  while (iters < max_iters && temp > 0.05 && curr_c < M) {\n    int ri = rand() % N;\n    int ci = rand() % N;\n    char old_ch = grid[ri][ci];\n    int ch_idx = rand() % 8;\n    char new_ch = chars[ch_idx];\n    if (new_ch == old_ch) continue;\n    grid[ri][ci] = new_ch;\n    int new_c = get_covered(grid);\n    double delta = new_c - curr_c;\n    bool accept = (delta > 0);\n    if (!accept && temp > 0) {\n      double prob = exp(delta / temp);\n      if (prob > ((double)rand() / RAND_MAX)) accept = true;\n    }\n    if (accept) {\n      curr_c = new_c;\n      if (curr_c > best_c) {\n        best_c = curr_c;\n        memcpy(best_grid, grid, sizeof(grid));\n      }\n    } else {\n      grid[ri][ci] = old_ch;\n    }\n    temp *= cool_rate;\n    ++iters;\n  }\n  // copy back best\n  memcpy(grid, best_grid, sizeof(grid));\n}\n\nint main() {\n  srand(42);\n  cin >> N >> M;\n  for (int i = 0; i < M; ++i) {\n    cin >> SS[i];\n    Lens[i] = SS[i].size();\n    fill(grid[i], grid[i] + N, '.');\n  }\n  // greedy passes\n  int passes = 0;\n  bool changed = true;\n  while (changed && passes++ < 20) {\n    changed = false;\n    auto cov = get_covered_vec(grid);\n    vector<int> unc;\n    for (int si = 0; si < M; ++si) {\n      if (!cov[si]) unc.push_back(si);\n    }\n    if (unc.empty()) break;\n    // sort unc by len desc\n    sort(unc.begin(), unc.end(), [](int a, int b) {\n      return Lens[a] > Lens[b];\n    });\n    for (int si : unc) {\n      const string& s = SS[si];\n      int k = Lens[si];\n      int best_cost = INT_MAX / 2;\n      int best_ndot = -1;\n      int best_dir = -1, best_fix = -1, best_st = -1;\n      for (int dir = 0; dir < 2; ++dir) {\n        for (int fix = 0; fix < N; ++fix) {\n          for (int st = 0; st < N; ++st) {\n            int cost = 0;\n            int ndot = 0;\n            for (int p = 0; p < k; ++p) {\n              int rr = dir ? (st + p) % N : fix;\n              int cc = dir ? fix : (st + p) % N;\n              char cur = grid[rr][cc];\n              if (cur != '.' && cur != s[p]) ++cost;\n              if (cur == '.') ++ndot;\n            }\n            if (cost < best_cost || (cost == best_cost && ndot > best_ndot)) {\n              best_cost = cost;\n              best_ndot = ndot;\n              best_dir = dir;\n              best_fix = fix;\n              best_st = st;\n            }\n          }\n        }\n      }\n      if (best_cost == 0) {\n        // place\n        int dir = best_dir, fix = best_fix, st = best_st;\n        for (int p = 0; p < k; ++p) {\n          int rr = dir ? (st + p) % N : fix;\n          int cc = dir ? fix : (st + p) % N;\n          grid[rr][cc] = s[p];\n        }\n        changed = true;\n      }\n    }\n  }\n  // fill dots safely\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      if (grid[i][j] == '.') grid[i][j] = 'A';\n    }\n  }\n  int final_c = get_covered(grid);\n  if (final_c < M) {\n    do_sa();\n  }\n  // output\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      cout << grid[i][j];\n    }\n    cout << '\\n';\n  }\n  return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nchar get_move(int fi, int fj, int ti, int tj) {\n    int delx = ti - fi;\n    int dely = tj - fj;\n    if (delx == -1 && dely == 0) return 'U';\n    if (delx == 1 && dely == 0) return 'D';\n    if (dely == 1 && delx == 0) return 'R';\n    if (dely == -1 && delx == 0) return 'L';\n    assert(false);\n    return '?';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, si, sj;\n    cin >> N >> si >> sj;\n    vector<string> grid(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> grid[i];\n    }\n    vector<vector<bool>> road(N, vector<bool>(N, false));\n    vector<vector<int>> enter(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (grid[i][j] != '#') {\n                road[i][j] = true;\n                enter[i][j] = grid[i][j] - '0';\n            }\n        }\n    }\n    vector<pair<int, int>> h_reps, v_reps;\n    for (int i = 0; i < N; ++i) {\n        int j = 0;\n        while (j < N) {\n            if (!road[i][j]) {\n                ++j;\n                continue;\n            }\n            int lj = j;\n            while (j < N && road[i][j]) ++j;\n            int rj = j - 1;\n            int mj = (lj + rj) / 2;\n            h_reps.emplace_back(i, mj);\n        }\n    }\n    for (int j = 0; j < N; ++j) {\n        int i = 0;\n        while (i < N) {\n            if (!road[i][j]) {\n                ++i;\n                continue;\n            }\n            int ti = i;\n            while (i < N && road[i][j]) ++i;\n            int bi = i - 1;\n            int mi = (ti + bi) / 2;\n            v_reps.emplace_back(mi, j);\n        }\n    }\n    vector<pair<int, int>> terms;\n    if (h_reps.size() <= v_reps.size()) {\n        terms = h_reps;\n    } else {\n        terms = v_reps;\n    }\n    terms.emplace_back(si, sj);\n    int nt = terms.size();\n    // build cells and cellid\n    vector<pair<int, int>> cells;\n    vector<vector<int>> cellid(N, vector<int>(N, -1));\n    int numcells = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (road[i][j]) {\n                cellid[i][j] = numcells;\n                cells.emplace_back(i, j);\n                ++numcells;\n            }\n        }\n    }\n    // graph directed\n    vector<vector<pair<int, int>>> graph(numcells);\n    int dx[4] = {-1, 0, 1, 0};\n    int dy[4] = {0, 1, 0, -1};\n    for (int u = 0; u < numcells; ++u) {\n        auto [i, j] = cells[u];\n        for (int d = 0; d < 4; ++d) {\n            int ni = i + dx[d];\n            int nj = j + dy[d];\n            if (ni >= 0 && ni < N && nj >= 0 && nj < N && road[ni][nj]) {\n                int v = cellid[ni][nj];\n                int cost = enter[ni][nj];\n                graph[u].emplace_back(v, cost);\n            }\n        }\n    }\n    // termids\n    vector<int> termids(nt);\n    for (int k = 0; k < nt; ++k) {\n        auto [x, y] = terms[k];\n        termids[k] = cellid[x][y];\n    }\n    const ll INF = 1LL << 60;\n    vector<vector<ll>> dists(nt, vector<ll>(nt, INF));\n    vector<vector<string>> pathstr(nt, vector<string>(nt));\n    for (int s = 0; s < nt; ++s) {\n        int sid = termids[s];\n        vector<ll> d(numcells, INF);\n        d[sid] = 0;\n        vector<int> pred(numcells, -1);\n        priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;\n        pq.emplace(0, sid);\n        while (!pq.empty()) {\n            auto [dc, u] = pq.top();\n            pq.pop();\n            if (dc > d[u]) continue;\n            for (auto [v, wc] : graph[u]) {\n                ll nc = d[u] + wc;\n                if (nc < d[v]) {\n                    d[v] = nc;\n                    pred[v] = u;\n                    pq.emplace(nc, v);\n                }\n            }\n        }\n        for (int t = 0; t < nt; ++t) {\n            int tid = termids[t];\n            dists[s][t] = d[tid];\n            string& pth = pathstr[s][t];\n            int cur = tid;\n            while (cur != sid) {\n                int prv = pred[cur];\n                if (prv == -1) break;\n                auto [pi, pj] = cells[prv];\n                auto [ci, cj] = cells[cur];\n                pth += get_move(pi, pj, ci, cj);\n                cur = prv;\n            }\n            reverse(pth.begin(), pth.end());\n        }\n    }\n    // now MST on terms\n    vector<tuple<ll, int, int>> term_edges;\n    for (int a = 0; a < nt; ++a) {\n        for (int b = a + 1; b < nt; ++b) {\n            ll wc = dists[a][b] + dists[b][a];\n            if (wc >= INF / 2) continue;\n            term_edges.emplace_back(wc, a, b);\n        }\n    }\n    sort(term_edges.begin(), term_edges.end());\n    vector<int> tpar(nt);\n    for (int i = 0; i < nt; ++i) tpar[i] = i;\n    auto tfind = [&](auto&& self, int x) -> int {\n        return tpar[x] == x ? x : tpar[x] = self(self, tpar[x]);\n    };\n    vector<vector<int>> tadj(nt);\n    int num_tedges = 0;\n    for (auto& e : term_edges) {\n        ll w;\n        int a, b;\n        tie(w, a, b) = e;\n        int pa = tfind(tfind, a);\n        int pb = tfind(tfind, b);\n        if (pa != pb) {\n            tpar[pa] = pb;\n            tadj[a].push_back(b);\n            tadj[b].push_back(a);\n            ++num_tedges;\n            if (num_tedges == nt - 1) break;\n        }\n    }\n    // now dfs\n    string moves;\n    moves.reserve(200000);\n    int start_tid = nt - 1;\n    function<void(int, int)> dfs_term = [&](int ta, int tp) {\n        for (int tb : tadj[ta]) {\n            if (tb == tp) continue;\n            moves += pathstr[ta][tb];\n            dfs_term(tb, ta);\n            moves += pathstr[tb][ta];\n        }\n    };\n    dfs_term(start_tid, -1);\n    cout << moves << '\\n';\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout << fixed << setprecision(10);\n  int N, M, K, R;\n  cin >> N >> M >> K >> R;\n  vector<vector<int>> D(N + 1, vector<int>(K));\n  vector<double> avg_d(K, 0.0);\n  for (int i = 1; i <= N; ++i) {\n    for (int k = 0; k < K; ++k) {\n      cin >> D[i][k];\n      avg_d[k] += D[i][k];\n    }\n  }\n  for (int k = 0; k < K; ++k) {\n    avg_d[k] /= N;\n  }\n  vector<vector<int>> adj(N + 1);\n  vector<int> pending(N + 1, 0);\n  for (int r = 0; r < R; ++r) {\n    int u, v;\n    cin >> u >> v;\n    adj[u].push_back(v);\n    ++pending[v];\n  }\n  vector<int> crit(N + 1, 0);\n  auto get_crit = [&](auto&& self, int i) -> int {\n    if (crit[i] != 0) return crit[i];\n    int mx = 0;\n    for (int suc : adj[i]) {\n      mx = max(mx, self(self, suc));\n    }\n    crit[i] = 1 + mx;\n    return crit[i];\n  };\n  for (int i = 1; i <= N; ++i) {\n    get_crit(get_crit, i);\n  }\n  vector<vector<double>> est_s(M + 1, vector<double>(K, 0.0));\n  vector<int> obs_count(M + 1, 0);\n  for (int j = 1; j <= M; ++j) {\n    for (int k = 0; k < K; ++k) {\n      est_s[j][k] = avg_d[k] * 1.6;\n    }\n  }\n  vector<int> task_worker(N + 1, 0);\n  vector<int> task_start(N + 1, 0);\n  vector<bool> task_completed(N + 1, false);\n  vector<int> worker_task(M + 1, 0);\n  set<int> ready_set;\n  for (int i = 1; i <= N; ++i) {\n    if (pending[i] == 0) {\n      ready_set.insert(i);\n    }\n  }\n  int day = 0;\n  while (true) {\n    ++day;\n    vector<int> idles;\n    for (int j = 1; j <= M; ++j) {\n      if (worker_task[j] == 0) {\n        idles.push_back(j);\n      }\n    }\n    vector<int> readies_vec(ready_set.begin(), ready_set.end());\n    if (idles.empty() || readies_vec.empty()) {\n      cout << 0 << '\\n';\n      cout.flush();\n    } else {\n      vector<pair<int, double>> ready_list;\n      for (int ti : readies_vec) {\n        double min_pt = 1e100;\n        for (int j : idles) {\n          double w = 0.0;\n          for (int k = 0; k < K; ++k) {\n            w += max(0.0, (double)D[ti][k] - est_s[j][k]);\n          }\n          double pt = (w <= 0 ? 1.0 : max(1.0, w));\n          if (pt < min_pt) min_pt = pt;\n        }\n        ready_list.emplace_back(ti, min_pt);\n      }\n      sort(ready_list.begin(), ready_list.end(), [&](const pair<int, double>& a, const pair<int, double>& b) {\n        if (crit[a.first] != crit[b.first]) return crit[a.first] > crit[b.first];\n        if (fabs(a.second - b.second) > 1e-9) return a.second < b.second;\n        return a.first < b.first;\n      });\n      set<int> avail(idles.begin(), idles.end());\n      vector<pair<int, int>> assignment;\n      for (auto [ti, mpt] : ready_list) {\n        if (avail.empty()) break;\n        double best_pt = 1e100;\n        int best_j = -1;\n        for (int j : avail) {\n          double w = 0.0;\n          for (int k = 0; k < K; ++k) {\n            w += max(0.0, (double)D[ti][k] - est_s[j][k]);\n          }\n          double pt = (w <= 0 ? 1.0 : max(1.0, w));\n          if (pt < best_pt || (fabs(pt - best_pt) < 1e-9 && j < best_j)) {\n            best_pt = pt;\n            best_j = j;\n          }\n        }\n        if (best_j != -1) {\n          assignment.emplace_back(best_j, ti);\n          avail.erase(best_j);\n        }\n      }\n      cout << assignment.size();\n      for (auto p : assignment) {\n        cout << \" \" << p.first << \" \" << p.second;\n      }\n      cout << '\\n';\n      cout.flush();\n      for (auto [wj, ti] : assignment) {\n        task_worker[ti] = wj;\n        task_start[ti] = day;\n        worker_task[wj] = ti;\n        ready_set.erase(ti);\n      }\n    }\n    int n;\n    cin >> n;\n    if (n == -1) {\n      return 0;\n    }\n    vector<int> finished_workers(n);\n    for (int i = 0; i < n; ++i) {\n      cin >> finished_workers[i];\n    }\n    for (int jj : finished_workers) {\n      int tsk = worker_task[jj];\n      if (tsk == 0) continue;\n      int t_obs = day - task_start[tsk] + 1;\n      double w_est = max(0.0, (double)t_obs - 1.0);\n      ++obs_count[jj];\n      double alpha = 1.0 / obs_count[jj];\n      double current_w = 0.0;\n      vector<double> contrib(K, 0.0);\n      for (int k = 0; k < K; ++k) {\n        double defk = max(0.0, (double)D[tsk][k] - est_s[jj][k]);\n        contrib[k] = defk;\n        current_w += defk;\n      }\n      double error = current_w - w_est;\n      if (current_w > 1e-6) {\n        for (int k = 0; k < K; ++k) {\n          if (contrib[k] > 1e-6) {\n            double frac = contrib[k] / current_w;\n            double delta = alpha * error * frac;\n            est_s[jj][k] += delta;\n            if (est_s[jj][k] < 0.0) est_s[jj][k] = 0.0;\n          }\n        }\n      } else if (w_est > 1.0) {\n        double total_d = 0.0;\n        for (int k = 0; k < K; ++k) total_d += D[tsk][k];\n        if (total_d > 0) {\n          double delta = -alpha * (w_est / (double)K);\n          for (int k = 0; k < K; ++k) {\n            est_s[jj][k] += delta;\n            if (est_s[jj][k] < 0.0) est_s[jj][k] = 0.0;\n          }\n        }\n      }\n      task_completed[tsk] = true;\n      task_worker[tsk] = 0;\n      worker_task[jj] = 0;\n      for (int suc : adj[tsk]) {\n        --pending[suc];\n        if (pending[suc] == 0 && task_worker[suc] == 0 && !task_completed[suc]) {\n          ready_set.insert(suc);\n        }\n      }\n    }\n  }\n  return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int xx = 0, int yy = 0) : x(xx), y(yy) {}\n};\n\nint dist(Point a, Point b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\ndouble get_angle(const Point& pp) {\n    return atan2(pp.y - 400, pp.x - 400);\n}\n\nstruct Order {\n    Point p, d;\n    int id;\n    int len() const { return dist(p, d); }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    vector<Order> orders(1000);\n    Point O(400, 400);\n    for (int i = 0; i < 1000; i++) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        orders[i].p = {a, b};\n        orders[i].d = {c, d};\n        orders[i].id = i + 1;\n    }\n    const int N = 50;\n\n    // Forward greedy\n    vector<int> fsel;\n    bool fused[1000] = {};\n    Point fcurr = O;\n    for (int k = 0; k < N; k++) {\n        int best = -1;\n        int md = INT_MAX;\n        for (int u = 0; u < 1000; u++) {\n            if (fused[u]) continue;\n            int dd = dist(fcurr, orders[u].p);\n            if (dd < md || (dd == md && orders[u].len() < orders[best].len())) {\n                md = dd;\n                best = u;\n            }\n        }\n        fsel.push_back(best);\n        fused[best] = true;\n        fcurr = orders[best].d;\n    }\n\n    // Reverse greedy\n    vector<int> rsel;\n    bool rused[1000] = {};\n    Point rcurr = O;\n    for (int k = 0; k < N; k++) {\n        int best = -1;\n        int md = INT_MAX;\n        for (int u = 0; u < 1000; u++) {\n            if (rused[u]) continue;\n            int dd = dist(orders[u].d, rcurr);\n            if (dd < md || (dd == md && dist(orders[u].p, O) < dist(orders[best].p, O))) {\n                md = dd;\n                best = u;\n            }\n        }\n        rsel.push_back(best);\n        rused[best] = true;\n        rcurr = orders[best].p;\n    }\n    reverse(rsel.begin(), rsel.end());\n\n    // Compute full costs for both\n    auto compute_full = [&](const vector<int>& sel) -> pair<int, int> {\n        int suml = 0;\n        for (int oi : sel) suml += orders[oi].len();\n        int varc = dist(O, orders[sel[0]].p);\n        for (int i = 0; i < N - 1; i++) {\n            varc += dist(orders[sel[i]].d, orders[sel[i + 1]].p);\n        }\n        varc += dist(orders[sel.back()].d, O);\n        return {varc + suml, varc};\n    };\n\n    auto [ffull, fvar] = compute_full(fsel);\n    auto [rfull, rvar] = compute_full(rsel);\n\n    vector<int> sel = (ffull <= rfull ? fsel : rsel);\n    int initial_fixed_var = (ffull <= rfull ? fvar : rvar);\n\n    // Now build Ps, Ds, ids from sel\n    vector<Point> Ps(N), Ds(N);\n    vector<int> ids(N);\n    for (int i = 0; i < N; i++) {\n        int oi = sel[i];\n        Ps[i] = orders[oi].p;\n        Ds[i] = orders[oi].d;\n        ids[i] = orders[oi].id;\n    }\n\n    // get_var_cost\n    auto get_var_cost = [&](const vector<int>& perm) -> int {\n        if (perm.empty()) return 0;\n        int res = dist(O, Ps[perm[0]]);\n        for (size_t i = 0; i + 1 < perm.size(); ++i) {\n            res += dist(Ds[perm[i]], Ps[perm[(size_t)i + 1]]);\n        }\n        res += dist(Ds[perm.back()], O);\n        return res;\n    };\n\n    // Three initials\n    vector<vector<int>> inits(3);\n    // 1: identity (greedy)\n    inits[0].resize(N);\n    iota(inits[0].begin(), inits[0].end(), 0);\n    // 2: angle sort on P\n    {\n        vector<pair<double, int>> ang(N);\n        for (int i = 0; i < N; i++) ang[i] = {get_angle(Ps[i]), i};\n        sort(ang.begin(), ang.end());\n        inits[1].resize(N);\n        for (int i = 0; i < N; i++) inits[1][i] = ang[i].second;\n    }\n    // 3: manh coord sort on P (u=x+y, v=x-y)\n    {\n        vector<pair<pair<int, int>, int>> mng(N);\n        for (int i = 0; i < N; i++) {\n            int u = Ps[i].x + Ps[i].y;\n            int v = Ps[i].x - Ps[i].y;\n            mng[i] = {{u, v}, i};\n        }\n        sort(mng.begin(), mng.end());\n        inits[2].resize(N);\n        for (int i = 0; i < N; i++) inits[2][i] = mng[i].second;\n    }\n\n    vector<int> path = inits[0];\n    int current_cost = get_var_cost(path);\n    int bestcost = current_cost;\n    vector<int> bestpath = path;\n    for (int ii = 1; ii < 3; ii++) {\n        int cc = get_var_cost(inits[ii]);\n        if (cc < bestcost) {\n            bestcost = cc;\n            bestpath = inits[ii];\n            path = inits[ii];\n            current_cost = cc;\n        }\n    }\n\n    // SA\n    mt19937 gen(random_device{}());\n    uniform_int_distribution<int> randpos(0, N - 1);\n    uniform_real_distribution<double> rdis(0.0, 1.0);\n    double Tstart = 4000.0;\n    double T = Tstart;\n    double cool_rate = 0.9999;\n    const int MAX_ATT = 8000000;\n    for (int att = 0; att < MAX_ATT; att++) {\n        int i = randpos(gen);\n        int j = randpos(gen);\n        if (i == j) continue;\n        if (i > j) swap(i, j);\n        vector<int> newp = path;\n        swap(newp[i], newp[j]);\n        int nc = get_var_cost(newp);\n        int delta = nc - current_cost;\n        if (delta < 0 || rdis(gen) < exp(-double(delta) / T)) {\n            path = std::move(newp);\n            current_cost = nc;\n            if (nc < bestcost) {\n                bestcost = nc;\n                bestpath = path;\n            }\n        }\n        T *= cool_rate;\n        if (T < 0.1) break;\n    }\n\n    // Build output\n    vector<Point> route;\n    route.reserve(102);\n    route.push_back(O);\n    for (int pi : bestpath) {\n        route.push_back(Ps[pi]);\n        route.push_back(Ds[pi]);\n    }\n    route.push_back(O);\n\n    vector<int> out_ids(N);\n    for (int i = 0; i < N; i++) {\n        out_ids[i] = ids[bestpath[i]];\n    }\n    sort(out_ids.begin(), out_ids.end());\n\n    cout << N;\n    for (int r : out_ids) cout << ' ' << r;\n    cout << '\\n';\n    cout << route.size();\n    for (const auto& pt : route) {\n        cout << ' ' << pt.x << ' ' << pt.y;\n    }\n    cout << '\\n';\n\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    vector<int> X(N), Y(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> X[i] >> Y[i];\n    }\n\n    vector<pair<int, int>> Edge(M);\n    vector<int> D(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        Edge[i] = {u, v};\n        double dx = X[u] - X[v];\n        double dy = Y[u] - Y[v];\n        D[i] = (int)round(hypot(dx, dy));\n    }\n\n    vector<int> par(N), sz(N, 1);\n    vector<double> cminx(N), cmaxx(N), cminy(N), cmaxy(N);\n    for (int i = 0; i < N; ++i) {\n        par[i] = i;\n        cminx[i] = cmaxx[i] = X[i];\n        cminy[i] = cmaxy[i] = Y[i];\n    }\n\n    auto find = [&](auto&& self, int x) -> int {\n        return par[x] == x ? x : par[x] = self(self, par[x]);\n    };\n\n    auto rect_dist = [&](int c1, int c2) -> double {\n        double dx = max({0.0, cminx[c1] - cmaxx[c2], cminx[c2] - cmaxx[c1]});\n        double dy = max({0.0, cminy[c1] - cmaxy[c2], cminy[c2] - cmaxy[c1]});\n        return hypot(dx, dy);\n    };\n\n    auto unite = [&](int a, int b) {\n        a = find(find, a);\n        b = find(find, b);\n        if (a == b) return;\n        if (sz[a] < sz[b]) swap(a, b);\n        par[b] = a;\n        sz[a] += sz[b];\n        cminx[a] = min(cminx[a], cminx[b]);\n        cmaxx[a] = max(cmaxx[a], cmaxx[b]);\n        cminy[a] = min(cminy[a], cminy[b]);\n        cmaxy[a] = max(cmaxy[a], cmaxy[b]);\n    };\n\n    int cur_comp = N;\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;\n\n        int u = Edge[i].first, v = Edge[i].second;\n        int pu = find(find, u), pv = find(find, v);\n        if (pu == pv) {\n            cout << 0 << '\\n' << flush;\n            continue;\n        }\n\n        int s1 = sz[pu], s2 = sz[pv];\n        int smin = min(s1, s2);\n        double sepd = rect_dist(pu, pv);\n        bool separated = (sepd > 1e-6);\n        double ratio = (double)l / D[i];\n\n        // Scan for future only when necessary\n        double min_fut_d = 1e9;\n        bool need_scan = (smin >= 12) && separated && (cur_comp > 20) && (i < M - 20);\n        if (need_scan) {\n            for (int j = i + 1; j < M; ++j) {\n                int qu = find(find, Edge[j].first);\n                int qv = find(find, Edge[j].second);\n                if ((qu == pu && qv == pv) || (qu == pv && qv == pu)) {\n                    min_fut_d = min(min_fut_d, (double)D[j]);\n                }\n            }\n        }\n        double est_sep = (min_fut_d < 5e8) ? min_fut_d : sepd;\n\n        bool too_bad = (ratio > 2.7);\n        bool is_small = (smin <= 32);\n        bool good_dist = !separated || (l <= 1.85 * est_sep + 2.5);\n\n        bool take = !too_bad && (is_small || good_dist);\n\n        // Urgency\n        int remaining = M - i - 1;\n        int needed = cur_comp - 1;\n        double urgency_ratio = (double)needed / max(1, remaining);\n        bool large_comps = (s1 >= 50 && s2 >= 50);\n        bool urgent = (remaining <= needed * 1.8) || (needed <= 15) || (urgency_ratio > 0.20) ||\n                      (large_comps && urgency_ratio > 0.15);\n        if (urgent) {\n            take = !too_bad;\n        }\n\n        if (take) {\n            unite(u, v);\n            --cur_comp;\n            cout << 1 << '\\n' << flush;\n        } else {\n            cout << 0 << '\\n' << flush;\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef pair<int, int> pii;\n\nconst int SZ = 30;\nbool passable[31][31];\nint DX[4] = {-1, 1, 0, 0};\nint DY[4] = {0, 0, -1, 1};\nchar WALLC[4] = {'u', 'd', 'l', 'r'};\nchar MOVEC[4] = {'U', 'D', 'L', 'R'};\nconst int GCX = 15, GCY = 15;\n\nbool in_bound(int x, int y) {\n  return x >= 1 && x <= SZ && y >= 1 && y <= SZ;\n}\n\nbool can_wall(const vector<pii>& hpos, const vector<pii>& ppos, int hi, int d, int NN, int MM) {\n  int hx = hpos[hi].first;\n  int hy = hpos[hi].second;\n  int tx = hx + DX[d];\n  int ty = hy + DY[d];\n  if (!in_bound(tx, ty)) return false;\n  for (int k = 0; k < MM; k++) {\n    if (hpos[k].first == tx && hpos[k].second == ty) return false;\n  }\n  for (int k = 0; k < NN; k++) {\n    if (ppos[k].first == tx && ppos[k].second == ty) return false;\n  }\n  for (int dd = 0; dd < 4; dd++) {\n    int ax = tx + DX[dd];\n    int ay = ty + DY[dd];\n    if (!in_bound(ax, ay)) continue;\n    for (int k = 0; k < NN; k++) {\n      if (ppos[k].first == ax && ppos[k].second == ay) return false;\n    }\n  }\n  return true;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n\n  int N;\n  cin >> N;\n  vector<pii> ppos(N);\n  vector<int> ptype(N);\n  for (int i = 0; i < N; i++) {\n    int x, y, t;\n    cin >> x >> y >> t;\n    ppos[i] = {x, y};\n    ptype[i] = t;\n  }\n  int M;\n  cin >> M;\n  vector<pii> hpos(M);\n  for (int i = 0; i < M; i++) {\n    int x, y;\n    cin >> x >> y;\n    hpos[i] = {x, y};\n  }\n\n  memset(passable, 0, sizeof(passable));\n  for (int i = 1; i <= SZ; i++)\n    for (int j = 1; j <= SZ; j++) passable[i][j] = true;\n\n  vector<double> pet_threat(N);\n  double threat_base[6] = {0, 1.0, 3.0, 10.0, 50.0, 20.0};\n  for (int i = 0; i < N; i++) {\n    pet_threat[i] = threat_base[ptype[i]];\n  }\n\n  int dista[31][31];\n\n  for (int turn = 0; turn < 300; turn++) {\n    int sumx = 0, sumy = 0;\n    for (auto& hp : hpos) {\n      sumx += hp.first;\n      sumy += hp.second;\n    }\n    int cur_cx = sumx / M;\n    int cur_cy = sumy / M;\n    int spread = 0;\n    int min_human_pd = 999;\n    for (auto& hp : hpos) {\n      int dd = abs(hp.first - cur_cx) + abs(hp.second - cur_cy);\n      spread = max(spread, dd);\n      // precompute for debug\n    }\n\n    bool wall_mode = (spread <= 4) || (turn > 150 && spread <= 8);\n\n    pii target = {cur_cx, cur_cy};\n    if (!wall_mode) {\n      // multi BFS pet dist\n      memset(dista, -1, sizeof(dista));\n      queue<pii> q;\n      for (int i = 0; i < N; i++) {\n        auto [px, py] = ppos[i];\n        if (passable[px][py]) {\n          dista[px][py] = 0;\n          q.push({px, py});\n        }\n      }\n      while (!q.empty()) {\n        auto [x, y] = q.front(); q.pop();\n        for (int d = 0; d < 4; d++) {\n          int nx = x + DX[d];\n          int ny = y + DY[d];\n          if (in_bound(nx, ny) && passable[nx][ny] && dista[nx][ny] == -1) {\n            dista[nx][ny] = dista[x][y] + 1;\n            q.push({nx, ny});\n          }\n        }\n      }\n      // best target: max dist to pet, tie min dist to grid center\n      int maxd = -1;\n      int min_tie = INT_MAX / 2;\n      for (int i = 1; i <= SZ; i++) {\n        for (int j = 1; j <= SZ; j++) {\n          if (!passable[i][j]) continue;\n          int dd = dista[i][j];\n          if (dd == -1) dd = 999;\n          int tie_dist = abs(i - GCX) + abs(j - GCY);\n          if (dd > maxd || (dd == maxd && tie_dist < min_tie)) {\n            maxd = dd;\n            min_tie = tie_dist;\n            target = {i, j};\n          }\n        }\n      }\n      // recompute min_human_pd\n      for (int hi = 0; hi < M; hi++) {\n        int hx = hpos[hi].first, hy = hpos[hi].second;\n        int pd = dista[hx][hy];\n        if (pd == -1) pd = 999;\n        min_human_pd = min(min_human_pd, pd);\n      }\n    } else {\n      min_human_pd = 999;\n    }\n\n    int tx = target.first;\n    int ty = target.second;\n\n    string action(M, '.');\n    if (wall_mode) {\n      for (int hi = 0; hi < M; hi++) {\n        int bestd = -1;\n        double bsc = -1e100;\n        auto [hx, hy] = hpos[hi];\n        for (int d = 0; d < 4; d++) {\n          if (!can_wall(hpos, ppos, hi, d, N, M)) continue;\n          int wtx = hx + DX[d];\n          int wty = hy + DY[d];\n          double sc = 0.0;\n          double dist_center = abs(wtx - cur_cx) + abs(wty - cur_cy) + 2.0;\n          for (int pi = 0; pi < N; pi++) {\n            auto [px, py] = ppos[pi];\n            int pdist = abs(wtx - px) + abs(wty - py);\n            sc += pet_threat[pi] / (pdist + 1.0);\n          }\n          sc /= dist_center;  // prefer outer walls\n          if (sc > bsc) {\n            bsc = sc;\n            bestd = d;\n          }\n        }\n        if (bestd != -1) {\n          action[hi] = WALLC[bestd];\n        }\n      }\n    } else {\n      for (int hi = 0; hi < M; hi++) {\n        auto [hx, hy] = hpos[hi];\n        int mdist = abs(hx - tx) + abs(hy - ty);\n        if (mdist == 0) continue;\n        int best_red = -1;\n        int bestd = -1;\n        for (int d = 0; d < 4; d++) {\n          int nx = hx + DX[d];\n          int ny = hy + DY[d];\n          if (!in_bound(nx, ny) || !passable[nx][ny]) continue;\n          int nmdist = abs(nx - tx) + abs(ny - ty);\n          int red = mdist - nmdist;\n          if (red > best_red) {\n            best_red = red;\n            bestd = d;\n          }\n        }\n        if (bestd != -1) {\n          action[hi] = MOVEC[bestd];\n        }\n      }\n    }\n\n    cout << \"#\" << turn << \" spread:\" << spread << \" min_h_pd:\" << min_human_pd << \" mode:\" << (wall_mode ? \"wall\" : \"move\");\n    cout << \" target(\" << tx << \",\" << ty << \")\" << endl;\n    cout << action << endl;\n    cout.flush();\n\n    // update pets (after human actions in judge)\n    for (int i = 0; i < N; i++) {\n      string s;\n      cin >> s;\n      int x = ppos[i].first;\n      int y = ppos[i].second;\n      for (char c : s) {\n        int dx = 0, dy = 0;\n        if (c == 'U') dx = -1;\n        else if (c == 'D') dx = 1;\n        else if (c == 'L') dy = -1;\n        else if (c == 'R') dy = 1;\n        x += dx;\n        y += dy;\n      }\n      ppos[i] = {x, y};\n    }\n\n    // update humans/walls\n    for (int hi = 0; hi < M; hi++) {\n      char c = action[hi];\n      if (c == '.') continue;\n      int dd = -1;\n      bool is_move = isupper((unsigned char)c);\n      if (is_move) {\n        if (c == 'U') dd = 0;\n        else if (c == 'D') dd = 1;\n        else if (c == 'L') dd = 2;\n        else if (c == 'R') dd = 3;\n        hpos[hi].first += DX[dd];\n        hpos[hi].second += DY[dd];\n      } else {\n        if (c == 'u') dd = 0;\n        else if (c == 'd') dd = 1;\n        else if (c == 'l') dd = 2;\n        else if (c == 'r') dd = 3;\n        int wtx = hpos[hi].first + DX[dd];\n        int wty = hpos[hi].second + DY[dd];\n        if (in_bound(wtx, wty)) {\n          passable[wtx][wty] = false;\n        }\n      }\n    }\n  }\n  return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int ROWS = 20;\nconst int COLS = 20;\nconst int N = ROWS * COLS;\n\nint get_row(int pos) { return pos / COLS; }\nint get_col(int pos) { return pos % COLS; }\n\nint attempt_move(int cur_pos, char direction, const vector<string>& h_walls, const vector<string>& v_walls) {\n  int r = get_row(cur_pos);\n  int c = get_col(cur_pos);\n  int dr = 0, dc = 0;\n  switch (direction) {\n    case 'U': dr = -1; break;\n    case 'D': dr = 1; break;\n    case 'L': dc = -1; break;\n    case 'R': dc = 1; break;\n    default: return cur_pos;\n  }\n  int nr = r + dr;\n  int nc = c + dc;\n  if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) {\n    return cur_pos;\n  }\n  if (dr != 0) {\n    if (dr > 0) {\n      if (v_walls[r][c] == '1') return cur_pos;\n    } else {\n      if (v_walls[r - 1][c] == '1') return cur_pos;\n    }\n  } else {\n    if (dc > 0) {\n      if (h_walls[r][c] == '1') return cur_pos;\n    } else {\n      if (h_walls[r][c - 1] == '1') return cur_pos;\n    }\n  }\n  return nr * COLS + nc;\n}\n\nstring shortest_path(int start_pos, int target_pos, const vector<string>& h_walls, const vector<string>& v_walls) {\n  vector<int> dist(N, -1);\n  vector<int> parent(N, -1);\n  dist[start_pos] = 0;\n  queue<int> q;\n  q.push(start_pos);\n  while (!q.empty()) {\n    int u = q.front();\n    q.pop();\n    if (u == target_pos) break;\n    for (char dch : {'U', 'D', 'L', 'R'}) {\n      int v = attempt_move(u, dch, h_walls, v_walls);\n      if (dist[v] == -1) {\n        dist[v] = dist[u] + 1;\n        parent[v] = u;\n        q.push(v);\n      }\n    }\n  }\n  if (dist[target_pos] == -1) {\n    return \"\";  // Should not happen\n  }\n  string path_str;\n  int cur = target_pos;\n  while (cur != start_pos) {\n    int prev = parent[cur];\n    int pr = get_row(prev), pc = get_col(prev);\n    int cr = get_row(cur), cc = get_col(cur);\n    char dch;\n    if (cr == pr + 1) dch = 'D';\n    else if (cr == pr - 1) dch = 'U';\n    else if (cc == pc + 1) dch = 'R';\n    else if (cc == pc - 1) dch = 'L';\n    else assert(false);\n    path_str += dch;\n    cur = prev;\n  }\n  reverse(path_str.begin(), path_str.end());\n  return path_str;\n}\n\ndouble evaluate(const string& path_str, double forget_p, int start_pos, int target_pos,\n                const vector<string>& h_walls, const vector<string>& v_walls) {\n  if (start_pos == target_pos) return 401.0;\n  int L = path_str.size();\n  vector<double> curr_prob(N, 0.0);\n  curr_prob[start_pos] = 1.0;\n  double total_es = 0.0;\n  for (int t = 0; t < L; ++t) {\n    char ch = path_str[t];\n    vector<double> next_prob(N, 0.0);\n    double arr_this = 0.0;\n    for (int ps = 0; ps < N; ++ps) {\n      double pr = curr_prob[ps];\n      if (pr < 1e-12) continue;\n      // stay\n      int stay_pos = ps;\n      if (stay_pos == target_pos) {\n        arr_this += pr * forget_p;\n      } else {\n        next_prob[stay_pos] += pr * forget_p;\n      }\n      // move\n      int move_pos = attempt_move(ps, ch, h_walls, v_walls);\n      if (move_pos == target_pos) {\n        arr_this += pr * (1.0 - forget_p);\n      } else {\n        next_prob[move_pos] += pr * (1.0 - forget_p);\n      }\n    }\n    total_es += arr_this * (401.0 - (t + 1));\n    curr_prob = std::move(next_prob);\n  }\n  return total_es;\n}\n\nstruct Cand {\n  string path;\n  double es;\n};\n\nint main() {\n  int si, sj, ti, tj;\n  double forget_p;\n  cin >> si >> sj >> ti >> tj >> forget_p;\n  vector<string> h_walls(20);\n  for (auto& s : h_walls) cin >> s;\n  vector<string> v_walls(19);\n  for (auto& s : v_walls) cin >> s;\n  int start_pos = si * COLS + sj;\n  int target_pos = ti * COLS + tj;\n  if (start_pos == target_pos) {\n    cout << \"\" << endl;\n    return 0;\n  }\n  string sp = shortest_path(start_pos, target_pos, h_walls, v_walls);\n  vector<Cand> candidates;\n  // per-move repeats\n  for (int rpm = 2; rpm <= 6; ++rpm) {\n    string cand;\n    cand.reserve(sp.size() * rpm);\n    for (char ch : sp) {\n      cand.append(rpm, ch);\n      if (cand.size() > 200) break;\n    }\n    if (cand.size() > 200 || cand.empty()) continue;\n    double esc = evaluate(cand, forget_p, start_pos, target_pos, h_walls, v_walls);\n    candidates.push_back({cand, esc});\n  }\n  // whole path repeats\n  for (int cycles = 1; cycles <= 5; ++cycles) {\n    string cand;\n    cand.reserve(sp.size() * cycles);\n    for (int i = 0; i < cycles; ++i) {\n      cand += sp;\n      if (cand.size() > 200) break;\n    }\n    if (cand.size() > 200 || cand.empty()) continue;\n    double esc = evaluate(cand, forget_p, start_pos, target_pos, h_walls, v_walls);\n    candidates.push_back({cand, esc});\n  }\n  // single shortest\n  {\n    double esc = evaluate(sp, forget_p, start_pos, target_pos, h_walls, v_walls);\n    candidates.push_back({sp, esc});\n  }\n  // select top for beam\n  sort(candidates.begin(), candidates.end(),\n       [](const Cand& a, const Cand& b) { return a.es > b.es; });\n  string best_path = candidates[0].path;\n  double best_es = candidates[0].es;\n  const int BEAM_SIZE = 10;\n  vector<Cand> curr_beam;\n  for (size_t i = 0; i < min((size_t)BEAM_SIZE, candidates.size()); ++i) {\n    curr_beam.push_back(candidates[i]);\n  }\n  string chars = \"UDLR\";\n  for (int clen = curr_beam[0].path.size(); clen < 200; ++clen) {\n    vector<Cand> next_beam;\n    for (const auto& cb : curr_beam) {\n      for (char dch : chars) {\n        string npath = cb.path + dch;\n        double nes = evaluate(npath, forget_p, start_pos, target_pos, h_walls, v_walls);\n        next_beam.push_back({npath, nes});\n        if (nes > best_es) {\n          best_es = nes;\n          best_path = npath;\n        }\n      }\n    }\n    sort(next_beam.begin(), next_beam.end(),\n         [](const Cand& a, const Cand& b) { return a.es > b.es; });\n    next_beam.resize(BEAM_SIZE);\n    bool improve = false;\n    for (const auto& nc : next_beam) {\n      if (nc.es > best_es) {\n        best_es = nc.es;\n        best_path = nc.path;\n        improve = true;\n      }\n    }\n    curr_beam = std::move(next_beam);\n    if (!improve || curr_beam[0].es < best_es * 0.98) {\n      break;\n    }\n  }\n  cout << best_path << endl;\n  return 0;\n}","ahc010":"","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint dx[4] = {-1, 1, 0, 0};\nint dy[4] = {0, 0, -1, 1};\nchar dc[4] = {'U', 'D', 'L', 'R'};\n\nint get_max_tree(const vector<vector<int>>& brd, int ex, int ey, int N) {\n  int emp_id = ex * N + ey;\n  int NN = N * N;\n  vector<vector<int>> adj(NN);\n  // vertical edges\n  for (int i = 0; i < N - 1; ++i) {\n    for (int j = 0; j < N; ++j) {\n      int id1 = i * N + j;\n      int id2 = (i + 1) * N + j;\n      if (id1 == emp_id || id2 == emp_id) continue;\n      int m1 = brd[i][j];\n      int m2 = brd[i + 1][j];\n      if ((m1 & 8) && (m2 & 2)) {\n        adj[id1].push_back(id2);\n        adj[id2].push_back(id1);\n      }\n    }\n  }\n  // horizontal edges\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N - 1; ++j) {\n      int id1 = i * N + j;\n      int id2 = i * N + j + 1;\n      if (id1 == emp_id || id2 == emp_id) continue;\n      int m1 = brd[i][j];\n      int m2 = brd[i][j + 1];\n      if ((m1 & 4) && (m2 & 1)) {\n        adj[id1].push_back(id2);\n        adj[id2].push_back(id1);\n      }\n    }\n  }\n  vector<char> vis(NN, 0);\n  vis[emp_id] = 1;\n  int maxt = 1;\n  for (int sid = 0; sid < NN; ++sid) {\n    if (vis[sid]) continue;\n    stack<int> st;\n    st.push(sid);\n    vis[sid] = 1;\n    int vv = 0;\n    int degsum = 0;\n    while (!st.empty()) {\n      int u = st.top();\n      st.pop();\n      ++vv;\n      degsum += adj[u].size();\n      for (int v : adj[u]) {\n        if (!vis[v]) {\n          vis[v] = 1;\n          st.push(v);\n        }\n      }\n    }\n    int ee = degsum / 2;\n    if (ee == vv - 1) {\n      maxt = max(maxt, vv);\n    }\n  }\n  return maxt;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  srand(time(nullptr));\n  int N;\n  long long T;\n  cin >> N >> T;\n  vector<vector<int>> orig_board(N, vector<int>(N));\n  int ox = -1, oy = -1;\n  for (int i = 0; i < N; ++i) {\n    string s;\n    cin >> s;\n    for (int j = 0; j < N; ++j) {\n      char ch = s[j];\n      int val = isdigit(ch) ? ch - '0' : 10 + (ch - 'a');\n      orig_board[i][j] = val;\n      if (val == 0) {\n        ox = i;\n        oy = j;\n      }\n    }\n  }\n  vector<vector<int>> board = orig_board;\n  int ex = ox, ey = oy;\n  int targetV = N * N - 1;\n  int cur_S = get_max_tree(board, ex, ey, N);\n  if (cur_S == targetV) {\n    cout << \"\" << endl;\n    return 0;\n  }\n  string ans;\n  double temp = 20.0;\n  double cool_rate = 0.999;\n  int max_total_steps = min(100000LL, 10LL * T);\n  int step = 0;\n  while (ans.size() < (size_t)T && step < max_total_steps) {\n    ++step;\n    vector<int> newS(4, -1);\n    vector<bool> can(4, false);\n    int ncan = 0;\n    for (int d = 0; d < 4; ++d) {\n      int nx = ex + dx[d];\n      int ny = ey + dy[d];\n      if (nx >= 0 && nx < N && ny >= 0 && ny < N) {\n        can[d] = true;\n        ++ncan;\n        int tile = board[nx][ny];\n        board[nx][ny] = 0;\n        board[ex][ey] = tile;\n        newS[d] = get_max_tree(board, nx, ny, N);\n        board[nx][ny] = tile;\n        board[ex][ey] = 0;\n      }\n    }\n    if (ncan == 0) break;\n    vector<double> probs(4, 0.0);\n    double sum_p = 0.0;\n    for (int d = 0; d < 4; ++d) {\n      if (can[d]) {\n        double delta = newS[d] - cur_S;\n        probs[d] = exp(delta / temp);\n        sum_p += probs[d];\n      }\n    }\n    double r = (double)rand() / RAND_MAX * sum_p;\n    double cum = 0.0;\n    int chd = -1;\n    for (int d = 0; d < 4; ++d) {\n      if (can[d]) {\n        cum += probs[d];\n        if (cum > r) {\n          chd = d;\n          break;\n        }\n      }\n    }\n    if (chd == -1) {\n      // fallback to best\n      int bestd = 0;\n      int bs = -1e9;\n      for (int d = 0; d < 4; ++d) {\n        if (can[d] && newS[d] > bs) {\n          bs = newS[d];\n          bestd = d;\n        }\n      }\n      chd = bestd;\n    }\n    // perform move\n    int nx = ex + dx[chd];\n    int ny = ey + dy[chd];\n    int tile = board[nx][ny];\n    board[nx][ny] = 0;\n    board[ex][ey] = tile;\n    ex = nx;\n    ey = ny;\n    ans += dc[chd];\n    cur_S = newS[chd];\n    if (cur_S == targetV) {\n      break;\n    }\n    temp *= cool_rate;\n    if (temp < 0.1) temp = 0.1;\n  }\n  cout << ans << endl;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Line {\n  ll px, py, qx, qy;\n};\n\nint side(const Line& l, ll x, ll y) {\n  ll dx1 = l.qx - l.px;\n  ll dy1 = l.qy - l.py;\n  ll dx2 = x - l.px;\n  ll dy2 = y - l.py;\n  ll cross = dx1 * dy2 - dy1 * dx2;\n  if (cross == 0) return 0;\n  return cross > 0 ? 1 : -1;\n}\n\ntuple<ll, ll, ll> exgcd(ll a, ll b) {\n  if (b == 0) return {a, 1, 0};\n  auto [g, x, y] = exgcd(b, a % b);\n  return {g, y, x - (a / b) * y};\n}\n\nint eval_add(const Line& cand, const vector<vector<int>>& groups, const vector<pair<ll, ll>>& points, const vector<int>& a) {\n  vector<int> tent_b(11, 0);\n  for (const auto& grp : groups) {\n    int L = 0, R = 0;\n    for (int id : grp) {\n      int s = side(cand, points[id].first, points[id].second);\n      if (s == 1) ++L;\n      else if (s == -1) ++R;\n    }\n    if (L >= 1 && L <= 10) ++tent_b[L];\n    if (R >= 1 && R <= 10) ++tent_b[R];\n  }\n  int sc = 0;\n  for (int d = 1; d <= 10; ++d) {\n    sc += min(a[d], tent_b[d]);\n  }\n  return sc;\n}\n\nvoid add_line(vector<Line>& lines, vector<vector<int>>& groups, const vector<pair<ll, ll>>& points, const Line& newline) {\n  vector<vector<int>> newgroups;\n  newgroups.reserve(groups.size() * 2);\n  for (auto grp : groups) {\n    vector<int> left, right;\n    for (int id : grp) {\n      int s = side(newline, points[id].first, points[id].second);\n      if (s == 1) left.push_back(id);\n      else if (s == -1) right.push_back(id);\n    }\n    if (!left.empty()) newgroups.push_back(move(left));\n    if (!right.empty()) newgroups.push_back(move(right));\n  }\n  groups = move(newgroups);\n  lines.push_back(newline);\n}\n\nvector<Line> generate_cands(const vector<vector<int>>& groups, const vector<pair<ll, ll>>& points) {\n  vector<Line> cands;\n  const int MAX_CANDS = 50;\n  cands.reserve(MAX_CANDS);\n  for (const auto& grp : groups) {\n    int gsz = grp.size();\n    if (gsz < 2) continue;\n    if ((int)cands.size() >= MAX_CANDS) break;\n    int minid = *min_element(grp.begin(), grp.end());\n    int maxid = *max_element(grp.begin(), grp.end());\n    mt19937_64 rng((ll)minid + (ll)maxid * 12345LL);\n    int ngen = min(20, gsz);\n    int range = 100;\n    for (int tr = 0; tr < ngen; ++tr) {\n      if ((int)cands.size() >= MAX_CANDS) break;\n      ll aa = (rng() % (2LL * range + 1)) - range;\n      ll bb = (rng() % (2LL * range + 1)) - range;\n      if (aa == 0 && bb == 0) continue;\n      ll gg = __gcd(abs(aa), abs(bb));\n      aa /= gg;\n      bb /= gg;\n      vector<pair<ll, int>> projs;\n      projs.reserve(gsz);\n      for (int id : grp) {\n        ll x = points[id].first;\n        ll y = points[id].second;\n        ll pr = aa * x + bb * y;\n        projs.emplace_back(pr, id);\n      }\n      sort(projs.begin(), projs.end());\n      int gm = min(10, gsz - 1);\n      for (int m = 1; m <= gm; ++m) {\n        if ((int)cands.size() >= MAX_CANDS) break;\n        ll ml = projs[m - 1].first;\n        ll mr = projs[m].first;\n        if (ml + 1 >= mr) continue;\n        ll kk = ml + 1;\n        ll dd = kk;\n        auto [g, x, y] = exgcd(aa, bb);\n        if (g < 0) {\n          g = -g;\n          x = -x;\n          y = -y;\n        }\n        if (dd % g != 0) continue;\n        ll mul = dd / g;\n        ll xx_ = x * mul;\n        ll yy_ = y * mul;\n        ll dirx_ = bb;\n        ll diry_ = -aa;\n        ll ppx = xx_;\n        ll ppy = yy_;\n        if (bb != 0) {\n          ll tt = -xx_ / bb;\n          ppx = xx_ + bb * tt;\n          ppy = yy_ - aa * tt;\n        }\n        ll qqx = ppx + dirx_;\n        ll qqy = ppy + diry_;\n        if (abs(ppx) > 1000000000LL || abs(ppy) > 1000000000LL || abs(qqx) > 1000000000LL ||\n            abs(qqy) > 1000000000LL)\n          continue;\n        if (ppx == qqx && ppy == qqy) continue;\n        cands.push_back({ppx, ppy, qqx, qqy});\n      }\n    }\n  }\n  return cands;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, K;\n  cin >> N >> K;\n  vector<int> a(11, 0);\n  for (int d = 1; d <= 10; ++d) {\n    cin >> a[d];\n  }\n  vector<pair<ll, ll>> points(N);\n  for (auto& p : points) {\n    cin >> p.first >> p.second;\n  }\n  vector<vector<int>> groups(1, vector<int>(N));\n  iota(groups[0].begin(), groups[0].end(), 0);\n  vector<Line> curr_lines;\n  while ((int)curr_lines.size() < K) {\n    auto cands = generate_cands(groups, points);\n    if (cands.empty()) break;\n    Line best_cand;\n    int best_new_sc = -1;\n    bool improved = false;\n    for (const auto& cand : cands) {\n      int nsc = eval_add(cand, groups, points, a);\n      if (nsc > best_new_sc) {\n        best_new_sc = nsc;\n        best_cand = cand;\n        improved = true;\n      }\n    }\n    if (!improved) break;\n    add_line(curr_lines, groups, points, best_cand);\n  }\n  cout << curr_lines.size() << '\\n';\n  for (const auto& l : curr_lines) {\n    cout << l.px << ' ' << l.py << ' ' << l.qx << ' ' << l.qy << '\\n';\n  }\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 64;\nbool occupied[MAXN][MAXN];\nbool used_h[MAXN][MAXN];\nbool used_v[MAXN][MAXN];\nbool used_ne[MAXN][MAXN];\nbool used_nw[MAXN][MAXN];\nint N, c;\nint M;\n\nstruct Move {\n    int x1, y1, x2, y2, x3, y3, x4, y4, rsize;\n    long long dist2;\n};\n\nvector<Move> cands;\nvector<Move> ans_moves;\n\nlong long distsq(int x, int y) {\n    long long dx = x - c;\n    long long dy = y - c;\n    return dx * dx + dy * dy;\n}\n\npair<int, int> getxy(int uu, int vv) {\n    int xx = (uu + vv) / 2;\n    int yy = (uu - vv) / 2;\n    return {xx, yy};\n}\n\nbool in_grid(int x, int y) {\n    return x >= 0 && x < N && y >= 0 && y < N;\n}\n\nbool check_clean(int x0, int y0, int x1, int y1) {\n    int dx = x1 - x0;\n    int dy = y1 - y0;\n    int adx = abs(dx);\n    int ady = abs(dy);\n    if (adx == 0 && ady == 0) return false;\n    if (adx != 0 && ady != 0 && adx != ady) return false;\n    int k = max(adx, ady);\n    int stepx = (dx > 0 ? 1 : (dx < 0 ? -1 : 0));\n    int stepy = (dy > 0 ? 1 : (dy < 0 ? -1 : 0));\n\n    // interiors\n    for (int i = 1; i < k; ++i) {\n        int xx = x0 + i * stepx;\n        int yy = y0 + i * stepy;\n        if (!in_grid(xx, yy) || occupied[xx][yy]) return false;\n    }\n\n    // units\n    for (int i = 0; i < k; ++i) {\n        int xx = x0 + i * stepx;\n        int yy = y0 + i * stepy;\n        int nx = xx + stepx;\n        int ny = yy + stepy;\n        if (!in_grid(xx, yy) || !in_grid(nx, ny)) return false;\n\n        int lx = min(xx, nx);\n        int ly = (xx == lx ? yy : ny);\n        int ry = (xx == lx ? ny : yy);\n\n        if (stepx == 0) {  // vert\n            int miny = min(yy, ny);\n            if (miny < 0 || miny >= N - 1 || used_v[xx][miny]) return false;\n        } else if (stepy == 0) {  // horiz\n            if (lx < 0 || lx >= N - 1 || used_h[yy][lx]) return false;\n        } else {  // diag\n            if (ry == ly + 1) {\n                if (lx < 0 || lx >= N - 1 || ly < 0 || ly >= N - 1 || used_ne[lx][ly]) return false;\n            } else if (ry == ly - 1) {\n                if (lx < 0 || lx >= N - 1 || ly < 1 || ly >= N || used_nw[lx][ly]) return false;\n            } else {\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nvoid mark_side(int x0, int y0, int x1, int y1) {\n    int dx = x1 - x0;\n    int dy = y1 - y0;\n    int adx = abs(dx);\n    int ady = abs(dy);\n    if (adx == 0 && ady == 0) return;\n    int k = max(adx, ady);\n    int stepx = (dx > 0 ? 1 : (dx < 0 ? -1 : 0));\n    int stepy = (dy > 0 ? 1 : (dy < 0 ? -1 : 0));\n\n    // mark units only\n    for (int i = 0; i < k; ++i) {\n        int xx = x0 + i * stepx;\n        int yy = y0 + i * stepy;\n        int nx = xx + stepx;\n        int ny = yy + stepy;\n\n        int lx = min(xx, nx);\n        int ly = (xx == lx ? yy : ny);\n        int ry = (xx == lx ? ny : yy);\n\n        if (stepx == 0) {  // vert\n            int miny = min(yy, ny);\n            used_v[xx][miny] = true;\n        } else if (stepy == 0) {  // horiz\n            used_h[yy][lx] = true;\n        } else {  // diag\n            if (ry == ly + 1) {\n                used_ne[lx][ly] = true;\n            } else if (ry == ly - 1) {\n                used_nw[lx][ly] = true;\n            }\n        }\n    }\n}\n\nvoid scan_axis() {\n    for (int xl = 0; xl < N; ++xl) {\n        for (int xr = xl + 1; xr < N; ++xr) {\n            for (int yb = 0; yb < N; ++yb) {\n                for (int yt = yb + 1; yt < N; ++yt) {\n                    vector<pair<int, int>> corns = {\n                        {xl, yb}, {xr, yb}, {xr, yt}, {xl, yt}\n                    };\n                    int cnt = 0;\n                    for (auto& p : corns) {\n                        if (occupied[p.first][p.second]) ++cnt;\n                    }\n                    if (cnt != 3) continue;\n                    pair<int, int> p1;\n                    int miss_idx = -1;\n                    for (int ii = 0; ii < 4; ++ii) {\n                        if (!occupied[corns[ii].first][corns[ii].second]) {\n                            p1 = corns[ii];\n                            miss_idx = ii;\n                            break;\n                        }\n                    }\n                    if (occupied[p1.first][p1.second]) continue;\n\n                    if (!check_clean(corns[0].first, corns[0].second, corns[1].first, corns[1].second) ||\n                        !check_clean(corns[1].first, corns[1].second, corns[2].first, corns[2].second) ||\n                        !check_clean(corns[2].first, corns[2].second, corns[3].first, corns[3].second) ||\n                        !check_clean(corns[3].first, corns[3].second, corns[0].first, corns[0].second)) continue;\n\n                    int idx2 = (miss_idx + 1) % 4;\n                    int idx3 = (miss_idx + 2) % 4;\n                    int idx4 = (miss_idx + 3) % 4;\n                    Move m;\n                    m.x1 = p1.first;\n                    m.y1 = p1.second;\n                    m.x2 = corns[idx2].first;\n                    m.y2 = corns[idx2].second;\n                    m.x3 = corns[idx3].first;\n                    m.y3 = corns[idx3].second;\n                    m.x4 = corns[idx4].first;\n                    m.y4 = corns[idx4].second;\n                    m.rsize = (xr - xl) + (yt - yb);\n                    m.dist2 = distsq(p1.first, p1.second);\n                    cands.push_back(m);\n                }\n            }\n        }\n    }\n}\n\nvoid scan_45(int parity) {\n    vector<int> us;\n    for (int uu = parity; uu <= 2 * (N - 1); uu += 2) us.push_back(uu);\n    vector<int> vs;\n    int v_start = parity ? -(N - 2) : -(N - 1);\n    for (int vv = v_start; vv <= N - 1; vv += 2) vs.push_back(vv);\n    for (size_t i = 0; i < us.size(); ++i) {\n        for (size_t j = i + 1; j < us.size(); ++j) {\n            int u1 = us[i], u2 = us[j];\n            for (size_t kk = 0; kk < vs.size(); ++kk) {\n                for (size_t l = kk + 1; l < vs.size(); ++l) {\n                    int v1 = vs[kk], v2 = vs[l];\n                    auto c0 = getxy(u1, v1);\n                    if (!in_grid(c0.first, c0.second)) continue;\n                    auto c1 = getxy(u1, v2);\n                    if (!in_grid(c1.first, c1.second)) continue;\n                    auto c2 = getxy(u2, v2);\n                    if (!in_grid(c2.first, c2.second)) continue;\n                    auto c3 = getxy(u2, v1);\n                    if (!in_grid(c3.first, c3.second)) continue;\n\n                    vector<pair<int, int>> corns = {c0, c1, c2, c3};\n                    int cnt = 0;\n                    for (auto& p : corns) {\n                        if (occupied[p.first][p.second]) ++cnt;\n                    }\n                    if (cnt != 3) continue;\n                    pair<int, int> p1;\n                    int miss_idx = -1;\n                    for (int ii = 0; ii < 4; ++ii) {\n                        if (!occupied[corns[ii].first][corns[ii].second]) {\n                            p1 = corns[ii];\n                            miss_idx = ii;\n                            break;\n                        }\n                    }\n                    if (occupied[p1.first][p1.second]) continue;\n\n                    if (!check_clean(corns[0].first, corns[0].second, corns[1].first, corns[1].second) ||\n                        !check_clean(corns[1].first, corns[1].second, corns[2].first, corns[2].second) ||\n                        !check_clean(corns[2].first, corns[2].second, corns[3].first, corns[3].second) ||\n                        !check_clean(corns[3].first, corns[3].second, corns[0].first, corns[0].second)) continue;\n\n                    int idx2 = (miss_idx + 1) % 4;\n                    int idx3 = (miss_idx + 2) % 4;\n                    int idx4 = (miss_idx + 3) % 4;\n                    Move m;\n                    m.x1 = p1.first;\n                    m.y1 = p1.second;\n                    m.x2 = corns[idx2].first;\n                    m.y2 = corns[idx2].second;\n                    m.x3 = corns[idx3].first;\n                    m.y3 = corns[idx3].second;\n                    m.x4 = corns[idx4].first;\n                    m.y4 = corns[idx4].second;\n                    int du = (u2 - u1) / 2;\n                    int dv = abs(v2 - v1) / 2;\n                    m.rsize = du + dv;\n                    m.dist2 = distsq(p1.first, p1.second);\n                    cands.push_back(m);\n                }\n            }\n        }\n    }\n}\n\nvoid do_scan() {\n    cands.clear();\n    scan_axis();\n    scan_45(0);\n    scan_45(1);\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    clock_t start_clk = clock();\n\n    cin >> N >> M;\n    c = (N - 1) / 2;\n    memset(occupied, 0, sizeof(occupied));\n    memset(used_h, 0, sizeof(used_h));\n    memset(used_v, 0, sizeof(used_v));\n    memset(used_ne, 0, sizeof(used_ne));\n    memset(used_nw, 0, sizeof(used_nw));\n    for (int i = 0; i < M; ++i) {\n        int x, y;\n        cin >> x >> y;\n        occupied[x][y] = true;\n    }\n\n    bool phase_inner = true;\n    while (true) {\n        double timet = (clock() - start_clk) / (double)CLOCKS_PER_SEC;\n        if (timet > 4.7) break;\n\n        do_scan();\n        if (cands.empty()) break;\n\n        sort(cands.begin(), cands.end(), [&](const Move& a, const Move& b) {\n            long long pa, pb;\n            if (phase_inner) {\n                pa = -a.dist2 + 500000000LL / (a.rsize + 1);\n                pb = -b.dist2 + 500000000LL / (b.rsize + 1);\n            } else {\n                pa = a.dist2 * 100LL - (long long)a.rsize * 10LL;\n                pb = b.dist2 * 100LL - (long long)b.rsize * 10LL;\n            }\n            return pa > pb;\n        });\n\n        int added_this = 0;\n        for (auto& mv : cands) {\n            double timet2 = (clock() - start_clk) / (double)CLOCKS_PER_SEC;\n            if (timet2 > 4.85) break;\n\n            if (occupied[mv.x1][mv.y1]) continue;\n\n            if (check_clean(mv.x1, mv.y1, mv.x2, mv.y2) &&\n                check_clean(mv.x2, mv.y2, mv.x3, mv.y3) &&\n                check_clean(mv.x3, mv.y3, mv.x4, mv.y4) &&\n                check_clean(mv.x4, mv.y4, mv.x1, mv.y1)) {\n                ans_moves.push_back(mv);\n                occupied[mv.x1][mv.y1] = true;\n                mark_side(mv.x1, mv.y1, mv.x2, mv.y2);\n                mark_side(mv.x2, mv.y2, mv.x3, mv.y3);\n                mark_side(mv.x3, mv.y3, mv.x4, mv.y4);\n                mark_side(mv.x4, mv.y4, mv.x1, mv.y1);\n                ++added_this;\n            }\n        }\n        if (added_this == 0) {\n            if (phase_inner) {\n                phase_inner = false;\n            } else {\n                break;\n            }\n        }\n    }\n\n    cout << ans_moves.size() << '\\n';\n    for (auto& m : ans_moves) {\n        cout << m.x1 << ' ' << m.y1 << ' ' << m.x2 << ' ' << m.y2\n             << ' ' << m.x3 << ' ' << m.y3 << ' ' << m.x4 << ' ' << m.y4 << '\\n';\n    }\n    return 0;\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int, int>;\nusing vv = vector<vector<int>>;\n\npair<int, int> get_new_pos(const vv& g, int pr, int pc, char dir) {\n    int nr = pr, nc = pc;\n    if (dir == 'L') {\n        int rank_left = 0;\n        for (int c = 0; c < pc; ++c) if (g[pr][c] != 0) ++rank_left;\n        nc = rank_left;\n    } else if (dir == 'R') {\n        int total = 0;\n        for (int c = 0; c < 10; ++c) if (g[pr][c] != 0) ++total;\n        int rank_left = 0;\n        for (int c = 0; c < pc; ++c) if (g[pr][c] != 0) ++rank_left;\n        nc = (10 - total) + rank_left;\n    } else if (dir == 'F') {\n        int rank_top = 0;\n        for (int r = 0; r < pr; ++r) if (g[r][pc] != 0) ++rank_top;\n        nr = rank_top;\n    } else if (dir == 'B') {\n        int total = 0;\n        for (int r = 0; r < 10; ++r) if (g[r][pc] != 0) ++total;\n        int rank_top = 0;\n        for (int r = 0; r < pr; ++r) if (g[r][pc] != 0) ++rank_top;\n        nr = (10 - total) + rank_top;\n    }\n    return {nr, nc};\n}\n\nvoid simulate(vv& g, char dir) {\n    if (dir == 'F') {\n        for (int c = 0; c < 10; ++c) {\n            vector<int> lis;\n            for (int r = 0; r < 10; ++r) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            for (int r = 0; r < sz; ++r) g[r][c] = lis[r];\n            for (int r = sz; r < 10; ++r) g[r][c] = 0;\n        }\n    } else if (dir == 'B') {\n        for (int c = 0; c < 10; ++c) {\n            vector<int> lis;\n            for (int r = 0; r < 10; ++r) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            int off = 10 - sz;\n            for (int r = 0; r < off; ++r) g[r][c] = 0;\n            for (int r = 0; r < sz; ++r) g[off + r][c] = lis[r];\n        }\n    } else if (dir == 'L') {\n        for (int r = 0; r < 10; ++r) {\n            vector<int> lis;\n            for (int c = 0; c < 10; ++c) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            for (int c = 0; c < sz; ++c) g[r][c] = lis[c];\n            for (int c = sz; c < 10; ++c) g[r][c] = 0;\n        }\n    } else if (dir == 'R') {\n        for (int r = 0; r < 10; ++r) {\n            vector<int> lis;\n            for (int c = 0; c < 10; ++c) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            int off = 10 - sz;\n            for (int c = 0; c < off; ++c) g[r][c] = 0;\n            for (int c = 0; c < sz; ++c) g[r][off + c] = lis[c];\n        }\n    }\n}\n\nlong long compute(const vv& g) {\n    bool vis[10][10] = {};\n    int dr[] = {-1, 0, 1, 0};\n    int dc[] = {0, 1, 0, -1};\n    long long sumsq = 0;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            if (g[r][c] != 0 && !vis[r][c]) {\n                int flav = g[r][c];\n                queue<pii> q;\n                q.emplace(r, c);\n                vis[r][c] = true;\n                int sz = 1;\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    for (int d = 0; d < 4; ++d) {\n                        int nr = x + dr[d];\n                        int nc = y + dc[d];\n                        if (nr >= 0 && nr < 10 && nc >= 0 && nc < 10 &&\n                            !vis[nr][nc] && g[nr][nc] == flav) {\n                            vis[nr][nc] = true;\n                            q.emplace(nr, nc);\n                            ++sz;\n                        }\n                    }\n                }\n                sumsq += 1LL * sz * sz;\n            }\n        }\n    }\n    return sumsq;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    vector<int> f(101);\n    for (int i = 1; i <= 100; ++i) {\n        cin >> f[i];\n    }\n    vv grid(10, vector<int>(10, 0));\n    set<pii> empties;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            empties.emplace(r, c);\n        }\n    }\n    string dirs = \"FBLR\";\n    int dr[] = {-1, 0, 1, 0};\n    int dc[] = {0, 1, 0, -1};\n    for (int t = 1; t <= 100; ++t) {\n        int p;\n        cin >> p;\n        auto it = empties.begin();\n        advance(it, p - 1);\n        auto [pr, pc] = *it;\n        grid[pr][pc] = f[t];\n        empties.erase(it);\n        int flav = f[t];\n\n        long long best_sc = -1;\n        int best_md = 999;\n        int best_pot = -1;\n        int best_dc = 999;\n        char best_dir = 'Z';\n        for (char d : dirs) {\n            vv temp = grid;\n            simulate(temp, d);\n            long long sc = compute(temp);\n            auto [nr, nc] = get_new_pos(grid, pr, pc, d);\n\n            // min dist to nearest other same\n            int mind = 11;\n            for (int i = 0; i < 10; ++i) {\n                for (int j = 0; j < 10; ++j) {\n                    if (temp[i][j] == flav && (i != nr || j != nc)) {\n                        int dd = abs(i - nr) + abs(j - nc);\n                        if (dd < mind) mind = dd;\n                    }\n                }\n            }\n\n            // line potential and CoM\n            vector<int> rowc(10, 0), colc(10, 0);\n            int sumr = 0, sumc_ = 0, num = 0;\n            for (int i = 0; i < 10; ++i) {\n                for (int j = 0; j < 10; ++j) {\n                    if (temp[i][j] == flav) {\n                        rowc[i]++;\n                        colc[j]++;\n                        sumr += i;\n                        sumc_ += j;\n                        num++;\n                    }\n                }\n            }\n            int pot = rowc[nr] + colc[nc] - 2;\n            int meanr = (num == 0 ? nr : sumr / num);\n            int meanc = (num == 0 ? nc : sumc_ / num);\n            int distc = abs(nr - meanr) + abs(nc - meanc);\n\n            // compare\n            bool better = false;\n            if (sc > best_sc) better = true;\n            else if (sc == best_sc) {\n                if (mind < best_md) better = true;\n                else if (mind == best_md) {\n                    if (pot > best_pot) better = true;\n                    else if (pot == best_pot) {\n                        if (distc < best_dc) better = true;\n                        else if (distc == best_dc) {\n                            if (d < best_dir) better = true;\n                        }\n                    }\n                }\n            }\n            if (better) {\n                best_sc = sc;\n                best_md = mind;\n                best_pot = pot;\n                best_dc = distc;\n                best_dir = d;\n            }\n        }\n        cout << best_dir << endl;\n        simulate(grid, best_dir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <limits>\nusing namespace std;\n\nusing Eigen::MatrixXd;\nusing Eigen::SelfAdjointEigenSolver;\nusing Eigen::VectorXd;\n\nusing Feature = vector<double>;\n\nint tri_index(int N, int i, int j) {\n  if (i > j) swap(i, j);\n  int pos = 0;\n  for (int a = 0; a < i; ++a) {\n    pos += N - 1 - a;\n  }\n  pos += j - i - 1;\n  return pos;\n}\n\nstring make_clique(int s, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  s = min(s, N);\n  for (int i = 0; i < s; ++i) {\n    for (int j = i + 1; j < s; ++j) {\n      g[tri_index(N, i, j)] = '1';\n    }\n  }\n  return g;\n}\n\nstring make_star(int leaves, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  leaves = min(leaves, N - 1);\n  for (int lv = 1; lv <= leaves; ++lv) {\n    g[tri_index(N, 0, lv)] = '1';\n  }\n  return g;\n}\n\nstring make_bipart(int a, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  a = min(a, N / 2);\n  int left = a;\n  int right_start = left;\n  for (int i = 0; i < left; ++i) {\n    for (int jj = 0; jj < N - left; ++jj) {\n      int j = right_start + jj;\n      g[tri_index(N, i, j)] = '1';\n    }\n  }\n  return g;\n}\n\nstring make_path(int s, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  s = min(s, N);\n  for (int i = 0; i < s - 1; ++i) {\n    g[tri_index(N, i, i + 1)] = '1';\n  }\n  return g;\n}\n\nstring make_cycle(int c, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  c = min(c, N);\n  if (c < 3) return make_path(c, N);\n  for (int i = 0; i < c; ++i) {\n    int j = (i + 1) % c;\n    g[tri_index(N, i, j)] = '1';\n  }\n  return g;\n}\n\nFeature get_feature(const string& s, int N) {\n  int B = N * (N - 1) / 2;\n  MatrixXd A(N, N);\n  A.setZero();\n  for (int i = 0; i < N; ++i) {\n    for (int j = i + 1; j < N; ++j) {\n      double val = s[tri_index(N, i, j)] - '0';\n      A(i, j) = val;\n      A(j, i) = val;\n    }\n  }\n  // Adjacency eigenvalues\n  SelfAdjointEigenSolver<MatrixXd> solverA(A);\n  VectorXd evA = solverA.eigenvalues();\n  vector<double> lambdaA(N);\n  for (int k = 0; k < N; ++k) lambdaA[k] = evA(k);\n  sort(lambdaA.rbegin(), lambdaA.rend());\n\n  // Sorted degrees descending\n  VectorXd deg = A.rowwise().sum();\n  vector<double> sdeg(N);\n  for (int k = 0; k < N; ++k) sdeg[k] = deg(k);\n  sort(sdeg.rbegin(), sdeg.rend());\n\n  // Laplacian eigenvalues\n  MatrixXd L(N, N);\n  L.setZero();\n  L.diagonal() = deg;\n  L -= A;\n  SelfAdjointEigenSolver<MatrixXd> solverL(L);\n  VectorXd evL = solverL.eigenvalues();\n  vector<double> lambdaL(N);\n  for (int k = 0; k < N; ++k) lambdaL[k] = evL(k);\n  sort(lambdaL.rbegin(), lambdaL.rend());\n\n  // Concatenate\n  Feature feat;\n  feat.reserve(3 * N);\n  feat.insert(feat.end(), lambdaA.begin(), lambdaA.end());\n  feat.insert(feat.end(), sdeg.begin(), sdeg.end());\n  feat.insert(feat.end(), lambdaL.begin(), lambdaL.end());\n  return feat;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n  int M;\n  double eps;\n  cin >> M >> eps;\n  int N = min(100, max(4, (int)(20 + 80 * (1 - eps))));\n  cout << N << '\\n';\n\n  vector<string> cand_repr;\n  vector<Feature> cand_feat;\n  auto add_cand = [&](const string& g) {\n    cand_repr.push_back(g);\n    cand_feat.push_back(get_feature(g, N));\n  };\n  // Cliques\n  for (int s = 1; s <= N; ++s) {\n    add_cand(make_clique(s, N));\n  }\n  // Stars\n  for (int l = 1; l < N; ++l) {\n    add_cand(make_star(l, N));\n  }\n  // Bipartites\n  for (int a = 1; a <= N / 2; ++a) {\n    add_cand(make_bipart(a, N));\n  }\n  // Paths\n  for (int s = 2; s <= N; ++s) {\n    add_cand(make_path(s, N));\n  }\n  // Cycles\n  for (int c = 3; c <= N; ++c) {\n    add_cand(make_cycle(c, N));\n  }\n  int nc = cand_feat.size();\n  vector<bool> used(nc, false);\n  vector<int> chosen;\n  for (int ck = 0; ck < M; ++ck) {\n    int best_ci = -1;\n    double max_mind = -numeric_limits<double>::infinity();\n    for (int ci = 0; ci < nc; ++ci) {\n      if (used[ci]) continue;\n      double mind = numeric_limits<double>::infinity();\n      for (int pi : chosen) {\n        double dd = 0.0;\n        const auto& f1 = cand_feat[ci];\n        const auto& f2 = cand_feat[pi];\n        for (size_t j = 0; j < f1.size(); ++j) {\n          double dif = f1[j] - f2[j];\n          dd += dif * dif;\n        }\n        mind = min(mind, dd);\n      }\n      if (mind > max_mind) {\n        max_mind = mind;\n        best_ci = ci;\n      }\n    }\n    used[best_ci] = true;\n    chosen.push_back(best_ci);\n  }\n\n  vector<Feature> codebook_feat(M);\n  for (int k = 0; k < M; ++k) {\n    int ci = chosen[k];\n    cout << cand_repr[ci] << '\\n';\n    codebook_feat[k] = cand_feat[ci];\n  }\n  cout << std::flush;\n\n  for (int q = 0; q < 100; ++q) {\n    string H;\n    cin >> H;\n    Feature fh = get_feature(H, N);\n    double best_d = numeric_limits<double>::infinity();\n    int tk = 0;\n    for (int k = 0; k < M; ++k) {\n      double dd = 0.0;\n      const auto& fk = codebook_feat[k];\n      for (size_t j = 0; j < fh.size(); ++j) {\n        double dif = fh[j] - fk[j];\n        dd += dif * dif;\n      }\n      if (dd < best_d) {\n        best_d = dd;\n        tk = k;\n      }\n    }\n    cout << tk << '\\n' << std::flush;\n  }\n  return 0;\n}","ahc017":"","ahc019":"","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Edge {\n    int u, v, id;\n    ll w;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    cin >> N >> M >> K;\n    vector<ll> xs(N + 1), ys(N + 1);\n    for (int i = 1; i <= N; ++i) {\n        cin >> xs[i] >> ys[i];\n    }\n    vector<Edge> edgs(M);\n    for (int j = 0; j < M; ++j) {\n        int u, v;\n        ll w;\n        cin >> u >> v >> w;\n        edgs[j] = {u, v, j + 1, w};\n    }\n    vector<ll> as(K + 1), bs(K + 1);\n    for (int k = 1; k <= K; ++k) {\n        cin >> as[k] >> bs[k];\n    }\n    // precompute distsq\n    vector<vector<ll>> distsq(N + 1, vector<ll>(K + 1));\n    for (int i = 1; i <= N; ++i) {\n        for (int k = 1; k <= K; ++k) {\n            ll dx = xs[i] - as[k];\n            ll dy = ys[i] - bs[k];\n            distsq[i][k] = dx * dx + dy * dy;\n        }\n    }\n    // terminals\n    set<int> terms;\n    terms.insert(1);\n    vector<int> assignn(K + 1);\n    for (int k = 1; k <= K; ++k) {\n        ll md = distsq[1][k];\n        int bi = 1;\n        for (int i = 2; i <= N; ++i) {\n            ll d2 = distsq[i][k];\n            if (d2 < md) {\n                md = d2;\n                bi = i;\n            }\n        }\n        assignn[k] = bi;\n        terms.insert(bi);\n    }\n    // UF\n    vector<int> par(N + 1);\n    for (int i = 0; i <= N; ++i) par[i] = i;\n    auto findf = [&](auto&& self, int x) -> int {\n        return par[x] == x ? x : par[x] = self(self, par[x]);\n    };\n    auto unitef = [&](int a, int b) {\n        int pa = findf(findf, a);\n        int pb = findf(findf, b);\n        if (pa == pb) return;\n        par[pa] = pb;\n    };\n    // MST\n    vector<int> B(M + 1, 0);\n    vector<Edge> sorted_edgs = edgs;\n    sort(sorted_edgs.begin(), sorted_edgs.end(), [](const Edge& a, const Edge& b) {\n        return a.w < b.w;\n    });\n    ll edge_cost = 0;\n    vector<int> mst_ids;\n    for (auto& e : sorted_edgs) {\n        int pu = findf(findf, e.u);\n        int pv = findf(findf, e.v);\n        if (pu != pv) {\n            unitef(e.u, e.v);\n            B[e.id] = 1;\n            edge_cost += e.w;\n            mst_ids.push_back(e.id);\n        }\n    }\n    // tree_adj\n    vector<vector<pair<int, int>>> tree_adj(N + 1);\n    for (int eid : mst_ids) {\n        const Edge& e = edgs[eid - 1];\n        tree_adj[e.u].emplace_back(e.v, eid);\n        tree_adj[e.v].emplace_back(e.u, eid);\n    }\n    // degrees\n    vector<int> deg(N + 1);\n    for (int i = 1; i <= N; ++i) {\n        deg[i] = tree_adj[i].size();\n    }\n    // prune queue\n    queue<int> to_prune;\n    for (int i = 1; i <= N; ++i) {\n        if (deg[i] == 1 && i != 1 && terms.find(i) == terms.end()) {\n            to_prune.push(i);\n        }\n    }\n    while (!to_prune.empty()) {\n        int u = to_prune.front();\n        to_prune.pop();\n        if (deg[u] != 1 || u == 1) continue;\n        if (terms.find(u) != terms.end()) continue;\n        // prune\n        auto [pu, eid] = tree_adj[u][0];\n        B[eid] = 0;\n        edge_cost -= edgs[eid - 1].w;\n        // update deg\n        deg[u] = 0;\n        deg[pu]--;\n        // check if pu becomes leaf\n        if (deg[pu] == 1 && pu != 1 && terms.find(pu) == terms.end()) {\n            to_prune.push(pu);\n        }\n    }\n    // now compute current component\n    vector<bool> vis(N + 1, false);\n    queue<int> qcomp;\n    qcomp.push(1);\n    vis[1] = true;\n    while (!qcomp.empty()) {\n        int u = qcomp.front();\n        qcomp.pop();\n        for (int jj = 1; jj <= M; ++jj) {\n            if (B[jj] == 0) continue;\n            const Edge& ee = edgs[jj - 1];\n            int vv = (ee.u == u ? ee.v : ee.u);\n            if (!vis[vv]) {\n                vis[vv] = true;\n                qcomp.push(vv);\n            }\n        }\n    }\n    vector<int> comp;\n    for (int i = 1; i <= N; ++i) {\n        if (vis[i]) comp.push_back(i);\n    }\n    // now assign needs\n    vector<ll> need(N + 1, 0);\n    for (int k = 1; k <= K; ++k) {\n        ll md2 = LLONG_MAX / 2;\n        int bi = -1;\n        for (int i : comp) {\n            ll d2 = distsq[i][k];\n            if (d2 < md2) {\n                md2 = d2;\n                bi = i;\n            }\n        }\n        need[bi] = max(need[bi], md2);\n    }\n    // calc P\n    auto calc_p = [](ll d2) -> int {\n        if (d2 == 0) return 0;\n        double sd = sqrt((double)d2);\n        int p = (int)ceil(sd);\n        while ((ll)p * p < d2) ++p;\n        while (p > 0 && (ll)(p - 1) * (p - 1) >= d2) --p;\n        return p;\n    };\n    vector<int> PP(N + 1, 0);\n    ll cov_cost = 0;\n    for (int i = 1; i <= N; ++i) {\n        if (need[i] > 0) {\n            PP[i] = calc_p(need[i]);\n            cov_cost += (ll)PP[i] * PP[i];\n        }\n    }\n    // output\n    for (int i = 1; i <= N; ++i) {\n        cout << PP[i];\n        cout << (i < N ? \" \" : \"\\n\");\n    }\n    for (int j = 1; j <= M; ++j) {\n        cout << B[j];\n        cout << (j < M ? \" \" : \"\\n\");\n    }\n    return 0;\n}","ahc021":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int, int>;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N = 30;\n  int total = N * (N + 1) / 2;\n  vector<int> cum(N + 1, 0);\n  for (int i = 1; i <= N; ++i) {\n    cum[i] = cum[i - 1] + i;\n  }\n  vector<pii> coord(total);\n  vector<vector<int>> flat_pos(N, vector<int>(N));\n  for (int x = 0; x < N; ++x) {\n    for (int y = 0; y <= x; ++y) {\n      int id = cum[x] + y;\n      coord[id] = {x, y};\n      flat_pos[x][y] = id;\n    }\n  }\n  vector<int> a(total);\n  for (int i = 0; i < total; ++i) {\n    cin >> a[i];\n  }\n  vector<vector<int>> childs(total);\n  for (int x = 0; x < N - 1; ++x) {\n    for (int y = 0; y <= x; ++y) {\n      int p = flat_pos[x][y];\n      int l = flat_pos[x + 1][y];\n      int r = flat_pos[x + 1][y + 1];\n      childs[p] = {l, r};\n    }\n  }\n  // Simulate to choose best direction\n  auto get_swap_count = [&](bool ltr) -> int {\n    vector<int> arr = a;\n    int swaps = 0;\n    auto siftdown = [&](auto&& self, int node) -> void {\n      while (true) {\n        const auto& ch = childs[node];\n        if (ch.empty()) return;\n        int l = ch[0], r = ch[1];\n        int sm = node;\n        if (arr[l] < arr[sm]) sm = l;\n        if (arr[r] < arr[sm]) sm = r;\n        if (sm == node) return;\n        swap(arr[node], arr[sm]);\n        ++swaps;\n        node = sm;\n      }\n    };\n    for (int xx = N - 2; xx >= 0; --xx) {\n      if (ltr) {\n        for (int yy = 0; yy <= xx; ++yy) {\n          int node = flat_pos[xx][yy];\n          siftdown(siftdown, node);\n        }\n      } else {\n        for (int yy = xx; yy >= 0; --yy) {\n          int node = flat_pos[xx][yy];\n          siftdown(siftdown, node);\n        }\n      }\n    }\n    return swaps;\n  };\n  int cnt1 = get_swap_count(true);\n  int cnt2 = get_swap_count(false);\n  bool use_ltr = (cnt1 <= cnt2);\n  // Now perform the real one\n  vector<int> cur_a = a;\n  vector<vector<int>> ops;\n  auto real_siftdown = [&](auto&& self, int node) -> void {\n    while (true) {\n      const auto& ch = childs[node];\n      if (ch.empty()) return;\n      int l = ch[0], r = ch[1];\n      int sm = node;\n      if (cur_a[l] < cur_a[sm]) sm = l;\n      if (cur_a[r] < cur_a[sm]) sm = r;\n      if (sm == node) return;\n      swap(cur_a[node], cur_a[sm]);\n      int p1 = node, p2 = sm;\n      auto [x1, y1] = coord[p1];\n      auto [x2, y2] = coord[p2];\n      ops.push_back({x1, y1, x2, y2});\n      node = sm;\n    }\n  };\n  for (int xx = N - 2; xx >= 0; --xx) {\n    if (use_ltr) {\n      for (int yy = 0; yy <= xx; ++yy) {\n        int node = flat_pos[xx][yy];\n        real_siftdown(real_siftdown, node);\n      }\n    } else {\n      for (int yy = xx; yy >= 0; --yy) {\n        int node = flat_pos[xx][yy];\n        real_siftdown(real_siftdown, node);\n      }\n    }\n  }\n  cout << ops.size() << '\\n';\n  for (auto& op : ops) {\n    cout << op[0] << ' ' << op[1] << ' ' << op[2] << ' ' << op[3] << '\\n';\n  }\n}","toyota2023summer-final":"","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n, m;\n  cin >> n >> m;\n  vector<vector<int>> grid(n, vector<int>(n));\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      cin >> grid[i][j];\n    }\n  }\n  vector<int> touches0(m + 1, 0);\n  vector<pair<int, int>> anchor(m + 1, make_pair(-1, -1));\n  vector<int> cursize(m + 1, 0);\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      int c = grid[i][j];\n      cursize[c]++;\n      if ((i == 0 || i == n - 1 || j == 0 || j == n - 1) && anchor[c].first == -1) {\n        anchor[c] = {i, j};\n        touches0[c] = 1;\n      } else if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {\n        touches0[c] = 1;\n      }\n    }\n  }\n  vector<vector<int>> cnt(m + 1, vector<int>(m + 1, 0));\n  // horizontal\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n - 1; ++j) {\n      int a = grid[i][j], b = grid[i][j + 1];\n      if (a != b && a > 0 && b > 0) {\n        int u = min(a, b), v = max(a, b);\n        cnt[u][v]++;\n      }\n    }\n  }\n  // vertical\n  for (int i = 0; i < n - 1; ++i) {\n    for (int j = 0; j < n; ++j) {\n      int a = grid[i][j], b = grid[i + 1][j];\n      if (a != b && a > 0 && b > 0) {\n        int u = min(a, b), v = max(a, b);\n        cnt[u][v]++;\n      }\n    }\n  }\n\n  vector<pair<int, int>> dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n  auto peel = [&](vector<vector<int>> g, const vector<int>& init_size) -> pair<vector<vector<int>>, int> {\n    vector<vector<int>> out = g;\n    vector<int> size_ = init_size;\n    auto cnte = cnt;\n    bool changed = true;\n    while (changed) {\n      changed = false;\n      for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n          if (out[i][j] == 0) continue;\n          int c = out[i][j];\n          if (anchor[c].first == i && anchor[c].second == j) continue;\n          if (size_[c] == 1) continue;\n          int same_n = 0;\n          bool can_zero = (i == 0 || i == n - 1 || j == 0 || j == n - 1);\n          int adj_cnt[101] = {};\n          bool would_hurt_i = false;\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) continue;\n            int nc = out[ni][nj];\n            if (nc == c) {\n              ++same_n;\n            } else if (nc == 0) {\n              can_zero = true;\n            } else {\n              ++adj_cnt[nc];\n              if (touches0[nc] == 0) would_hurt_i = true;\n            }\n          }\n          bool safe_adj = true;\n          for (int nc = 1; nc <= m; ++nc) {\n            if (adj_cnt[nc] > 0) {\n              int u = min(c, nc), v = max(c, nc);\n              if (cnte[u][v] == adj_cnt[nc]) {\n                safe_adj = false;\n                break;\n              }\n            }\n          }\n          if (same_n > 1 || !safe_adj || !can_zero || would_hurt_i) continue;\n          // remove\n          out[i][j] = 0;\n          size_[c]--;\n          // update cnt\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n              int nc = out[ni][nj];\n              if (nc > 0 && nc != c) {\n                int u = min(c, nc), v = max(c, nc);\n                cnte[u][v]--;\n              }\n            }\n          }\n          changed = true;\n        }\n      }\n    }\n    int zeros = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        if (out[i][j] == 0) ++zeros;\n      }\n    }\n    return {out, zeros};\n  };\n\n  auto [out1, z1] = peel(grid, cursize);\n\n  auto peel_rev = [&](vector<vector<int>> g, const vector<int>& init_size) -> pair<vector<vector<int>>, int> {\n    vector<vector<int>> out = g;\n    vector<int> size_ = init_size;\n    auto cnte = cnt;\n    bool changed = true;\n    while (changed) {\n      changed = false;\n      for (int i = n - 1; i >= 0; --i) {\n        for (int j = n - 1; j >= 0; --j) {\n          if (out[i][j] == 0) continue;\n          int c = out[i][j];\n          if (anchor[c].first == i && anchor[c].second == j) continue;\n          if (size_[c] == 1) continue;\n          int same_n = 0;\n          bool can_zero = (i == 0 || i == n - 1 || j == 0 || j == n - 1);\n          int adj_cnt[101] = {};\n          bool would_hurt_i = false;\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) continue;\n            int nc = out[ni][nj];\n            if (nc == c) {\n              ++same_n;\n            } else if (nc == 0) {\n              can_zero = true;\n            } else {\n              ++adj_cnt[nc];\n              if (touches0[nc] == 0) would_hurt_i = true;\n            }\n          }\n          bool safe_adj = true;\n          for (int nc = 1; nc <= m; ++nc) {\n            if (adj_cnt[nc] > 0) {\n              int u = min(c, nc), v = max(c, nc);\n              if (cnte[u][v] == adj_cnt[nc]) {\n                safe_adj = false;\n                break;\n              }\n            }\n          }\n          if (same_n > 1 || !safe_adj || !can_zero || would_hurt_i) continue;\n          // remove\n          out[i][j] = 0;\n          size_[c]--;\n          // update cnt\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n              int nc = out[ni][nj];\n              if (nc > 0 && nc != c) {\n                int u = min(c, nc), v = max(c, nc);\n                cnte[u][v]--;\n              }\n            }\n          }\n          changed = true;\n        }\n      }\n    }\n    int zeros = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        if (out[i][j] == 0) ++zeros;\n      }\n    }\n    return {out, zeros};\n  };\n\n  auto [out2, z2] = peel_rev(grid, cursize);\n\n  // pick the better one\n  vector<vector<int>> final_out = (z1 >= z2 ? out1 : out2);\n\n  // output\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      cout << final_out[i][j];\n      if (j < n - 1) cout << \" \";\n    }\n    cout << \"\\n\";\n  }\n  return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  unsigned seed = chrono::duration_cast<chrono::microseconds>(\n      chrono::steady_clock::now().time_since_epoch()).count();\n  mt19937 rng(seed);\n  int N, D, Q;\n  cin >> N >> D >> Q;\n  vector<vector<int8_t>> cmp(N, vector<int8_t>(N, -2));\n  vector<int> perm(N);\n  iota(perm.begin(), perm.end(), 0);\n  int q_used = 0;\n  // Main querying loop with shuffled pairings\n  while (q_used < Q) {\n    shuffle(perm.begin(), perm.end(), rng);\n    for (int i = 0; i + 1 < N; i += 2) {\n      if (q_used >= Q) break;\n      int a = perm[i], b = perm[i + 1];\n      if (cmp[a][b] != -2) continue;\n      // Query\n      cout << 1 << ' ' << 1 << ' ' << a << ' ' << b << '\\n';\n      cout.flush();\n      string res;\n      cin >> res;\n      int8_t val;\n      if (res == \"<\") val = -1;\n      else if (res == \">\") val = 1;\n      else val = 0;\n      cmp[a][b] = val;\n      cmp[b][a] = -val;\n      q_used++;\n    }\n  }\n  // Dummy queries to reach exactly Q if needed\n  int dummy_a = 0, dummy_b = 1;\n  while (q_used < Q) {\n    cout << 1 << ' ' << 1 << ' ' << dummy_a << ' ' << dummy_b << '\\n';\n    cout.flush();\n    string res;\n    cin >> res;\n    q_used++;\n  }\n  // Build beat graph: adj[i] = lighter items directly beaten by i (cmp[i][j] > 0)\n  vector<vector<int>> adj(N);\n  for (int i = 0; i < N; i++) {\n    for (int j = 0; j < N; j++) {\n      if (i != j && cmp[i][j] > 0) {\n        adj[i].push_back(j);\n      }\n    }\n  }\n  // Compute reachability sizes\n  vector<int> reach(N);\n  for (int s = 0; s < N; s++) {\n    vector<char> vis(N, 0);\n    queue<int> qq;\n    qq.push(s);\n    vis[s] = 1;\n    int cnt = 1;\n    while (!qq.empty()) {\n      int u = qq.front();\n      qq.pop();\n      for (int v : adj[u]) {\n        if (!vis[v]) {\n          vis[v] = 1;\n          cnt++;\n          qq.push(v);\n        }\n      }\n    }\n    reach[s] = cnt;\n  }\n  // Rank by descending reach size\n  vector<pair<int, int>> ranked;\n  for (int i = 0; i < N; i++) {\n    ranked.emplace_back(-reach[i], i);\n  }\n  sort(ranked.begin(), ranked.end());\n  // Assign groups round-robin from heaviest\n  vector<int> group(N);\n  int gid = 0;\n  for (auto& p : ranked) {\n    group[p.second] = gid;\n    gid = (gid + 1) % D;\n  }\n  // Output assignment\n  for (int i = 0; i < N; i++) {\n    cout << group[i];\n    if (i + 1 < N) cout << ' ';\n    else cout << '\\n';\n  }\n  return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n, m;\n  cin >> n >> m;\n  vector<vector<int>> stacks(m);\n  vector<int> location(n + 1, -1);\n  int h = n / m;\n  for (int i = 0; i < m; i++) {\n    stacks[i].resize(h);\n    for (int j = 0; j < h; j++) {\n      cin >> stacks[i][j];\n      location[stacks[i][j]] = i;\n    }\n  }\n  vector<pair<int, int>> ops;\n  int next_box = 1;\n  const int INF = INT_MAX / 2;\n  while (next_box <= n) {\n    int s = location[next_box];\n    if (s != -1 && !stacks[s].empty() && stacks[s].back() == next_box) {\n      // carry out\n      ops.emplace_back(next_box, 0);\n      stacks[s].pop_back();\n      location[next_box] = -1;\n      next_box++;\n      continue;\n    }\n    // expose by moving pile above\n    auto& stk = stacks[s];\n    auto it = find(stk.begin(), stk.end(), next_box);\n    size_t p = it - stk.begin();\n    size_t start_idx = p + 1;\n    int v_move = stk[start_idx];\n    int pile_top = stk.back();\n    // find best dest\n    int best_d = -1;\n    int best_score = -1;\n    for (int d = 0; d < m; d++) {\n      if (d == s) continue;\n      const auto& dstk = stacks[d];\n      bool is_empty = dstk.empty();\n      int tt = is_empty ? INF : dstk.back();\n      bool acceptable = is_empty || (tt > pile_top);\n      if (acceptable) {\n        int sc = tt;\n        if (sc > best_score) {\n          best_score = sc;\n          best_d = d;\n        }\n      }\n    }\n    if (best_d == -1) {\n      // fallback: max anywhere\n      best_score = -1;\n      for (int d = 0; d < m; d++) {\n        if (d == s) continue;\n        const auto& dstk = stacks[d];\n        int sc = dstk.empty() ? INF : dstk.back();\n        if (sc > best_score) {\n          best_score = sc;\n          best_d = d;\n        }\n      }\n    }\n    // perform move\n    auto& dstk = stacks[best_d];\n    vector<int> pile(stk.begin() + start_idx, stk.end());\n    stk.resize(start_idx);\n    dstk.insert(dstk.end(), pile.begin(), pile.end());\n    for (int b : pile) {\n      location[b] = best_d;\n    }\n    ops.emplace_back(v_move, best_d + 1);\n  }\n  for (auto [v, i] : ops) {\n    cout << v << ' ' << i << '\\n';\n  }\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N;\n  cin >> N;\n  vector<string> H(N - 1);\n  for (auto& s : H) cin >> s;\n  vector<string> V(N);\n  for (auto& s : V) cin >> s;\n  vector<vector<int>> D(N, vector<int>(N));\n  long long sumD = 0;\n  for (int i = 0; i < N; i++) {\n    for (int j = 0; j < N; j++) {\n      cin >> D[i][j];\n      sumD += D[i][j];\n    }\n  }\n  int dr[4] = {0, 1, 0, -1};\n  int dc[4] = {1, 0, -1, 0};\n  char dirchar[4] = {'R', 'D', 'L', 'U'};\n  auto no_wall = [&](int r, int c, int d) -> bool {\n    int nr = r + dr[d];\n    int nc = c + dc[d];\n    if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n    if (dr[d] == 0) {  // horizontal\n      int cmin = min(c, nc);\n      return V[r][cmin] == '0';\n    } else {  // vertical\n      int rmin = min(r, nr);\n      return H[rmin][c] == '0';\n    }\n  };\n  // BFS dist from (0,0)\n  vector<vector<int>> Dist(N, vector<int>(N, -1));\n  {\n    queue<pair<int, int>> q;\n    q.emplace(0, 0);\n    Dist[0][0] = 0;\n    while (!q.empty()) {\n      auto [r, c] = q.front();\n      q.pop();\n      for (int d = 0; d < 4; d++) {\n        int nr = r + dr[d], nc = c + dc[d];\n        if (nr >= 0 && nr < N && nc >= 0 && nc < N && Dist[nr][nc] == -1 && no_wall(r, c, d)) {\n          Dist[nr][nc] = Dist[r][c] + 1;\n          q.emplace(nr, nc);\n        }\n      }\n    }\n  }\n  // score func\n  auto compute_score = [&](const string& p) -> double {\n    int L = p.size();\n    if (L == 0 || L % 2 != 0) return 1e18;  // rough check even L\n    vector<vector<int>> lastv(N, vector<int>(N, 0));\n    int cur_t = 0, r = 0, c = 0;\n    array<int, 256> dir2d = {};\n    dir2d['R'] = 0;\n    dir2d['D'] = 1;\n    dir2d['L'] = 2;\n    dir2d['U'] = 3;\n    // first cycle\n    for (char ch : p) {\n      int d = dir2d[ch];\n      int nr = r + dr[d];\n      int nc = c + dc[d];\n      cur_t++;\n      lastv[nr][nc] = cur_t;\n      r = nr;\n      c = nc;\n    }\n    if (r != 0 || c != 0) return 1e18;  // must end at 0,0\n    // check all visited\n    bool allv = true;\n    for (int i = 0; i < N; i++) {\n      for (int j = 0; j < N; j++) {\n        if (lastv[i][j] == 0) allv = false;\n      }\n    }\n    if (!allv) return 1e18;\n    // S_L\n    long long cur_total = 0;\n    for (int i = 0; i < N; i++) {\n      for (int j = 0; j < N; j++) {\n        cur_total += (long long)D[i][j] * (cur_t - lastv[i][j]);\n      }\n    }\n    long long sum_sec = cur_total;\n    // second cycle L-1 steps\n    for (int sp = 0; sp < L - 1; sp++) {\n      char ch = p[sp];\n      int d = dir2d[ch];\n      int nr = r + dr[d];\n      int nc = c + dc[d];\n      long long old_dirt = (long long)D[nr][nc] * (cur_t - lastv[nr][nc]);\n      long long delta = (sumD - D[nr][nc]) - old_dirt;\n      cur_total += delta;\n      cur_t++;\n      lastv[nr][nc] = cur_t;\n      sum_sec += cur_total;\n      r = nr;\n      c = nc;\n    }\n    return (double)sum_sec / L;\n  };\n  // gen_path\n  vector<function<double(int, int)>> prios;\n  vector<double> alphas = {0.25, 1.0/3, 0.4, 0.45, 0.5, 0.55, 0.6, 2.0/3, 0.75};\n  for (double al : alphas) {\n    prios.push_back( [al, &D](int i, int j) { return pow(D[i][j], al); } );\n  }\n  prios.push_back( [&D](int i,int j){ return (double)D[i][j]; } );\n  prios.push_back( [&D, &Dist](int i,int j){ return sqrt(D[i][j]) / (1.0 + Dist[i][j]); } );\n  prios.push_back( [&D, &Dist](int i,int j){ return (double)D[i][j] / (1.0 + Dist[i][j]); } );\n  prios.push_back( [&Dist](int i,int j){ return 100.0 / (1.0 + Dist[i][j]); } );\n  prios.push_back( [&Dist](int i,int j){ return -Dist[i][j]; } );\n  prios.push_back( [&](int i,int j){ return 10000.0 / (1.0 + i * N + j); } );  // row-major top-left\n  prios.push_back( [&](int i,int j){ \n    double colp = (i % 2 == 0 ? j : N - 1 - j);\n    return 10000.0 / (1.0 + i * N + (N - 1 - colp));  // snake\n  } );\n  string best_path;\n  double best_sc = 1e100;\n  auto gen_path = [&](auto&& prio_f) -> string {\n    vector<vector<char>> vis(N, vector<char>(N, 0));\n    string pth;\n    pth.reserve(100000);\n    auto dfs = [&](auto&& self, int r, int c) -> void {\n      vis[r][c] = 1;\n      vector<pair<double, int>> cands;\n      for (int d = 0; d < 4; d++) {\n        int nr = r + dr[d], nc = c + dc[d];\n        if (nr >= 0 && nr < N && nc >= 0 && nc < N && !vis[nr][nc] && no_wall(r, c, d)) {\n          double pr = prio_f(nr, nc);\n          cands.emplace_back(-pr, d);\n        }\n      }\n      sort(cands.begin(), cands.end());\n      for (auto [_, d] : cands) {\n        int nr = r + dr[d];\n        int nc = c + dc[d];\n        pth += dirchar[d];\n        self(self, nr, nc);\n        pth += dirchar[(d + 2) % 4];\n      }\n    };\n    dfs(dfs, 0, 0);\n    return pth;\n  };\n  for (const auto& pf : prios) {\n    string cand = gen_path(pf);\n    double sc = compute_score(cand);\n    if (sc < best_sc) {\n      best_sc = sc;\n      best_path = std::move(cand);\n    }\n  }\n  cout << best_path << '\\n';\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing pii = pair<int, int>;\nint manh(pii a, pii b) { return abs(a.first - b.first) + abs(a.second - b.second); }\n\nconst int INF = 1000000010;\n\nstruct PartialEmb {\n  int movecost = INF;\n  vector<pii> seq;\n};\n\nstruct Emb {\n  array<pii, 5> seq;\n  int intd;\n};\n\nint compute_T(const vector<pii>& pa, pii inip) {\n  if (pa.empty()) return 0;\n  int res = 0;\n  pii pr = inip;\n  for (auto p : pa) {\n    res += manh(pr, p) + 1;\n    pr = p;\n  }\n  return res;\n}\n\nvector<int> do_2opt(vector<int> ord, pii initp, const vector<Emb>& embs, int M) {\n  int passes = 0;\n  bool improved;\n  do {\n    improved = false;\n    for (int a = 0; a < M; ++a) {\n      for (int b = a + 1; b < M; ++b) {\n        pii prev_end = (a == 0 ? initp : embs[ord[a - 1]].seq[4]);\n        pii sa = embs[ord[a]].seq[0];\n        int old1 = manh(prev_end, sa);\n        int old2 = (b == M - 1 ? 0 : manh(embs[ord[b]].seq[4], embs[ord[b + 1]].seq[0]));\n        pii sb = embs[ord[b]].seq[0];\n        int new1 = manh(prev_end, sb);\n        pii ea = embs[ord[a]].seq[4];\n        int new2 = (b == M - 1 ? 0 : manh(ea, embs[ord[b + 1]].seq[0]));\n        int delta = new1 + new2 - old1 - old2;\n        if (delta < 0) {\n          reverse(ord.begin() + a, ord.begin() + b + 1);\n          improved = true;\n        }\n      }\n    }\n  } while (improved && ++passes < 500);\n  return ord;\n}\n\nint compute_inter(const vector<int>& ord, pii initp, const vector<Emb>& embs) {\n  int M = ord.size();\n  if (M == 0) return 0;\n  int sumd = manh(initp, embs[ord[0]].seq[0]);\n  for (int i = 0; i < M - 1; ++i) {\n    sumd += manh(embs[ord[i]].seq[4], embs[ord[i + 1]].seq[0]);\n  }\n  return sumd;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M;\n  cin >> N >> M;\n  int si, sj;\n  cin >> si >> sj;\n  pii initp = {si, sj};\n  vector<string> grid(N);\n  for (auto& s : grid) cin >> s;\n  vector<vector<pii>> pos(26);\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      int c = grid[i][j] - 'A';\n      pos[c].emplace_back(i, j);\n    }\n  }\n  vector<string> ts(M);\n  for (auto& s : ts) cin >> s;\n\n  // Precompute best partials\n  vector<vector<vector<PartialEmb>>> best_partials(M, vector<vector<PartialEmb>>(5));\n  vector<vector<int>> cand_sz(M, vector<int>(5));\n  for (int k = 0; k < M; ++k) {\n    string t = ts[k];\n    auto& szz = cand_sz[k];\n    for (int l = 0; l < 5; ++l) {\n      int cc = t[l] - 'A';\n      szz[l] = pos[cc].size();\n      best_partials[k][l].assign(szz[l], PartialEmb());\n    }\n    vector<pii> candd[5];\n    for (int l = 0; l < 5; ++l) candd[l] = pos[t[l] - 'A'];\n    int sz[5];\n    for (int l = 0; l < 5; ++l) sz[l] = szz[l];\n    for (int a0 = 0; a0 < sz[0]; ++a0) {\n      pii p0 = candd[0][a0];\n      for (int a1 = 0; a1 < sz[1]; ++a1) {\n        pii p1 = candd[1][a1];\n        int d01 = manh(p0, p1);\n        for (int a2 = 0; a2 < sz[2]; ++a2) {\n          pii p2 = candd[2][a2];\n          int d12 = manh(p1, p2);\n          int cum2 = d01 + d12;\n          for (int a3 = 0; a3 < sz[3]; ++a3) {\n            pii p3 = candd[3][a3];\n            int d23 = manh(p2, p3);\n            int cum3 = cum2 + d23;\n            for (int a4 = 0; a4 < sz[4]; ++a4) {\n              pii p4 = candd[4][a4];\n              int d34 = manh(p3, p4);\n              int cum4 = cum3 + d34;\n              // sl=0\n              {\n                auto& pe = best_partials[k][0][a0];\n                if (cum4 < pe.movecost) {\n                  pe.movecost = cum4;\n                  pe.seq = {p0, p1, p2, p3, p4};\n                }\n              }\n              // sl=1\n              {\n                int mc = cum4 - d01;\n                auto& pe = best_partials[k][1][a1];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p1, p2, p3, p4};\n                }\n              }\n              // sl=2\n              {\n                int mc = cum4 - cum2;\n                auto& pe = best_partials[k][2][a2];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p2, p3, p4};\n                }\n              }\n              // sl=3\n              {\n                int mc = cum4 - cum3;\n                auto& pe = best_partials[k][3][a3];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p3, p4};\n                }\n              }\n              // sl=4\n              {\n                int mc = 0;\n                auto& pe = best_partials[k][4][a4];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p4};\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  // Extract fixed embs\n  vector<Emb> embs(M);\n  for (int k = 0; k < M; ++k) {\n    int min_intd = INF;\n    int best_a = -1;\n    for (int a = 0; a < cand_sz[k][0]; ++a) {\n      int mc = best_partials[k][0][a].movecost;\n      if (mc < min_intd) {\n        min_intd = mc;\n        best_a = a;\n      }\n    }\n    embs[k].intd = min_intd;\n    embs[k].seq = {best_partials[k][0][best_a].seq[0], best_partials[k][0][best_a].seq[1],\n                   best_partials[k][0][best_a].seq[2], best_partials[k][0][best_a].seq[3],\n                   best_partials[k][0][best_a].seq[4]};\n  }\n\n  // Compute dist_init\n  vector<int> dist_init(M);\n  for (int k = 0; k < M; ++k) {\n    dist_init[k] = manh(initp, embs[k].seq[0]);\n  }\n\n  // NN order\n  vector<int> order_nn(M);\n  vector<bool> usd(M, false);\n  pii curp = initp;\n  for (int st = 0; st < M; ++st) {\n    int bestk = -1;\n    int mindd = INF;\n    for (int k = 0; k < M; ++k) {\n      if (usd[k]) continue;\n      pii stp = embs[k].seq[0];\n      int dd = manh(curp, stp);\n      if (dd < mindd || (dd == mindd && k < bestk)) {\n        mindd = dd;\n        bestk = k;\n      }\n    }\n    order_nn[st] = bestk;\n    usd[bestk] = true;\n    curp = embs[bestk].seq[4];\n  }\n  auto order1 = do_2opt(order_nn, initp, embs, M);\n  vector<pii> path1;\n  for (int idx : order1) {\n    for (auto pp : embs[idx].seq) path1.push_back(pp);\n  }\n\n  // Spatial order\n  vector<int> order_spa(M);\n  iota(order_spa.begin(), order_spa.end(), 0);\n  sort(order_spa.begin(), order_spa.end(), [&](int aa, int bb) {\n    int cia = (embs[aa].seq[0].first + embs[aa].seq[4].first) / 2;\n    int cja = (embs[aa].seq[0].second + embs[aa].seq[4].second) / 2;\n    int cib = (embs[bb].seq[0].first + embs[bb].seq[4].first) / 2;\n    int cjb = (embs[bb].seq[0].second + embs[bb].seq[4].second) / 2;\n    return cia * N + cja < cib * N + cjb;\n  });\n  auto order3 = do_2opt(order_spa, initp, embs, M);\n  vector<pii> path3;\n  for (int idx : order3) {\n    for (auto pp : embs[idx].seq) path3.push_back(pp);\n  }\n\n  // Close to init\n  vector<int> order_close(M);\n  iota(order_close.begin(), order_close.end(), 0);\n  sort(order_close.begin(), order_close.end(), [&](int x, int y) { return dist_init[x] < dist_init[y]; });\n  auto order_close_opt = do_2opt(order_close, initp, embs, M);\n  vector<pii> path_close;\n  for (int idx : order_close_opt) {\n    for (auto pp : embs[idx].seq) path_close.push_back(pp);\n  }\n\n  // SA improved\n  mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n  vector<int> sa_ord = order_nn;  // start from NN\n  int cur_c = compute_inter(sa_ord, initp, embs);\n  int sa_bestc = cur_c;\n  vector<int> sa_bestord = sa_ord;\n  double sa_T = 8000.0;\n  double cooling = 0.9999;\n  int maxit_sa = 80000;\n  uniform_int_distribution<int> uid(0, M - 1);\n  uniform_real_distribution<double> urd(0.0, 1.0);\n  for (int it = 0; it < maxit_sa; ++it) {\n    int ra = uid(rng), rb = uid(rng);\n    if (ra > rb) swap(ra, rb);\n    if (ra == rb) {\n      --it;\n      continue;\n    }\n    vector<int> trial = sa_ord;\n    reverse(trial.begin() + ra, trial.begin() + rb + 1);\n    int trial_c = compute_inter(trial, initp, embs);\n    int delta = trial_c - cur_c;\n    double prob = (delta < 0) ? 1.0 : exp(-double(delta) / sa_T);\n    if (urd(rng) < prob) {\n      sa_ord = move(trial);\n      cur_c = trial_c;\n      if (trial_c < sa_bestc) {\n        sa_bestc = trial_c;\n        sa_bestord = sa_ord;\n      }\n    }\n    sa_T *= cooling;\n    if (sa_T < 5.0) break;\n  }\n  auto order_sa_opt = do_2opt(sa_bestord, initp, embs, M);\n  vector<pii> path_sa;\n  for (int idx : order_sa_opt) {\n    for (auto pp : embs[idx].seq) path_sa.push_back(pp);\n  }\n\n  // Dynamic greedy with overlaps\n  vector<pii> path_dyn;\n  pii curr_pos = initp;\n  string recent_str = \"\";\n  vector<bool> covered_dyn(M, false);\n  int remaining = M;\n  while (remaining > 0 && (int)path_dyn.size() <= 4990) {\n    int best_kk = -1;\n    int best_added_t = INF;\n    int best_oo = -1;\n    int best_aa = -1;\n    int best_overlap = -1;\n    for (int kk = 0; kk < M; ++kk) {\n      if (covered_dyn[kk]) continue;\n      string tk = ts[kk];\n      int temp_best = INF;\n      int temp_o = -1;\n      int temp_a = -1;\n      int temp_max_ol = -1;\n      size_t rlen = recent_str.size();\n      int maxoo = min(4, (int)rlen);\n      for (int oo = 0; oo <= maxoo; ++oo) {\n        bool match = true;\n        for (int j = 0; j < oo; ++j) {\n          if (recent_str[rlen - oo + j] != tk[j]) {\n            match = false;\n            break;\n          }\n        }\n        if (!match) continue;\n        int ll = oo;\n        int rrem = 5 - oo;\n        if (rrem <= 0) continue;\n        int min_conn = INF;\n        int ba_this = -1;\n        int ncand = cand_sz[kk][ll];\n        for (int aid = 0; aid < ncand; ++aid) {\n          const auto& pe = best_partials[kk][ll][aid];\n          if (pe.seq.empty() || pe.movecost >= INF / 2) continue;\n          int cd = manh(curr_pos, pe.seq[0]) + pe.movecost;\n          if (cd < min_conn) {\n            min_conn = cd;\n            ba_this = aid;\n          }\n        }\n        if (min_conn == INF) continue;\n        int addedd = min_conn + rrem;\n        if (addedd < temp_best || (addedd == temp_best && oo > temp_max_ol)) {\n          temp_best = addedd;\n          temp_o = oo;\n          temp_a = ba_this;\n          temp_max_ol = oo;\n        }\n      }\n      if (temp_best < INF / 2) {\n        if (temp_best < best_added_t || (temp_best == best_added_t && temp_o > best_overlap)) {\n          best_added_t = temp_best;\n          best_kk = kk;\n          best_oo = temp_o;\n          best_aa = temp_a;\n          best_overlap = temp_o;\n        }\n      }\n    }\n    if (best_kk == -1) break;\n    int ll = best_oo;\n    const auto& pe = best_partials[best_kk][ll][best_aa];\n    for (auto p : pe.seq) {\n      path_dyn.push_back(p);\n    }\n    string addl = \"\";\n    for (auto p : pe.seq) {\n      addl += grid[p.first][p.second];\n    }\n    recent_str += addl;\n    if (recent_str.size() > 4) {\n      recent_str = recent_str.substr(recent_str.size() - 4);\n    }\n    curr_pos = pe.seq.back();\n    covered_dyn[best_kk] = true;\n    --remaining;\n  }\n  // Append remaining if any\n  if (remaining > 0) {\n    pii cur_rem = curr_pos;\n    vector<bool> usd_rem(M, false);  // reuse covered_dyn false for uncovered\n    for (int st = 0; st < remaining; ++st) {\n      int bestk = -1;\n      int mindd = INF;\n      for (int k = 0; k < M; ++k) {\n        if (covered_dyn[k]) continue;\n        int dd = manh(cur_rem, embs[k].seq[0]);\n        if (dd < mindd || (dd == mindd && k < bestk)) {\n          mindd = dd;\n          bestk = k;\n        }\n      }\n      for (auto p : embs[bestk].seq) path_dyn.push_back(p);\n      covered_dyn[bestk] = true;\n      cur_rem = embs[bestk].seq[4];\n    }\n  }\n\n  // Pick best among all\n  vector<pair<int, const vector<pii>*>> candts = {\n      {compute_T(path1, initp), &path1},\n      {compute_T(path3, initp), &path3},\n      {compute_T(path_close, initp), &path_close},\n      {compute_T(path_sa, initp), &path_sa},\n      {compute_T(path_dyn, initp), &path_dyn}};\n  sort(candts.begin(), candts.end());\n  const vector<pii>& best_path = *candts[0].second;\n  for (auto p : best_path) {\n    cout << p.first << \" \" << p.second << '\\n';\n  }\n}","ahc030":"#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <random>\n#include <chrono>\nusing namespace std;\nusing namespace Eigen;\n\nconst int MAXNN = 400;\nconst int MAXM = 20;\nconst int MAXB = 512;\n\nstruct State {\n    double score;\n    int choice[MAXM];\n};\n\nstruct Placement {\n    int di, dj;\n    double score;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout << fixed << setprecision(10);\n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n    vector<vector<pair<int, int>>> shapes(M);\n    int total_mass = 0;\n    for (int m = 0; m < M; ++m) {\n        int d;\n        cin >> d;\n        shapes[m].resize(d);\n        for (int l = 0; l < d; ++l) {\n            cin >> shapes[m][l].first >> shapes[m][l].second;\n        }\n        total_mass += d;\n    }\n    int NN = N * N;\n    assert(NN <= MAXNN);\n    assert(M <= MAXM);\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    int QQ = 48;\n    int ksize = max(8, NN / 2);\n    double alpha = 1.0 - 2 * eps;\n    vector<double> ys(QQ);\n    vector<int> ks(QQ);\n    MatrixXd A(QQ, NN);\n    A.setZero();\n    vector<vector<int>> subsets(QQ);\n    for (int q = 0; q < QQ; ++q) {\n        vector<int> all_cells(NN);\n        iota(all_cells.begin(), all_cells.end(), 0);\n        shuffle(all_cells.begin(), all_cells.end(), rng);\n        int actual_k = min(ksize, NN);\n        subsets[q].reserve(actual_k);\n        for (int t = 0; t < actual_k; ++t) {\n            subsets[q].push_back(all_cells[t]);\n        }\n        printf(\"q %d\", (int)subsets[q].size());\n        for (int cc : subsets[q]) {\n            printf(\" %d %d\", cc / N, cc % N);\n        }\n        printf(\"\\n\");\n        fflush(stdout);\n        int y;\n        cin >> y;\n        ys[q] = y;\n        ks[q] = subsets[q].size();\n        for (int cc : subsets[q]) {\n            A(q, cc) = 1.0;\n        }\n    }\n    VectorXd sh(QQ);\n    for (int q = 0; q < QQ; ++q) {\n        double bq = eps * ks[q];\n        sh(q) = max(0.0, (ys[q] - bq) / alpha);\n    }\n    ColPivHouseholderQR<MatrixXd> decomp(A);\n    VectorXd vhat_raw = decomp.solve(sh);\n    vector<vector<double>> dens(N, vector<double>(N));\n    for (int c = 0; c < NN; ++c) {\n        int i = c / N, j = c % N;\n        dens[i][j] = max(0.0, vhat_raw(c));\n    }\n    // Smooth twice 5x5 tent\n    for (int pass = 0; pass < 2; ++pass) {\n        vector<vector<double>> newd(N, vector<double>(N));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                double sum = 0.0, wsum = 0.0;\n                for (int di = -2; di <= 2; ++di) {\n                    for (int dj = -2; dj <= 2; ++dj) {\n                        int ni = i + di, nj = j + dj;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                            double w = 1.0 / (1.0 + abs(di) + abs(dj));\n                            sum += w * dens[ni][nj];\n                            wsum += w;\n                        }\n                    }\n                }\n                newd[i][j] = sum / wsum;\n            }\n        }\n        dens = std::move(newd);\n    }\n    // Top placements\n    int LL = 40;\n    vector<vector<Placement>> top_placements(M);\n    for (int m = 0; m < M; ++m) {\n        const auto& shp = shapes[m];\n        int d = shp.size();\n        int hmax = 0, wmax = 0;\n        for (auto [ii, jj] : shp) {\n            hmax = max(hmax, ii + 1);\n            wmax = max(wmax, jj + 1);\n        }\n        int ndi = N - hmax + 1;\n        int ndj = N - wmax + 1;\n        vector<tuple<double, int, int>> cand;\n        cand.reserve((size_t)ndi * ndj);\n        for (int di = 0; di < ndi; ++di) {\n            for (int dj = 0; dj < ndj; ++dj) {\n                double sc = 0.0;\n                for (auto [ri, rj] : shp) {\n                    sc += dens[di + ri][dj + rj];\n                }\n                double avg_sc = sc / d;\n                cand.emplace_back(-avg_sc, di, dj);\n            }\n        }\n        sort(cand.begin(), cand.end());\n        int tk = min(LL, (int)cand.size());\n        top_placements[m].reserve(tk);\n        for (int l = 0; l < tk; ++l) {\n            auto [nsc, di, dj] = cand[l];\n            top_placements[m].push_back({di, dj, -nsc});\n        }\n    }\n    // Order by size desc\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return shapes[a].size() > shapes[b].size();\n    });\n    // Beam search\n    int BB = 256;\n    double lambda = 0.25;\n    int temp_cover[MAXNN];\n    vector<State> current_beam;\n    current_beam.reserve(BB);\n    State init_st;\n    memset(init_st.choice, -1, sizeof(init_st.choice));\n    init_st.score = 0.0;\n    current_beam.push_back(init_st);\n    for (int s = 0; s < M; ++s) {\n        int fld = order[s];\n        vector<State> next_beam;\n        next_beam.reserve(current_beam.size() * (size_t)LL);\n        for (const auto& st : current_beam) {\n            const auto& tpls = top_placements[fld];\n            for (size_t l = 0; l < tpls.size(); ++l) {\n                State nst = st;\n                nst.choice[fld] = (int)l;\n                memset(temp_cover, 0, (size_t)NN * sizeof(int));\n                for (int ff = 0; ff < M; ++ff) {\n                    int cl = nst.choice[ff];\n                    if (cl < 0) continue;\n                    const auto& pl = top_placements[ff][cl];\n                    const auto& shp = shapes[ff];\n                    for (auto p : shp) {\n                        int x = pl.di + p.first;\n                        int y = pl.dj + p.second;\n                        temp_cover[x * N + y]++;\n                    }\n                }\n                double sc = 0.0;\n                for (int x = 0; x < N; ++x) {\n                    for (int y = 0; y < N; ++y) {\n                        int c = x * N + y;\n                        int cv = temp_cover[c];\n                        double vh = dens[x][y];\n                        sc += vh * cv - lambda * cv * (double)cv;\n                    }\n                }\n                nst.score = sc;\n                next_beam.push_back(std::move(nst));\n            }\n        }\n        sort(next_beam.begin(), next_beam.end(), [](const State& aa, const State& bb) {\n            return aa.score > bb.score;\n        });\n        current_beam.clear();\n        current_beam.reserve(BB);\n        int nb = min(BB, (int)next_beam.size());\n        for (int bi = 0; bi < nb; ++bi) {\n            current_beam.push_back(std::move(next_beam[bi]));\n        }\n    }\n    // Best guess\n    const State& best = current_beam[0];\n    set<pair<int, int>> union_set;\n    for (int ff = 0; ff < M; ++ff) {\n        int cl = best.choice[ff];\n        if (cl < 0) continue;\n        const auto& pl = top_placements[ff][cl];\n        const auto& shp = shapes[ff];\n        for (auto p : shp) {\n            union_set.emplace(pl.di + p.first, pl.dj + p.second);\n        }\n    }\n    vector<pair<int, int>> ans(union_set.begin(), union_set.end());\n    printf(\"a %zu\", ans.size());\n    for (auto [i, j] : ans) {\n        printf(\" %d %d\", i, j);\n    }\n    printf(\"\\n\");\n    fflush(stdout);\n    int ver;\n    cin >> ver;\n    if (ver == 1) {\n        return 0;\n    }\n    // Fallback 1: drill candidate cells\n    double fb_thresh = 0.10;\n    double sumhat = 0.0;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) sumhat += dens[i][j];\n    double avg_dens = sumhat / NN;\n    fb_thresh = max(0.10, 0.35 * avg_dens);\n    vector<pair<int, int>> cand;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (dens[i][j] > fb_thresh) {\n                cand.emplace_back(i, j);\n            }\n        }\n    }\n    vector<vector<char>> drilled_grid(N, vector<char>(N, 0));\n    vector<pair<int, int>> true_oil;\n    for (auto [i, j] : cand) {\n        drilled_grid[i][j] = 1;\n        printf(\"q 1 %d %d\\n\", i, j);\n        fflush(stdout);\n        int vv;\n        cin >> vv;\n        if (vv > 0) {\n            true_oil.emplace_back(i, j);\n        }\n    }\n    printf(\"a %zu\", true_oil.size());\n    for (auto [i, j] : true_oil) {\n        printf(\" %d %d\", i, j);\n    }\n    printf(\"\\n\");\n    fflush(stdout);\n    int ver2;\n    cin >> ver2;\n    if (ver2 == 1) {\n        return 0;\n    }\n    // Super fallback: drill remaining\n    vector<pair<int, int>> all_oil = true_oil;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (drilled_grid[i][j]) continue;\n            drilled_grid[i][j] = 1;\n            printf(\"q 1 %d %d\\n\", i, j);\n            fflush(stdout);\n            int vv;\n            cin >> vv;\n            if (vv > 0) {\n                all_oil.emplace_back(i, j);\n            }\n        }\n    }\n    sort(all_oil.begin(), all_oil.end());\n    printf(\"a %zu\", all_oil.size());\n    for (auto [i, j] : all_oil) {\n        printf(\" %d %d\", i, j);\n    }\n    printf(\"\\n\");\n    fflush(stdout);\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  int W, D, N;\n  cin >> W >> D >> N;\n  vector<vector<int>> A(D, vector<int>(N));\n  for (int d = 0; d < D; ++d) {\n    for (int k = 0; k < N; ++k) {\n      cin >> A[d][k];\n    }\n  }\n  vector<vector<ll>> costs(N, vector<ll>(W + 1));\n  for (int k = 0; k < N; ++k) {\n    for (int ww = 0; ww <= W; ++ww) {\n      ll tot = 0;\n      for (int d = 0; d < D; ++d) {\n        ll ar = (ll)W * ww;\n        tot += max(0LL, (ll)A[d][k] - ar);\n      }\n      costs[k][ww] = 100LL * tot;\n    }\n  }\n  const ll INF = 4e18;\n  vector<vector<ll>> dp(N + 1, vector<ll>(W + 1, INF));\n  vector<vector<int>> prevu(N + 1, vector<int>(W + 1, -1));\n  vector<vector<int>> chww(N + 1, vector<int>(W + 1, -1));\n  dp[0][0] = 0;\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j <= W; ++j) {\n      if (dp[i][j] == INF) continue;\n      for (int ww = 1; ww <= W - j; ++ww) {\n        int nj = j + ww;\n        ll ncost = dp[i][j] + costs[i][ww];\n        if (ncost < dp[i + 1][nj]) {\n          dp[i + 1][nj] = ncost;\n          prevu[i + 1][nj] = j;\n          chww[i + 1][nj] = ww;\n        }\n      }\n    }\n  }\n  // Recover\n  vector<int> width(N);\n  int cur_i = N;\n  int cur_j = W;\n  while (cur_i > 0) {\n    int ww = chww[cur_i][cur_j];\n    width[cur_i - 1] = ww;\n    cur_j = prevu[cur_i][cur_j];\n    --cur_i;\n  }\n  // Prefix\n  vector<int> prefix(N + 1, 0);\n  for (int k = 0; k < N; ++k) {\n    prefix[k + 1] = prefix[k] + width[k];\n  }\n  // Output\n  for (int d = 0; d < D; ++d) {\n    for (int k = 0; k < N; ++k) {\n      cout << 0 << ' ' << prefix[k] << ' ' << W << ' ' << prefix[k + 1] << '\\n';\n    }\n  }\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll MOD = 998244353LL;\nconst int TRIALS = 32;\nconst int TOPK = 16;\nconst int SZ = 9;\nconst int STAMPSZ = 20;\nconst int OPSMAX = 81;\nconst int POS = 7; // 0..6\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  srand(time(nullptr));\n  int N, M, K;\n  cin >> N >> M >> K;\n  ll board[SZ][SZ];\n  for (int i = 0; i < SZ; i++)\n    for (int j = 0; j < SZ; j++)\n      cin >> board[i][j];\n  ll stamps[STAMPSZ][3][3];\n  for (int m = 0; m < STAMPSZ; m++)\n    for (int i = 0; i < 3; i++)\n      for (int j = 0; j < 3; j++)\n        cin >> stamps[m][i][j];\n  ll init_score = 0;\n  for (int i = 0; i < SZ; i++)\n    for (int j = 0; j < SZ; j++)\n      init_score += board[i][j];\n  ll best_score = init_score - 1;\n  vector<tuple<int, int, int>> best_ops;\n  for (int trial = 0; trial < TRIALS; trial++) {\n    ll cur[SZ][SZ];\n    memcpy(cur, board, sizeof(board));\n    vector<tuple<int, int, int>> ops;\n    for (int step = 0; step < OPSMAX; step++) {\n      vector<tuple<ll, int, int, int>> cands;\n      cands.reserve(980);\n      ll maxd = LLONG_MIN / 2;\n      for (int m = 0; m < STAMPSZ; m++) {\n        for (int p = 0; p < POS; p++) {\n          for (int q = 0; q < POS; q++) {\n            ll delta = 0;\n            for (int di = 0; di < 3; di++) {\n              for (int dj = 0; dj < 3; dj++) {\n                int x = p + di, y = q + dj;\n                ll s = stamps[m][di][dj];\n                ll r = cur[x][y];\n                ll nr = r + s;\n                if (nr >= MOD) nr -= MOD;\n                delta += nr - r;\n              }\n            }\n            cands.emplace_back(delta, m, p, q);\n            if (delta > maxd) maxd = delta;\n          }\n        }\n      }\n      nth_element(cands.begin(), cands.begin() + min(TOPK, (int)cands.size()), cands.end(),\n                  greater<tuple<ll, int, int, int>>{});\n      int pick = rand() % TOPK;\n      auto [delta, bm, bp, bq] = cands[pick];\n      // apply\n      for (int di = 0; di < 3; di++) {\n        for (int dj = 0; dj < 3; dj++) {\n          int x = bp + di, y = bq + dj;\n          ll s = stamps[bm][di][dj];\n          ll r = cur[x][y];\n          ll nr = r + s;\n          if (nr >= MOD) nr -= MOD;\n          cur[x][y] = nr;\n        }\n      }\n      ops.emplace_back(bm, bp, bq);\n    }\n    ll score = 0;\n    for (int i = 0; i < SZ; i++)\n      for (int j = 0; j < SZ; j++)\n        score += cur[i][j];\n    if (score > best_score) {\n      best_score = score;\n      best_ops = std::move(ops);\n    }\n  }\n  cout << best_ops.size() << '\\n';\n  for (auto [m, p, q] : best_ops) {\n    cout << m << ' ' << p << ' ' << q << '\\n';\n  }\n}","ahc033":"","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<string> get_moves(int r1, int c1, int r2, int c2) {\n    vector<string> res;\n    int dr = r2 - r1;\n    int dc = c2 - c1;\n    string vdir = \"\";\n    if (dr > 0) vdir = \"D\";\n    else if (dr < 0) vdir = \"U\";\n    string hdir = \"\";\n    if (dc > 0) hdir = \"R\";\n    else if (dc < 0) hdir = \"L\";\n    for (int i = 0; i < abs(dr); ++i) {\n        res.push_back(vdir);\n    }\n    for (int i = 0; i < abs(dc); ++i) {\n        res.push_back(hdir);\n    }\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    cin >> N;\n    vector<vector<int>> height(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> height[i][j];\n        }\n    }\n    vector<string> ops;\n    int cur_r = 0, cur_c = 0;\n    long long current_load = 0;\n    while (ops.size() < 95000) {\n        // check if done\n        bool is_done = (current_load == 0);\n        if (is_done) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (height[i][j] != 0) {\n                        is_done = false;\n                        goto next;\n                    }\n                }\n            }\n        }\n    next:;\n        if (is_done) break;\n\n        double best_score = 1e100;\n        int best_secondary = -1;\n        int best_r = -1, best_c = -1;\n        if (current_load > 0) {\n            // find best sink (closest, tie largest need)\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (height[i][j] < 0) {\n                        double dist = abs(i - cur_r) + abs(j - cur_c);\n                        int camt = -height[i][j];\n                        double cscore = dist;\n                        if (cscore < best_score || (cscore == best_score && camt > best_secondary)) {\n                            best_score = cscore;\n                            best_secondary = camt;\n                            best_r = i;\n                            best_c = j;\n                        }\n                    }\n                }\n            }\n        } else {\n            // find best source (min est_cost = D*100 + min_ds*(100 + amt), tie largest amt)\n            for (int sr = 0; sr < N; ++sr) {\n                for (int sc = 0; sc < N; ++sc) {\n                    if (height[sr][sc] > 0) {\n                        int camt = height[sr][sc];\n                        double D = abs(sr - cur_r) + abs(sc - cur_c);\n                        double min_ds = 1e9;\n                        int sink_sec = -1;\n                        for (int tr = 0; tr < N; ++tr) {\n                            for (int tc = 0; tc < N; ++tc) {\n                                if (height[tr][tc] < 0) {\n                                    double ds = abs(tr - sr) + abs(tc - sc);\n                                    int ssamt = -height[tr][tc];\n                                    if (ds < min_ds || (ds == min_ds && ssamt > sink_sec)) {\n                                        min_ds = ds;\n                                        sink_sec = ssamt;\n                                    }\n                                }\n                            }\n                        }\n                        double cscore = D * 100.0 + min_ds * (100.0 + (double)camt);\n                        if (cscore < best_score || (cscore == best_score && camt > best_secondary)) {\n                            best_score = cscore;\n                            best_secondary = camt;\n                            best_r = sr;\n                            best_c = sc;\n                        }\n                    }\n                }\n            }\n        }\n        if (best_r == -1) break;\n\n        // move\n        auto path = get_moves(cur_r, cur_c, best_r, best_c);\n        for (auto& p : path) {\n            ops.push_back(p);\n        }\n        cur_r = best_r;\n        cur_c = best_c;\n\n        // act\n        if (current_load > 0) {\n            // unload\n            long long need = -(long long)height[best_r][best_c];\n            long long d = min(current_load, need);\n            ops.push_back(\"-\" + to_string(d));\n            height[best_r][best_c] += (int)d;\n            current_load -= d;\n        } else {\n            // load\n            long long d = height[best_r][best_c];\n            ops.push_back(\"+\" + to_string(d));\n            height[best_r][best_c] -= (int)d;\n            current_load += d;\n        }\n    }\n    for (auto& s : ops) {\n        cout << s << '\\n';\n    }\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int N, M, T;\n    cin >> N >> M >> T;\n    const int P = N * N; // 36\n    const int S = 2 * N * (N - 1); // 60\n    vector<vector<int>> cur(S, vector<int>(M));\n    for (int k = 0; k < S; k++) {\n        for (int j = 0; j < M; j++) {\n            cin >> cur[k][j];\n        }\n    }\n\n    auto pid = [N](int i, int j) { return i * N + j; };\n\n    // adjacency list\n    vector<vector<int>> adj(P);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N - 1; j++) {\n            int u = pid(i, j), v = pid(i, j + 1);\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n    }\n    for (int i = 0; i < N - 1; i++) {\n        for (int j = 0; j < N; j++) {\n            int u = pid(i, j), v = pid(i + 1, j);\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n    }\n\n    // edges\n    vector<pair<int, int>> edges;\n    for (int u = 0; u < P; u++) {\n        for (int v : adj[u]) {\n            if (v > u) edges.emplace_back(u, v);\n        }\n    }\n\n    // degrees & pos_order (high deg first)\n    vector<int> degree(P);\n    for (int i = 0; i < P; i++) degree[i] = adj[i].size();\n    vector<int> pos_order(P);\n    iota(pos_order.begin(), pos_order.end(), 0);\n    sort(pos_order.begin(), pos_order.end(), [&](int pa, int pb) {\n        return degree[pa] > degree[pb] || (degree[pa] == degree[pb] && pa < pb);\n    });\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> uni_pos(0, P - 1);\n    uniform_real_distribution<double> uni_prob(0.0, 1.0);\n\n    for (int t = 0; t < T; t++) {\n        // values\n        vector<long long> val(S, 0);\n        for (int k = 0; k < S; k++) {\n            for (int j = 0; j < M; j++) val[k] += cur[k][j];\n        }\n\n        // global sort by val desc\n        vector<int> idx(S);\n        iota(idx.begin(), idx.end(), 0);\n        sort(idx.begin(), idx.end(), [&](int a, int b) {\n            return val[a] > val[b] || (val[a] == val[b] && a < b);\n        });\n\n        // elites: dim maxes\n        set<int> elites_set;\n        for (int l = 0; l < M; l++) {\n            int best = -1, mx = -1;\n            for (int k = 0; k < S; k++) {\n                if (cur[k][l] > mx) {\n                    mx = cur[k][l];\n                    best = k;\n                }\n            }\n            if (best != -1) elites_set.insert(best);\n        }\n        int num_elite = elites_set.size();\n        if (t >= 6) num_elite = min(8, num_elite); // late: fewer elites\n\n        // complementary score for non-elites\n        vector<double> comp_score(S, 0.0);\n        if (!elites_set.empty()) {\n            double inv_ne = 1.0 / num_elite;\n            for (int k = 0; k < S; k++) {\n                if (elites_set.count(k)) continue;\n                long long sum_sup = 0;\n                for (int e : elites_set) {\n                    for (int m = 0; m < M; m++) {\n                        sum_sup += max((long long)cur[k][m], (long long)cur[e][m]);\n                    }\n                }\n                comp_score[k] = sum_sup * inv_ne;\n            }\n        }\n\n        // candidates: top comp_score non-elites (or val if no elites)\n        vector<int> candidates;\n        vector<int> non_elite_idx;\n        for (int ii = 0; ii < S; ii++) {\n            int k = idx[ii];\n            if (elites_set.count(k) == 0) non_elite_idx.push_back(k);\n        }\n        sort(non_elite_idx.begin(), non_elite_idx.end(), [&](int a, int b) {\n            if (comp_score[a] != comp_score[b]) return comp_score[a] > comp_score[b];\n            return val[a] > val[b] || (val[a] == val[b] && a < b);\n        });\n        int need_more = P - num_elite;\n        for (int i = 0; i < need_more && i < (int)non_elite_idx.size(); i++) {\n            candidates.push_back(non_elite_idx[i]);\n        }\n\n        // top36\n        vector<int> top36(elites_set.begin(), elites_set.end());\n        top36.insert(top36.end(), candidates.begin(), candidates.end());\n\n        // locals\n        vector<vector<int>> loc(P, vector<int>(M));\n        vector<long long> local_val(P);\n        for (int li = 0; li < P; li++) {\n            int gi = top36[li];\n            local_val[li] = val[gi];\n            for (int m = 0; m < M; m++) loc[li][m] = cur[gi][m];\n        }\n\n        // sort locals by val desc\n        vector<int> local_order(P);\n        iota(local_order.begin(), local_order.end(), 0);\n        sort(local_order.begin(), local_order.end(), [&](int a, int b) {\n            return local_val[a] > local_val[b] || (local_val[a] == local_val[b] && a < b);\n        });\n\n        // supersum lambda\n        auto supersum = [&](int lid1, int lid2) -> long long {\n            long long s = 0;\n            for (int m = 0; m < M; m++) {\n                s += max((long long)loc[lid1][m], (long long)loc[lid2][m]);\n            }\n            return s;\n        };\n\n        // Multi-start SA\n        vector<int> best_assignment(P);\n        long long best_score = LLONG_MIN / 2;\n        const int NUM_STARTS = 2;\n        const int MAX_ITER = 400000;\n        const double TEMP_START = 15000.0;\n        const double COOL_RATE = 0.9997;\n\n        for (int st = 0; st < NUM_STARTS; st++) {\n            // init assignment: top locals to high-deg pos\n            vector<int> assignment(P);\n            for (int pp = 0; pp < P; pp++) {\n                assignment[pos_order[pp]] = local_order[pp];\n            }\n\n            // init score\n            long long score = 0;\n            for (auto [u, v] : edges) {\n                score += supersum(assignment[u], assignment[v]);\n            }\n\n            // SA\n            double cur_temp = TEMP_START;\n            for (int iter = 0; iter < MAX_ITER; iter++) {\n                int a = uni_pos(rng), b = uni_pos(rng);\n                if (a == b) continue;\n\n                int sidA = assignment[a], sidB = assignment[b];\n                long long delta = 0;\n\n                for (int n : adj[a]) {\n                    if (n == b) continue;\n                    delta += supersum(assignment[n], sidB) - supersum(assignment[n], sidA);\n                }\n                for (int n : adj[b]) {\n                    if (n == a) continue;\n                    delta += supersum(assignment[n], sidA) - supersum(assignment[n], sidB);\n                }\n\n                bool accept = delta >= 0;\n                if (!accept) {\n                    double p = exp((double)delta / cur_temp);\n                    accept = uni_prob(rng) < p;\n                }\n                if (accept) {\n                    swap(assignment[a], assignment[b]);\n                    score += delta;\n                }\n\n                cur_temp *= COOL_RATE;\n                if (cur_temp < 1.0) break;\n            }\n\n            if (score > best_score) {\n                best_score = score;\n                best_assignment = assignment;\n            }\n        }\n\n        // build grid\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                int pos = pid(i, j);\n                int lid = best_assignment[pos];\n                grid[i][j] = top36[lid];\n            }\n        }\n\n        // output\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << grid[i][j];\n                if (j + 1 < N) cout << ' ';\n                else cout << '\\n';\n            }\n        }\n        cout.flush();\n\n        // read new\n        for (int k = 0; k < S; k++) {\n            for (int m = 0; m < M; m++) {\n                cin >> cur[k][m];\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, V;\n  cin >> N >> M >> V;\n  vector<string> S(N), T(N);\n  for (auto& str : S) cin >> str;\n  for (auto& str : T) cin >> str;\n  vector<vector<int>> has(N, vector<int>(N, 0));\n  vector<vector<int>> targ(N, vector<int>(N, 0));\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      has[i][j] = S[i][j] - '0';\n      targ[i][j] = T[i][j] - '0';\n    }\n  }\n\n  // Compute center for initial position\n  int sumx = 0, sumy = 0, cnt = 0;\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      if (has[i][j]) {\n        sumx += i;\n        sumy += j;\n        ++cnt;\n      }\n    }\n  }\n  int rx = cnt ? sumx / cnt : N / 2;\n  int ry = cnt ? sumy / cnt : N / 2;\n  rx = max(0, min(N - 1, rx));\n  ry = max(0, min(N - 1, ry));\n\n  // Design simple tree: V' = 2, length N/2\n  int Vp = 2;\n  int L = max(1, N / 2);\n  cout << Vp << '\\n';\n  cout << 0 << \" \" << L << '\\n';\n  cout << rx << \" \" << ry << '\\n';\n\n  // Simulation state\n  vector<pair<int, int>> extras, holes;\n  bool dirty = true;\n  auto rebuild = [&]() {\n    extras.clear();\n    holes.clear();\n    for (int i = 0; i < N; ++i) {\n      for (int j = 0; j < N; ++j) {\n        if (has[i][j] && !targ[i][j]) extras.emplace_back(i, j);\n        if (!has[i][j] && targ[i][j]) holes.emplace_back(i, j);\n      }\n    }\n    dirty = false;\n  };\n\n  // Directions: 0=R,1=D,2=L,3=U\n  int dir_dx[4] = {0, 1, 0, -1};\n  int dir_dy[4] = {1, 0, -1, 0};\n\n  // Current state\n  int cur_rx = rx, cur_ry = ry;\n  int edir = 0;\n  bool holding = false;\n\n  vector<string> ops;\n  const int MAX_TURNS = 100000;\n  while (ops.size() < MAX_TURNS) {\n    if (dirty) rebuild();\n\n    // Current finger position\n    int fx = cur_rx + L * dir_dx[edir];\n    int fy = cur_ry + L * dir_dy[edir];\n\n    // Find best_target pos\n    pair<int, int> best_target{-1, -1};\n    int best_dist = INT_MAX;\n    int best_lex = INT_MAX;\n    bool target_empty = false;\n    if (holding) {\n      if (holes.empty()) {\n        target_empty = true;\n      } else {\n        for (auto p : holes) {\n          int i = p.first, j = p.second;\n          int d = abs(fx - i) + abs(fy - j);\n          int lex = i * N + j;\n          if (d < best_dist || (d == best_dist && lex < best_lex)) {\n            best_dist = d;\n            best_lex = lex;\n            best_target = p;\n          }\n        }\n      }\n    } else {\n      if (extras.empty()) {\n        target_empty = true;\n      } else {\n        for (auto p : extras) {\n          int i = p.first, j = p.second;\n          int d = abs(fx - i) + abs(fy - j);\n          int lex = i * N + j;\n          if (d < best_dist || (d == best_dist && lex < best_lex)) {\n            best_dist = d;\n            best_lex = lex;\n            best_target = p;\n          }\n        }\n      }\n    }\n    if (target_empty) {\n      best_target = {fx, fy};\n      best_dist = 0;\n    }\n\n    // Lambda for ndist after action\n    auto get_ndist = [&](int px, int py, bool hld) -> int {\n      if (!(0 <= px && px < N && 0 <= py && py < N)) return 999;\n      auto& lst = hld ? holes : extras;\n      if (lst.empty()) return 0;\n      int md = INT_MAX;\n      for (auto p : lst) {\n        md = min(md, abs(px - p.first) + abs(py - p.second));\n      }\n      return md;\n    };\n\n    // Try all actions\n    char best_mv = '.', best_rt = '.', best_pk = '.';\n    int best_score = INT_MIN;\n    string mv_opts = \".UDLR\";\n    string rt_opts = \".LR\";\n    string pk_opts = \".P\";\n    for (char mv : mv_opts) {\n      int nrx = cur_rx, nry = cur_ry;\n      int ddx = 0, ddy = 0;\n      if (mv == 'U') {\n        ddx = -1;\n      } else if (mv == 'D') {\n        ddx = 1;\n      } else if (mv == 'L') {\n        ddy = -1;\n      } else if (mv == 'R') {\n        ddy = 1;\n      }\n      nrx += ddx;\n      nry += ddy;\n      if (nrx < 0 || nrx >= N || nry < 0 || nry >= N) continue;\n\n      for (char rt : rt_opts) {\n        int rdelta = 0;\n        if (rt == 'R') rdelta = 1;\n        else if (rt == 'L') rdelta = 3;\n        int nedir = (edir + rdelta) % 4;\n\n        int nfx = nrx + L * dir_dx[nedir];\n        int nfy = nry + L * dir_dy[nedir];\n        bool inb = (0 <= nfx && nfx < N && 0 <= nfy && nfy < N);\n\n        for (char pk : pk_opts) {\n          // Compute new_holding\n          bool new_holding = holding;\n          bool act_success = false;\n          bool good_act = false;\n          if (pk == 'P' && inb) {\n            if (holding) {\n              // try place\n              if (has[nfx][nfy] == 0) {\n                act_success = true;\n                new_holding = false;\n                if (targ[nfx][nfy]) good_act = true;\n              }\n            } else {\n              // try grab\n              if (has[nfx][nfy] == 1) {\n                act_success = true;\n                new_holding = true;\n                if (!targ[nfx][nfy]) good_act = true;\n              }\n            }\n          }\n\n          // ndist\n          int ndist = get_ndist(nfx, nfy, new_holding);\n\n          // target dist\n          int tdist = (best_target.first < 0 ? 0 : abs(nfx - best_target.first) + abs(nfy - best_target.second));\n\n          int score = -ndist * 100 - tdist * 5;\n          if (act_success && good_act) score += 50000;\n          else if (act_success) score += 5000;\n          if (inb) score += 100;\n\n          // action cost\n          if (mv != '.') score -= 3;\n          if (rt != '.') score -= 3;\n          if (pk != '.') score -= 1;\n\n          if (score > best_score) {\n            best_score = score;\n            best_mv = mv;\n            best_rt = rt;\n            best_pk = pk;\n          }\n        }\n      }\n    }\n\n    // Output op\n    string op(4, '.');\n    op[0] = best_mv;\n    op[1] = best_rt;\n    op[3] = best_pk;\n    cout << op << '\\n';\n    ops.push_back(op);\n\n    // Apply\n    int ddx = 0, ddy = 0;\n    if (best_mv == 'U') ddx = -1;\n    else if (best_mv == 'D') ddx = 1;\n    else if (best_mv == 'L') ddy = -1;\n    else if (best_mv == 'R') ddy = 1;\n    cur_rx += ddx;\n    cur_ry += ddy;\n\n    int rdelta = 0;\n    if (best_rt == 'R') rdelta = 1;\n    else if (best_rt == 'L') rdelta = 3;\n    edir = (edir + rdelta) % 4;\n\n    int nfx = cur_rx + L * dir_dx[edir];\n    int nfy = cur_ry + L * dir_dy[edir];\n    bool inb = (0 <= nfx && nfx < N && 0 <= nfy && nfy < N);\n    if (best_pk == 'P' && inb) {\n      if (holding) {\n        if (has[nfx][nfy] == 0) {\n          has[nfx][nfy] = 1;\n          holding = false;\n          dirty = true;\n        }\n      } else {\n        if (has[nfx][nfy] == 1) {\n          has[nfx][nfy] = 0;\n          holding = true;\n          dirty = true;\n        }\n      }\n    }\n\n    // Check done\n    if (extras.empty() && !holding) break;\n  }\n\n  return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n};\n\nvector<Point> make_small_rect(const Point& p) {\n    vector<Point> res(4);\n    bool right_ok = (p.x < 100000);\n    bool up_ok = (p.y < 100000);\n    bool left_ok = (p.x > 0);\n    bool down_ok = (p.y > 0);\n\n    int lx = p.x;\n    int rx = right_ok ? p.x + 1 : p.x;\n    if (lx == rx && left_ok) {\n        lx = p.x - 1;\n    }\n    int ly = p.y;\n    int ry = up_ok ? p.y + 1 : p.y;\n    if (ly == ry && down_ok) {\n        ly = p.y - 1;\n    }\n    res[0] = {lx, ly};\n    res[1] = {rx, ly};\n    res[2] = {rx, ry};\n    res[3] = {lx, ry};\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<Point> mack(N);\n    for (auto& p : mack) {\n        cin >> p.x >> p.y;\n    }\n    vector<Point> sard(N);\n    for (auto& p : sard) {\n        cin >> p.x >> p.y;\n    }\n\n    // Initial best: single mackerel\n    int best_profit = 1;\n    int best_min_x = mack[0].x;\n    int best_max_x = mack[0].x;\n    int best_min_y = mack[0].y;\n    int best_max_y = mack[0].y;\n\n    // Global BB of all mackerels\n    int gminx = INT_MAX, gmaxx = INT_MIN, gmin_y = INT_MAX, gmax_y = INT_MIN;\n    for (const auto& p : mack) {\n        gminx = min(gminx, p.x);\n        gmaxx = max(gmaxx, p.x);\n        gmin_y = min(gmin_y, p.y);\n        gmax_y = max(gmax_y, p.y);\n    }\n    int g_b = 0;\n    for (const auto& s : sard) {\n        if (gminx <= s.x && s.x <= gmaxx && gmin_y <= s.y && s.y <= gmax_y) g_b++;\n    }\n    int g_prof = N - g_b;\n    if (g_prof > best_profit && gmaxx > gminx && gmax_y > gmin_y) {\n        best_profit = g_prof;\n        best_min_x = gminx;\n        best_max_x = gmaxx;\n        best_min_y = gmin_y;\n        best_max_y = gmax_y;\n    }\n\n    // Thresholds for strips\n    vector<int> thresholds = {100, 200, 500, 1000, 2000, 3000, 4000, 5000, 6000, 8000, 10000, 12000, 15000, 20000, 30000, 40000};\n\n    auto update_best = [&](int prof, int mx1, int mx2, int my1, int my2) {\n        if (prof > best_profit && mx2 > mx1 && my2 > my1) {\n            best_profit = prof;\n            best_min_x = mx1;\n            best_max_x = mx2;\n            best_min_y = my1;\n            best_max_y = my2;\n        }\n    };\n\n    // X-sorted strips\n    {\n        auto mack_sort = mack;\n        sort(mack_sort.begin(), mack_sort.end());\n        for (int th : thresholds) {\n            int ii = 0;\n            while (ii < N) {\n                int jj = ii;\n                while (jj + 1 < N && mack_sort[jj + 1].x - mack_sort[jj].x <= th) ++jj;\n                int aa = jj - ii + 1;\n                if (aa >= 1) {\n                    int mx1 = mack_sort[ii].x;\n                    int mx2 = mack_sort[jj].x;\n                    int my1 = INT_MAX, my2 = INT_MIN;\n                    for (int k = ii; k <= jj; ++k) {\n                        my1 = min(my1, mack_sort[k].y);\n                        my2 = max(my2, mack_sort[k].y);\n                    }\n                    int bb_cnt = 0;\n                    for (const auto& s : sard) {\n                        if (mx1 <= s.x && s.x <= mx2 && my1 <= s.y && s.y <= my2) ++bb_cnt;\n                    }\n                    int prof = aa - bb_cnt;\n                    update_best(prof, mx1, mx2, my1, my2);\n                }\n                ii = jj + 1;\n            }\n        }\n    }\n\n    // Y-sorted strips\n    {\n        auto mack_sort = mack;\n        auto comp_y = [](const Point& a, const Point& b) {\n            return a.y < b.y || (a.y == b.y && a.x < b.x);\n        };\n        sort(mack_sort.begin(), mack_sort.end(), comp_y);\n        for (int th : thresholds) {\n            int ii = 0;\n            while (ii < N) {\n                int jj = ii;\n                while (jj + 1 < N && mack_sort[jj + 1].y - mack_sort[jj].y <= th) ++jj;\n                int aa = jj - ii + 1;\n                if (aa >= 1) {\n                    int my1 = mack_sort[ii].y;\n                    int my2 = mack_sort[jj].y;\n                    int mx1 = INT_MAX, mx2 = INT_MIN;\n                    for (int k = ii; k <= jj; ++k) {\n                        mx1 = min(mx1, mack_sort[k].x);\n                        mx2 = max(mx2, mack_sort[k].x);\n                    }\n                    int bb_cnt = 0;\n                    for (const auto& s : sard) {\n                        if (mx1 <= s.x && s.x <= mx2 && my1 <= s.y && s.y <= my2) ++bb_cnt;\n                    }\n                    int prof = aa - bb_cnt;\n                    update_best(prof, mx1, mx2, my1, my2);\n                }\n                ii = jj + 1;\n            }\n        }\n    }\n\n    // Advanced X-windows\n    {\n        auto mxsrt = mack;\n        sort(mxsrt.begin(), mxsrt.end());\n        auto sxsrt = sard;\n        sort(sxsrt.begin(), sxsrt.end());\n        for (int i = 0; i < N; ++i) {\n            int cminy = INT_MAX;\n            int cmaxy = INT_MIN;\n            for (int j = i; j < N; ++j) {\n                cminy = min(cminy, mxsrt[j].y);\n                cmaxy = max(cmaxy, mxsrt[j].y);\n                int xl = mxsrt[i].x;\n                int xr = mxsrt[j].x;\n                int aa = j - i + 1;\n                if (aa > 450) break;\n\n                // Count sards in [xl,xr] x [cminy,cmaxy]\n                auto it1 = lower_bound(sxsrt.begin(), sxsrt.end(), Point{xl, INT_MIN});\n                auto it2 = upper_bound(it1, sxsrt.end(), Point{xr, INT_MAX});\n                int p = it1 - sxsrt.begin();\n                int q = (it2 - sxsrt.begin()) - 1;\n                int bb = 0;\n                for (int k = p; k <= q && k < N; ++k) {\n                    int sy = sxsrt[k].y;\n                    if (sy >= cminy && sy <= cmaxy) ++bb;\n                }\n                int prof = aa - bb;\n                update_best(prof, xl, xr, cminy, cmaxy);\n            }\n        }\n    }\n\n    // Advanced Y-windows\n    {\n        auto comp_y = [](const Point& a, const Point& b) {\n            return a.y < b.y || (a.y == b.y && a.x < b.x);\n        };\n        auto mysrt = mack;\n        sort(mysrt.begin(), mysrt.end(), comp_y);\n        auto sysrt = sard;\n        sort(sysrt.begin(), sysrt.end(), comp_y);\n        for (int i = 0; i < N; ++i) {\n            int cminx = INT_MAX;\n            int cmaxx = INT_MIN;\n            for (int j = i; j < N; ++j) {\n                cminx = min(cminx, mysrt[j].x);\n                cmaxx = max(cmaxx, mysrt[j].x);\n                int yl = mysrt[i].y;\n                int yr = mysrt[j].y;\n                int aa = j - i + 1;\n                if (aa > 450) break;\n\n                // Count sards in [cminx,cmaxx] x [yl,yr]\n                Point key_low{INT_MIN, yl};\n                auto it1 = lower_bound(sysrt.begin(), sysrt.end(), key_low, comp_y);\n                Point key_up{INT_MAX, yr};\n                auto it2 = upper_bound(it1, sysrt.end(), key_up, comp_y);\n                int p = it1 - sysrt.begin();\n                int q = (it2 - sysrt.begin()) - 1;\n                int bb = 0;\n                for (int k = p; k <= q && k < N; ++k) {\n                    int sx = sysrt[k].x;\n                    if (sx >= cminx && sx <= cmaxx) ++bb;\n                }\n                int prof = aa - bb;\n                update_best(prof, cminx, cmaxx, yl, yr);\n            }\n        }\n    }\n\n    // Fallback if degenerate\n    if (best_max_x == best_min_x || best_max_y == best_min_y) {\n        vector<Point> small = make_small_rect(mack[0]);\n        best_min_x = INT_MAX;\n        best_max_x = INT_MIN;\n        best_min_y = INT_MAX;\n        best_max_y = INT_MIN;\n        for (auto& pt : small) {\n            best_min_x = min(best_min_x, pt.x);\n            best_max_x = max(best_max_x, pt.x);\n            best_min_y = min(best_min_y, pt.y);\n            best_max_y = max(best_max_y, pt.y);\n        }\n        best_profit = 1;\n    }\n\n    // Output the rectangle\n    cout << 4 << '\\n';\n    cout << best_min_x << \" \" << best_min_y << '\\n';\n    cout << best_max_x << \" \" << best_min_y << '\\n';\n    cout << best_max_x << \" \" << best_max_y << '\\n';\n    cout << best_min_x << \" \" << best_max_y << '\\n';\n\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Rect {\n    ll xl, xr, yt, yb;\n};\n\nstruct State {\n    vector<Rect> pos;\n    vector<array<int, 4>> placed_seq;\n    int next_id;\n    ll cur_maxw, cur_maxh, penalty;\n};\n\nll get_score(const State& s) {\n    return s.cur_maxw + s.cur_maxh + s.penalty;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int N, T;\n    ll sigma;\n    cin >> N >> T >> sigma;\n    vector<ll> est_w(N), est_h(N);\n    for (int i = 0; i < N; i++) {\n        cin >> est_w[i] >> est_h[i];\n    }\n\n    const int BEAM_SIZE = 30;\n    vector<State> beam(1);\n    beam[0].pos.assign(N, Rect{-1, -1, -1, -1});\n    beam[0].placed_seq.clear();\n    beam[0].next_id = 0;\n    beam[0].cur_maxw = 0;\n    beam[0].cur_maxh = 0;\n    beam[0].penalty = 0;\n\n    for (int step = 0; step < N; step++) {\n        vector<State> next_beam;\n        next_beam.reserve(20000);\n        for (const auto& st : beam) {\n            int nid = st.next_id;\n            if (nid == N) continue;\n\n            // Skip option\n            {\n                State news = st;\n                news.penalty += est_w[nid] + est_h[nid];\n                news.next_id++;\n                next_beam.push_back(news);\n            }\n\n            // Place options\n            vector<int> poss_b;\n            poss_b.reserve(N);\n            poss_b.push_back(-1);\n            for (int j = 0; j < nid; j++) {\n                if (st.pos[j].xl >= 0) {\n                    poss_b.push_back(j);\n                }\n            }\n            for (int rot = 0; rot < 2; rot++) {\n                ll ww = (rot ? est_h[nid] : est_w[nid]);\n                ll hh = (rot ? est_w[nid] : est_h[nid]);\n                for (int dd = 0; dd < 2; dd++) {\n                    for (int ibb : poss_b) {\n                        int bb = ibb;\n                        ll xl_, xr_, yt_, yb_;\n                        if (dd == 0) {  // U\n                            xl_ = (bb == -1 ? 0LL : st.pos[bb].xr);\n                            xr_ = xl_ + ww;\n                            yt_ = 0;\n                            for (int j = 0; j < nid; j++) {\n                                if (st.pos[j].xl < 0) continue;\n                                ll lx = max(st.pos[j].xl, xl_);\n                                ll rx = min(st.pos[j].xr, xr_);\n                                if (lx < rx) {\n                                    yt_ = max(yt_, st.pos[j].yb);\n                                }\n                            }\n                            yb_ = yt_ + hh;\n                        } else {  // L\n                            yt_ = (bb == -1 ? 0LL : st.pos[bb].yb);\n                            yb_ = yt_ + hh;\n                            xl_ = 0;\n                            for (int j = 0; j < nid; j++) {\n                                if (st.pos[j].xl < 0) continue;\n                                ll ty = max(st.pos[j].yt, yt_);\n                                ll by_ = min(st.pos[j].yb, yb_);\n                                if (ty < by_) {\n                                    xl_ = max(xl_, st.pos[j].xr);\n                                }\n                            }\n                            xr_ = xl_ + ww;\n                        }\n                        State news = st;\n                        news.pos[nid] = {xl_, xr_, yt_, yb_};\n                        news.next_id++;\n                        news.cur_maxw = max(st.cur_maxw, xr_);\n                        news.cur_maxh = max(st.cur_maxh, yb_);\n                        news.placed_seq.push_back({nid, rot, dd, bb});\n                        next_beam.push_back(news);\n                    }\n                }\n            }\n        }\n        // Sort by score ascending\n        sort(next_beam.begin(), next_beam.end(), [](const State& a, const State& b) {\n            return get_score(a) < get_score(b);\n        });\n        // Keep top BEAM_SIZE\n        beam.clear();\n        beam.reserve(BEAM_SIZE);\n        int keep_cnt = min(BEAM_SIZE, (int)next_beam.size());\n        for (int k = 0; k < keep_cnt; k++) {\n            beam.push_back(std::move(next_beam[k]));\n        }\n    }\n\n    // Best config\n    State best_st = beam[0];\n    auto& config = best_st.placed_seq;\n    int nn = config.size();\n\n    // Now repeat for T turns\n    for (int t = 0; t < T; t++) {\n        cout << nn << '\\n';\n        for (const auto& arr : config) {\n            cout << arr[0] << ' ' << arr[1] << ' ' << (arr[2] == 0 ? \"U\" : \"L\") << ' ' << arr[3] << '\\n';\n        }\n        cout.flush();\n        ll Wp, Hp;\n        cin >> Wp >> Hp;\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  int N, M, H;\n  cin >> N >> M >> H;\n  vector<int> A(N);\n  for (int &a : A) cin >> a;\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  vector<int> X(N), Y(N);\n  for (int i = 0; i < N; i++) {\n    cin >> X[i] >> Y[i];\n  }\n  const int INFD = 1 << 30;\n  vector<vector<int>> dist(N, vector<int>(N, INFD));\n  for (int s = 0; s < N; s++) {\n    vector<char> vis(N, 0);\n    queue<int> qq;\n    dist[s][s] = 0;\n    vis[s] = 1;\n    qq.push(s);\n    while (!qq.empty()) {\n      int u = qq.front();\n      qq.pop();\n      for (int nei : adj[u]) {\n        if (!vis[nei]) {\n          vis[nei] = 1;\n          dist[s][nei] = dist[s][u] + 1;\n          qq.push(nei);\n        }\n      }\n    }\n  }\n  vector<vector<int>> covers(N);\n  for (int r = 0; r < N; r++) {\n    for (int v = 0; v < N; v++) {\n      if (dist[r][v] <= H) {\n        covers[r].push_back(v);\n      }\n    }\n  }\n  bitset<1000> uncovered;\n  uncovered.set();\n  vector<int> roots;\n  while (uncovered.any()) {\n    ll best_profit = -1;\n    int best_r = -1;\n    int best_a = INT_MAX;\n    for (int r = 0; r < N; r++) {\n      ll prof = 0;\n      for (int v : covers[r]) {\n        if (uncovered.test(v)) {\n          int d = dist[r][v];\n          prof += (ll)A[v] * d;\n        }\n      }\n      if (prof > best_profit || (prof == best_profit && A[r] < best_a)) {\n        best_profit = prof;\n        best_r = r;\n        best_a = A[r];\n      }\n    }\n    assert(best_r != -1);\n    roots.push_back(best_r);\n    for (int v : covers[best_r]) {\n      if (uncovered.test(v)) {\n        uncovered[v] = 0;\n      }\n    }\n  }\n  // Now build forest\n  vector<int> parent(N, -1);\n  vector<int> depth(N, INFD);\n  queue<int> q;\n  for (int r : roots) {\n    if (depth[r] == INFD) {\n      depth[r] = 0;\n      parent[r] = -1;\n      q.push(r);\n    }\n  }\n  while (!q.empty()) {\n    int u = q.front();\n    q.pop();\n    for (int v : adj[u]) {\n      if (depth[v] == INFD) {\n        depth[v] = depth[u] + 1;\n        parent[v] = u;\n        q.push(v);\n      }\n    }\n  }\n  // Output\n  for (int i = 0; i < N; i++) {\n    cout << parent[i];\n    if (i + 1 < N) cout << \" \";\n    else cout << \"\\n\";\n  }\n}","ahc042":"#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<string> board(N);\n    vector<vector<int>> state(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                state[i][j] = 1;\n            }\n        }\n    }\n    \n    // kmax\n    vector<int> row_left_kmax(N), row_right_kmax(N);\n    for (int r = 0; r < N; ++r) {\n        int first_o = N;\n        for (int j = 0; j < N; ++j) if (board[r][j] == 'o') { first_o = j; break; }\n        row_left_kmax[r] = first_o;\n        int last_o = -1;\n        for (int j = N - 1; j >= 0; --j) if (board[r][j] == 'o') { last_o = j; break; }\n        row_right_kmax[r] = N - 1 - last_o;\n    }\n    vector<int> col_up_kmax(N), col_down_kmax(N);\n    for (int c = 0; c < N; ++c) {\n        int first_o = N;\n        for (int i = 0; i < N; ++i) if (board[i][c] == 'o') { first_o = i; break; }\n        col_up_kmax[c] = first_o;\n        int last_o = -1;\n        for (int i = N - 1; i >= 0; --i) if (board[i][c] == 'o') { last_o = i; break; }\n        col_down_kmax[c] = N - 1 - last_o;\n    }\n    \n    using Op = pair<char, int>;\n    vector<Op> best_sol;\n    size_t min_t = SIZE_MAX;\n    \n    // Heuristic 1-2: All-rows / all-cols optimal split cover\n    auto try_global = [&](const vector<vector<int>>& xs, const vector<int>& k_prefix, const vector<int>& k_suffix,\n                          char d_prefix, char d_suffix, char opp_prefix, char opp_suffix) -> vector<Op> {\n        vector<Op> ops;\n        bool feasible = true;\n        for (int ln = 0; ln < N; ++ln) {\n            vector<int> ps = xs[ln];\n            int m = ps.size();\n            if (m == 0) continue;\n            sort(ps.begin(), ps.end());\n            long long best_c = LLONG_MAX / 2;\n            int best_kpre = 0, best_ksuf = 0;\n            // all prefix\n            if (m > 0) {\n                int maxp = ps.back();\n                int kp = maxp + 1;\n                if (kp <= k_prefix[ln]) {\n                    long long c = 2LL * kp;\n                    if (c < best_c) {\n                        best_c = c;\n                        best_kpre = kp;\n                        best_ksuf = 0;\n                    }\n                }\n            }\n            // all suffix\n            if (m > 0) {\n                int minp = ps[0];\n                int ks = N - minp;\n                if (ks <= k_suffix[ln]) {\n                    long long c = 2LL * ks;\n                    if (c < best_c) {\n                        best_c = c;\n                        best_kpre = 0;\n                        best_ksuf = ks;\n                    }\n                }\n            }\n            // splits\n            for (int s = 0; s <= m; ++s) {\n                long long c = 0;\n                int kp = 0, ks = 0;\n                bool ok = true;\n                if (s > 0) {\n                    int maxpl = ps[s - 1];\n                    kp = maxpl + 1;\n                    if (kp > k_prefix[ln]) ok = false;\n                    else c += 2LL * kp;\n                }\n                if (s < m) {\n                    int minpr = ps[s];\n                    ks = N - minpr;\n                    if (ks > k_suffix[ln]) ok = false;\n                    else c += 2LL * ks;\n                }\n                if (ok && c < best_c) {\n                    best_c = c;\n                    best_kpre = kp;\n                    best_ksuf = ks;\n                }\n            }\n            if (best_c >= LLONG_MAX / 2) {\n                feasible = false;\n                break;\n            }\n            // add ops prefix first\n            for (int t = 0; t < best_kpre; ++t) ops.emplace_back(d_prefix, ln);\n            for (int t = 0; t < best_kpre; ++t) ops.emplace_back(opp_prefix, ln);\n            // suffix\n            for (int t = 0; t < best_ksuf; ++t) ops.emplace_back(d_suffix, ln);\n            for (int t = 0; t < best_ksuf; ++t) ops.emplace_back(opp_suffix, ln);\n        }\n        if (feasible) return ops;\n        return {};\n    };\n    \n    // row_xs\n    vector<vector<int>> row_xs(N);\n    for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) if (state[i][j]) row_xs[i].push_back(j);\n    auto row_ops = try_global(row_xs, row_left_kmax, row_right_kmax, 'L', 'R', 'R', 'L');\n    if (!row_ops.empty() && row_ops.size() < min_t) {\n        min_t = row_ops.size();\n        best_sol = row_ops;\n    }\n    \n    // col_xs\n    vector<vector<int>> col_xs(N);\n    for (int j = 0; j < N; ++j) for (int i = 0; i < N; ++i) if (state[i][j]) col_xs[j].push_back(i);\n    auto col_ops = try_global(col_xs, col_up_kmax, col_down_kmax, 'U', 'D', 'D', 'U');\n    if (!col_ops.empty() && col_ops.size() < min_t) {\n        min_t = col_ops.size();\n        best_sol = col_ops;\n    }\n    \n    // Greedy variants\n    for (int var_id = 0; var_id < 4; ++var_id) {\n        auto temp_state = state;\n        vector<Op> ops;\n        int rem_x = 0;\n        for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) rem_x += temp_state[i][j];\n        while (rem_x > 0) {\n            double best_score = -1.0;\n            int best_cnt = 0;\n            int best_kk = N + 1;\n            char best_d = ' ';\n            int best_p = -1;\n            // rows L\n            for (int r = 0; r < N; ++r) {\n                int kmaxx = row_left_kmax[r];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    for (int j = 0; j < kk; ++j) cntt += temp_state[r][j];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'L';\n                        best_p = r;\n                    }\n                }\n            }\n            // rows R\n            for (int r = 0; r < N; ++r) {\n                int kmaxx = row_right_kmax[r];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    int st = N - kk;\n                    for (int j = st; j < N; ++j) cntt += temp_state[r][j];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'R';\n                        best_p = r;\n                    }\n                }\n            }\n            // cols U\n            for (int c = 0; c < N; ++c) {\n                int kmaxx = col_up_kmax[c];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    for (int i = 0; i < kk; ++i) cntt += temp_state[i][c];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'U';\n                        best_p = c;\n                    }\n                }\n            }\n            // cols D\n            for (int c = 0; c < N; ++c) {\n                int kmaxx = col_down_kmax[c];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    int st = N - kk;\n                    for (int i = st; i < N; ++i) cntt += temp_state[i][c];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'D';\n                        best_p = c;\n                    }\n                }\n            }\n            if (best_cnt == 0) break;  // safeguard\n            // apply\n            char dir = best_d;\n            int p = best_p;\n            int kk = best_kk;\n            char opp;\n            if (dir == 'L') opp = 'R';\n            else if (dir == 'R') opp = 'L';\n            else if (dir == 'U') opp = 'D';\n            else opp = 'U';\n            for (int t = 0; t < kk; ++t) ops.emplace_back(dir, p);\n            for (int t = 0; t < kk; ++t) ops.emplace_back(opp, p);\n            // update temp_state\n            if (dir == 'L' || dir == 'R') {\n                int r = p;\n                int st = (dir == 'L' ? 0 : N - kk);\n                for (int pos = st; pos < st + kk; ++pos) {\n                    temp_state[r][pos] = 0;\n                }\n            } else {\n                int c = p;\n                int st = (dir == 'U' ? 0 : N - kk);\n                for (int pos = st; pos < st + kk; ++pos) {\n                    temp_state[pos][c] = 0;\n                }\n            }\n            rem_x -= best_cnt;\n        }\n        size_t this_t = ops.size();\n        if (this_t < min_t) {\n            min_t = this_t;\n            best_sol = move(ops);\n        }\n    }\n    \n    // Output best\n    for (const auto& op : best_sol) {\n        cout << op.first << ' ' << op.second << '\\n';\n    }\n    return 0;\n}","ahc044":"","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing pii = pair<int, int>;\nusing vpii = vector<pii>;\nusing u32 = uint32_t;\nusing tiii = tuple<int, int, int>;  // d, a, b with a < b\n\nu32 hilbert_order(int xx, int yy) {\n  const int n = 16384;\n  int x = max(0, min(n - 1, xx));\n  int y = max(0, min(n - 1, yy));\n  u32 d = 0;\n  u32 s;\n  for (s = n / 2; s > 0; s >>= 1) {\n    u32 rx = (x & s) > 0;\n    u32 ry = (y & s) > 0;\n    d += s * s * ((3 * rx) ^ ry);\n    if (ry == 0) {\n      if (rx == 1) {\n        x = n - 1 - x;\n        y = n - 1 - y;\n      }\n      swap(x, y);\n    }\n  }\n  return d;\n}\n\nvoid get_mst(const vector<int>& C, vpii& mst_edges) {\n  int l = C.size();\n  cout << \"? \" << l;\n  for (int u : C) cout << \" \" << u;\n  cout << endl << flush;\n  mst_edges.resize(l - 1);\n  for (int i = 0; i < l - 1; i++) {\n    int a, b;\n    cin >> a >> b;\n    if (a > b) swap(a, b);\n    mst_edges[i] = {a, b};\n  }\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, Q_max, L, W;\n  cin >> N >> M >> Q_max >> L >> W;\n  vi G(M);\n  for (auto& g : G) cin >> g;\n  vi lx(N), rx(N), ly(N), ry(N);\n  vi cx(N), cy(N);\n  for (int i = 0; i < N; i++) {\n    cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    cx[i] = (lx[i] + rx[i]) / 2;\n    cy[i] = (ly[i] + ry[i]) / 2;\n  }\n  vector<u32> hidx(N);\n  for (int i = 0; i < N; i++) {\n    hidx[i] = hilbert_order(cx[i], cy[i]);\n  }\n  vi order(N);\n  iota(order.begin(), order.end(), 0);\n  auto cmp = [&](int i, int j) { return hidx[i] < hidx[j]; };\n  sort(order.begin(), order.end(), cmp);\n  vi cum(M + 1, 0);\n  for (int i = 1; i <= M; i++) {\n    cum[i] = cum[i - 1] + G[i - 1];\n  }\n  vvi groups(M);\n  for (int m = 0; m < M; m++) {\n    groups[m].assign(order.begin() + cum[m], order.begin() + cum[m + 1]);\n  }\n  auto proxy_dist = [&](int a, int b) -> int {\n    ll dx = cx[a] - cx[b];\n    ll dy = cy[a] - cy[b];\n    ll dd = dx * dx + dy * dy;\n    int res = (int)sqrt((double)dd);\n    while (1LL * (res + 1) * (res + 1) <= dd) ++res;\n    while (1LL * res * res > dd) --res;\n    return res;\n  };\n  vector<vpii> all_trees(M);\n  int queries_used = 0;\n  int step_size = 3;\n  for (int m = 0; m < M; m++) {\n    int g = groups[m].size();\n    if (g < 2) {\n      all_trees[m] = {};\n      continue;\n    }\n    vi C = groups[m];\n    vpii candidates;\n    if (g <= L) {\n      vpii temp;\n      get_mst(C, temp);\n      queries_used++;\n      all_trees[m] = std::move(temp);\n      continue;\n    }\n    // large group\n    int wsz = L;\n    int pos = 0;\n    while (pos + wsz <= g) {\n      vi sub(C.begin() + pos, C.begin() + pos + wsz);\n      vpii temp;\n      get_mst(sub, temp);\n      queries_used++;\n      for (auto e : temp) candidates.push_back(e);\n      pos += step_size;\n    }\n    if (pos < g) {\n      int rem = g - pos;\n      if (rem >= 2) {\n        int lsz = min(wsz, rem);\n        vi sub(C.begin() + pos, C.begin() + pos + lsz);\n        vpii temp;\n        get_mst(sub, temp);\n        queries_used++;\n        for (auto e : temp) candidates.push_back(e);\n      }\n    }\n    // now Kruskal with proxy dist\n    vi local_id(N, -1);\n    for (int loc = 0; loc < g; loc++) {\n      local_id[C[loc]] = loc;\n    }\n    vector<tiii> cand_edges;\n    for (auto [a, b] : candidates) {\n      int dd = proxy_dist(a, b);\n      cand_edges.emplace_back(dd, a, b);\n    }\n    // add consecutive edges\n    for (int i = 0; i < g - 1; i++) {\n      int u = C[i], v = C[i + 1];\n      int uu = min(u, v), vv = max(u, v);\n      int dd = proxy_dist(u, v);\n      cand_edges.emplace_back(dd, uu, vv);\n    }\n    // sort by proxy dist\n    sort(cand_edges.begin(), cand_edges.end());\n    // union-find\n    vi par(g);\n    iota(par.begin(), par.end(), 0);\n    auto find = [&](auto&& self, int x) -> int {\n      return par[x] == x ? x : par[x] = self(self, par[x]);\n    };\n    vpii tree_edges;\n    for (auto [d, aa, bb] : cand_edges) {\n      int la = local_id[aa], lb = local_id[bb];\n      int pa = find(find, la), pb = find(find, lb);\n      if (pa != pb) {\n        par[pa] = pb;\n        tree_edges.emplace_back(aa, bb);\n        if ((int)tree_edges.size() == g - 1) break;\n      }\n    }\n    // fallback if not connected\n    if ((int)tree_edges.size() < g - 1) {\n      tree_edges.clear();\n      for (int i = 0; i < g - 1; i++) {\n        int u = C[i], v = C[i + 1];\n        if (u > v) swap(u, v);\n        tree_edges.emplace_back(u, v);\n      }\n    }\n    all_trees[m] = std::move(tree_edges);\n  }\n  cout << \"!\" << endl;\n  for (int m = 0; m < M; m++) {\n    for (size_t i = 0; i < groups[m].size(); ++i) {\n      if (i > 0) cout << \" \";\n      cout << groups[m][i];\n    }\n    cout << '\\n';\n    for (const auto& e : all_trees[m]) {\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\nconst int INF = 1e9 + 5;\nint dr[4] = {-1, 1, 0, 0};\nint dc[4] = {0, 0, -1, 1};\nchar dirch[4] = {'U', 'D', 'L', 'R'};\n\nvector<pair<char, char>> get_path(int sr, int sc, int tr, int tc, int N) {\n  int NN = N * N;\n  vector<int> dist(NN, INF);\n  vector<int> prevv(NN, -1);\n  vector<char> pactt(NN, 0);\n  vector<char> pdirr(NN, 0);\n  int sid = sr * N + sc;\n  int tid = tr * N + tc;\n  dist[sid] = 0;\n  queue<int> q;\n  q.push(sid);\n  while (!q.empty()) {\n    int id = q.front();\n    q.pop();\n    int cr = id / N;\n    int cc = id % N;\n    // moves\n    for (int d = 0; d < 4; d++) {\n      int nr = cr + dr[d];\n      int nc = cc + dc[d];\n      if (nr >= 0 && nr < N && nc >= 0 && nc < N) {\n        int nid = nr * N + nc;\n        if (dist[nid] == INF) {\n          dist[nid] = dist[id] + 1;\n          prevv[nid] = id;\n          pactt[nid] = 'M';\n          pdirr[nid] = dirch[d];\n          q.push(nid);\n        }\n      }\n    }\n    // slides\n    for (int d = 0; d < 4; d++) {\n      int er = cr;\n      int ec = cc;\n      int ddr = dr[d];\n      int ddc = dc[d];\n      while (true) {\n        int nr = er + ddr;\n        int nc = ec + ddc;\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N) break;\n        er = nr;\n        ec = nc;\n      }\n      int eid = er * N + ec;\n      if (dist[eid] == INF) {\n        dist[eid] = dist[id] + 1;\n        prevv[eid] = id;\n        pactt[eid] = 'S';\n        pdirr[eid] = dirch[d];\n        q.push(eid);\n      }\n    }\n  }\n  // reconstruct\n  vector<pair<char, char>> path;\n  if (dist[tid] == INF) return path;\n  int cur = tid;\n  while (cur != sid) {\n    char a = pactt[cur];\n    char dd = pdirr[cur];\n    path.emplace_back(a, dd);\n    cur = prevv[cur];\n  }\n  reverse(path.begin(), path.end());\n  return path;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M;\n  cin >> N >> M;\n  vector<pair<int, int>> pos(M);\n  for (int i = 0; i < M; i++) {\n    cin >> pos[i].first >> pos[i].second;\n  }\n  int cr = pos[0].first;\n  int cc = pos[0].second;\n  vector<pair<char, char>> total;\n  for (int k = 1; k < M; k++) {\n    auto pth = get_path(cr, cc, pos[k].first, pos[k].second, N);\n    for (auto pr : pth) {\n      total.push_back(pr);\n    }\n    cr = pos[k].first;\n    cc = pos[k].second;\n  }\n  for (auto [a, d] : total) {\n    cout << a << ' ' << d << '\\n';\n  }\n  return 0;\n}"},"8":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing u32 = uint32_t;\nusing A4 = array<int, 4>;\n\ninline bool overlaps_rect(int ax, int ay, int cx, int dy, int bx, int by, int dx, int ey) {\n  return ax < dx && cx > bx && ay < ey && dy > by;\n}\n\nbool overlaps(const vector<A4>& v, int a, int b, int c, int d) {\n  for (const auto& p : v) {\n    if (overlaps_rect(a, b, c, d, p[0], p[1], p[2], p[3])) return true;\n  }\n  return false;\n}\n\nbool overlaps_with(const vector<A4>& occ, const vector<A4>& ext, int a, int b, int c, int d) {\n  return overlaps(occ, a, b, c, d) || overlaps(ext, a, b, c, d);\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n;\n  cin >> n;\n  vector<int> X(n), Y(n), R(n);\n  for (int i = 0; i < n; i++) {\n    cin >> X[i] >> Y[i] >> R[i];\n  }\n  vector<A4> points(n);\n  for (int i = 0; i < n; i++) {\n    points[i] = {X[i], Y[i], X[i] + 1, Y[i] + 1};\n  }\n  vector<int> order(n);\n  iota(order.begin(), order.end(), 0);\n  sort(order.begin(), order.end(), [&](int i, int j) {\n    if (R[i] != R[j]) return R[i] > R[j];\n    return X[i] < X[j];\n  });\n  vector<A4> occupied;\n  vector<A4> solution(n);\n  for (int kk = 0; kk < n; kk++) {\n    int i = order[kk];\n    int xi = X[i], yi = Y[i];\n    ll rri = R[i];\n    vector<A4> extras;\n    for (int jj = kk + 1; jj < n; jj++) {\n      extras.push_back(points[order[jj]]);\n    }\n    int aa = xi, bb = yi, cc = xi + 1, dd = yi + 1;\n    bool min_free = !overlaps_with(occupied, extras, aa, bb, cc, dd);\n    if (min_free) {\n      int cura = xi, curb = yi, curc = xi + 1, curd = yi + 1;\n      const int MAX_ITER = 300;\n      for (int iter = 0; iter < MAX_ITER; iter++) {\n        int d_left = 0;\n        {\n          int lo = 0, hi = cura;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int na = cura - mid;\n            if (na >= 0 && !overlaps_with(occupied, extras, na, curb, curc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_left = lo;\n        }\n        int d_right = 0;\n        {\n          int lo = 0, hi = 10000 - curc;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nc = curc + mid;\n            if (nc <= 10000 && !overlaps_with(occupied, extras, cura, curb, nc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_right = lo;\n        }\n        int d_bot = 0;\n        {\n          int lo = 0, hi = curb;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nb = curb - mid;\n            if (nb >= 0 && !overlaps_with(occupied, extras, cura, nb, curc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_bot = lo;\n        }\n        int d_top = 0;\n        {\n          int lo = 0, hi = 10000 - curd;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nt = curd + mid;\n            if (nt <= 10000 && !overlaps_with(occupied, extras, cura, curb, curc, nt)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_top = lo;\n        }\n        ll h = (ll)(curd - curb);\n        ll w = (ll)(curc - cura);\n        ll gain_l = (ll)d_left * h;\n        ll gain_r = (ll)d_right * h;\n        ll gain_b = (ll)d_bot * w;\n        ll gain_t = (ll)d_top * w;\n        ll maxg = max({gain_l, gain_r, gain_b, gain_t});\n        if (maxg == 0) break;\n        int chdir = -1;\n        if (gain_l == maxg) chdir = 0;\n        else if (gain_r == maxg) chdir = 1;\n        else if (gain_b == maxg) chdir = 2;\n        else chdir = 3;\n        if (chdir == 0) cura -= d_left;\n        else if (chdir == 1) curc += d_right;\n        else if (chdir == 2) curb -= d_bot;\n        else curd += d_top;\n      }\n      int Wma = curc - cura;\n      int Hma = curd - curb;\n      double bestp = -1.0;\n      int best_sq = INT_MAX;\n      int best_ms = INT_MAX;\n      int besw = 1, besh = 1;\n      for (int ww = 1; ww <= Wma; ww++) {\n        double hhd = (double)rri / ww;\n        int hh = (int)round(hhd);\n        for (int dk = -2; dk <= 2; dk++) {\n          int hht = hh + dk;\n          hht = max(1, min(Hma, hht));\n          ll ss = (ll)ww * hht;\n          double ra = min((double)rri, (double)ss) / max((double)rri, (double)ss);\n          double pp = 2 * ra - ra * ra;\n          int sq = abs(ww - hht);\n          int ms = max(ww, hht);\n          if (pp > bestp || (fabs(pp - bestp) < 1e-10 && (sq < best_sq || (sq == best_sq && ms < best_ms)))) {\n            bestp = pp;\n            best_sq = sq;\n            best_ms = ms;\n            besw = ww;\n            besh = hht;\n          }\n        }\n      }\n      double cx = xi + 0.5;\n      double cy = yi + 0.5;\n      double hw = besw / 2.0;\n      double hh_ = besh / 2.0;\n      int a_ideal = (int)round(cx - hw);\n      int a = max(cura, min(a_ideal, curc - besw));\n      int b_ideal = (int)round(cy - hh_);\n      int b = max(curb, min(b_ideal, curd - besh));\n      int c2 = a + besw;\n      int d2 = b + besh;\n      solution[i] = {a, b, c2, d2};\n      occupied.push_back(solution[i]);\n    } else {\n      bool found = false;\n      u32 state = static_cast<u32>(i) * 1103515245u + 12345u;\n      const int MAX_ATT = 30000;\n      for (int att = 0; att < MAX_ATT; att++) {\n        u32 st = state;\n        state = state * 1103515245u + 12345u;\n        int px = static_cast<int>((st >> 16) % 10000u);\n        int py = static_cast<int>(st % 10000u);\n        if (!overlaps(occupied, px, py, px + 1, py + 1)) {\n          solution[i] = {px, py, px + 1, py + 1};\n          occupied.push_back(solution[i]);\n          found = true;\n          break;\n        }\n      }\n      if (!found) {\n        found = false;\n        for (int px = 9999; px >= 0 && !found; px -= 5) {\n          for (int py = 9999; py >= 0 && !found; py -= 5) {\n            if (!overlaps(occupied, px, py, px + 1, py + 1)) {\n              solution[i] = {px, py, px + 1, py + 1};\n              occupied.push_back(solution[i]);\n              found = true;\n              break;\n            }\n          }\n        }\n      }\n      if (!found) {\n        solution[i] = {0, 0, 1, 1};\n        occupied.push_back(solution[i]);\n      }\n    }\n  }\n  for (int i = 0; i < n; i++) {\n    auto& re = solution[i];\n    cout << re[0] << \" \" << re[1] << \" \" << re[2] << \" \" << re[3] << \"\\n\";\n  }\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int si, sj;\n  cin >> si >> sj;\n  vector<vector<int>> T(50, vector<int>(50));\n  int maxt = -1;\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) {\n      cin >> T[i][j];\n      maxt = max(maxt, T[i][j]);\n    }\n  int M = maxt + 1;\n  vector<vector<int>> P(50, vector<int>(50));\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) cin >> P[i][j];\n\n  // Precompute tile_maxp\n  vector<int> tile_maxp(M, 0);\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) {\n      tile_maxp[T[i][j]] = max(tile_maxp[T[i][j]], P[i][j]);\n    }\n\n  // Precompute tile_adj and static_deg\n  vector<unordered_set<int>> adj_set(M);\n  const int dr[] = {-1, 1, 0, 0};\n  const int dc[] = {0, 0, -1, 1};\n  for (int i = 0; i < 50; i++) {\n    for (int j = 0; j < 50; j++) {\n      int t1 = T[i][j];\n      for (int d = 0; d < 4; d++) {\n        int ni = i + dr[d];\n        int nj = j + dc[d];\n        if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n          int t2 = T[ni][nj];\n          if (t1 != t2) {\n            adj_set[t1].insert(t2);\n          }\n        }\n      }\n    }\n  }\n  vector<vector<int>> tile_adj(M);\n  vector<int> static_deg(M);\n  for (int t = 0; t < M; t++) {\n    tile_adj[t].assign(adj_set[t].begin(), adj_set[t].end());\n    static_deg[t] = tile_adj[t].size();\n  }\n\n  const char dirchar[] = {'U', 'D', 'L', 'R'};\n\n  string best_str = \"\";\n  long long best_sc = -1LL;\n  int best_len = 0;\n  const int TRIALS = 262144;\n  const int MAX_TOP = 10;\n  const int PRUNE_STEP = 80;\n  const double PRUNE_FRAC = 0.75;\n\n  mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n  for (int trial = 0; trial < TRIALS; trial++) {\n    vector<int> vis(M, 0);\n    int st = T[si][sj];\n    vis[st] = 1;\n    long long score = P[si][sj];\n    int cr = si, cc = sj;\n    string moves = \"\";\n    int local_mode = trial % 7;\n    while (true) {\n      // Early pruning\n      int curlen = moves.size() + 1;\n      if (best_sc >= 0 && curlen > PRUNE_STEP && \n          score < best_sc * PRUNE_FRAC * curlen / best_len) {\n        break;\n      }\n\n      vector<int> cand_dirs;\n      for (int d = 0; d < 4; d++) {\n        int nr = cr + dr[d];\n        int nc = cc + dc[d];\n        if (nr < 0 || nr >= 50 || nc < 0 || nc >= 50) continue;\n        int nt = T[nr][nc];\n        if (vis[nt]) continue;\n        cand_dirs.push_back(d);\n      }\n      size_t ncand = cand_dirs.size();\n      if (ncand == 0) break;\n\n      int fdir;\n      if (local_mode == 6) {  // Fallback uniform if ncand small, but mode6 below\n        uniform_int_distribution<int> dist(0, ncand - 1);\n        fdir = cand_dirs[dist(rng)];\n      } else {\n        vector<tuple<int, int, int, int>> scored_cands;\n        for (size_t ci = 0; ci < ncand; ci++) {\n          int d = cand_dirs[ci];\n          int nr = cr + dr[d];\n          int nc = cc + dc[d];\n          int nt = T[nr][nc];\n\n          // Dynamic tile out-degree\n          int ddeg = 0;\n          for (int t2 : tile_adj[nt]) {\n            if (!vis[t2]) ddeg++;\n          }\n\n          int pp = P[nr][nc];\n          int bonus = (pp == tile_maxp[nt] ? 50 : 0);\n          int pps = pp + bonus;\n          int sdeg = static_deg[nt];\n\n          int k1, k2, k3;\n          if (local_mode == 0) { // low_sdeg low_ddeg high_pps\n            k1 = sdeg; k2 = ddeg; k3 = -pps;\n          } else if (local_mode == 1) { // low_sdeg high_ddeg high_pps\n            k1 = sdeg; k2 = -ddeg; k3 = -pps;\n          } else if (local_mode == 2) { // high_sdeg low_ddeg high_pps\n            k1 = -sdeg; k2 = ddeg; k3 = -pps;\n          } else if (local_mode == 3) { // low_ddeg low_sdeg high_pps\n            k1 = ddeg; k2 = sdeg; k3 = -pps;\n          } else if (local_mode == 4) { // pure high_pps\n            k1 = 0; k2 = 0; k3 = -pps;\n          } else if (local_mode == 5) { // uniform random\n            uniform_int_distribution<int> dist(0, ncand - 1);\n            fdir = cand_dirs[dist(rng)];\n            goto picked;\n          } else { // local_mode==6: pure low_ddeg low_sdeg high_pps (Warnsdorff)\n            k1 = ddeg; k2 = sdeg; k3 = -pps;\n          }\n          scored_cands.emplace_back(k1, k2, k3, (int)ci);\n        }\n        sort(scored_cands.begin(), scored_cands.end());\n        int nsel = min((int)ncand, MAX_TOP);\n        uniform_int_distribution<int> dist(0, nsel - 1);\n        int pick_ci = dist(rng);\n        auto [_, __, ___, fci] = scored_cands[pick_ci];\n        fdir = cand_dirs[fci];\n      }\n    picked:\n      int nr = cr + dr[fdir];\n      int nc = cc + dc[fdir];\n      moves += dirchar[fdir];\n      int nt = T[nr][nc];\n      vis[nt] = 1;\n      score += P[nr][nc];\n      cr = nr;\n      cc = nc;\n    }\n    int this_len = moves.size() + 1;\n    if (score > best_sc) {\n      best_sc = score;\n      best_len = this_len;\n      best_str = moves;\n    }\n  }\n  cout << best_str << '\\n';\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  const int N = 30;\n  auto nodef = [&](int i, int j) -> int { return i * N + j; };\n  auto geti = [&](int u) -> int { return u / N; };\n  auto getj = [&](int u) -> int { return u % N; };\n  vector<vector<double>> h(N, vector<double>(N - 1, 5000.0));\n  vector<vector<double>> vv(N - 1, vector<double>(N, 5000.0));\n  for (int q = 0; q < 1000; ++q) {\n    int si, sj, ti, tj;\n    cin >> si >> sj >> ti >> tj;\n    int ss = nodef(si, sj);\n    int tt = nodef(ti, tj);\n    vector<double> dist(N * N, 1e18);\n    vector<int> prevv(N * N, -1);\n    dist[ss] = 0.0;\n    priority_queue<pair<double, int>, vector<pair<double, int>>, greater<pair<double, int>>> pq;\n    pq.push({0.0, ss});\n    while (!pq.empty()) {\n      auto [cost, u] = pq.top();\n      pq.pop();\n      if (cost > dist[u]) continue;\n      int i = geti(u), j = getj(u);\n      // right\n      if (j < N - 1) {\n        int v = nodef(i, j + 1);\n        double w = h[i][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // left\n      if (j > 0) {\n        int v = nodef(i, j - 1);\n        double w = h[i][j - 1];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // down\n      if (i < N - 1) {\n        int v = nodef(i + 1, j);\n        double w = vv[i][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n      // up\n      if (i > 0) {\n        int v = nodef(i - 1, j);\n        double w = vv[i - 1][j];\n        double nc = dist[u] + w;\n        if (nc < dist[v]) {\n          dist[v] = nc;\n          prevv[v] = u;\n          pq.push({nc, v});\n        }\n      }\n    }\n    double predicted = dist[tt];\n    // reconstruct path\n    vector<int> path_nodes;\n    for (int cur = tt; cur != ss; cur = prevv[cur]) {\n      path_nodes.push_back(cur);\n      assert(prevv[cur] != -1); // for safety, remove in prod\n    }\n    path_nodes.push_back(ss);\n    reverse(path_nodes.begin(), path_nodes.end());\n    // build path_str\n    string path_str;\n    for (size_t k = 0; k + 1 < path_nodes.size(); ++k) {\n      int u = path_nodes[k], v = path_nodes[k + 1];\n      int ui = geti(u), uj = getj(u), vi = geti(v), vj = getj(v);\n      int di = vi - ui, dj = vj - uj;\n      char ch;\n      if (di == -1 && dj == 0) ch = 'U';\n      else if (di == 1 && dj == 0) ch = 'D';\n      else if (di == 0 && dj == -1) ch = 'L';\n      else if (di == 0 && dj == 1) ch = 'R';\n      else assert(false); // error\n      path_str += ch;\n    }\n    cout << path_str << '\\n';\n    cout.flush();\n    int obs;\n    cin >> obs;\n    // update estimates multiplicatively\n    double factor = (predicted > 1e-9 ? (double)obs / predicted : 1.0);\n    int num_e = path_nodes.size() - 1;\n    for (int k = 0; k < num_e; ++k) {\n      int u = path_nodes[k], v = path_nodes[k + 1];\n      int ui = geti(u), uj = getj(u), vi = geti(v), vj = getj(v);\n      if (ui == vi) {  // horiz\n        int lj = min(uj, vj);\n        h[ui][lj] *= factor;\n        h[ui][lj] = max(200.0, min(20000.0, h[ui][lj]));\n      } else {  // vert\n        int ti_ = min(ui, vi);\n        vv[ti_][uj] *= factor;\n        vv[ti_][uj] = max(200.0, min(20000.0, vv[ti_][uj]));\n      }\n    }\n  }\n  return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nstring SS[805];\nint Lens[805];\nchar grid[20][20];\nchar best_grid[20][20];\nchar temp_grid[20][20];\nchar chars[8] = {'A','B','C','D','E','F','G','H'};\nchar dblr[20][41];\nchar dblc[20][41];\n\nvoid compute_dbl() {\n  for (int r = 0; r < N; ++r) {\n    memcpy(dblr[r], grid[r], N);\n    memcpy(dblr[r] + N, grid[r], N);\n  }\n  for (int c = 0; c < N; ++c) {\n    for (int r = 0; r < N; ++r) dblc[c][r] = grid[r][c];\n    memcpy(dblc[c] + N, dblc[c], N);\n  }\n}\n\nint get_covered() {\n  compute_dbl();\n  int cnt = 0;\n  for (int si = 0; si < M; ++si) {\n    int k = Lens[si];\n    const char* pat = SS[si].c_str();\n    bool ok = false;\n    for (int r = 0; r < N && !ok; ++r) {\n      const char* dbl = dblr[r];\n      for (int st = 0; st < N; ++st) {\n        if (memcmp(dbl + st, pat, k) == 0) { ok = true; break; }\n      }\n    }\n    if (!ok) {\n      for (int c = 0; c < N && !ok; ++c) {\n        const char* dbl = dblc[c];\n        for (int st = 0; st < N; ++st) {\n          if (memcmp(dbl + st, pat, k) == 0) { ok = true; break; }\n        }\n      }\n    }\n    if (ok) ++cnt;\n  }\n  return cnt;\n}\n\nbool get_covered_vec(bool cov[805]) {\n  memset(cov, 0, M);\n  compute_dbl();\n  int cnt = 0;\n  for (int si = 0; si < M; ++si) {\n    int k = Lens[si];\n    const char* pat = SS[si].c_str();\n    bool ok = false;\n    for (int r = 0; r < N && !ok; ++r) {\n      const char* dbl = dblr[r];\n      for (int st = 0; st < N; ++st) {\n        if (memcmp(dbl + st, pat, k) == 0) { ok = true; break; }\n      }\n    }\n    if (!ok) {\n      for (int c = 0; c < N && !ok; ++c) {\n        const char* dbl = dblc[c];\n        for (int st = 0; st < N; ++st) {\n          if (memcmp(dbl + st, pat, k) == 0) { ok = true; break; }\n        }\n      }\n    }\n    cov[si] = ok;\n    if (ok) ++cnt;\n  }\n  return cnt == M;\n}\n\nvoid do_blanking() {\n  vector<pair<int, int>> non_dots;\n  for (int i = 0; i < N; ++i)\n    for (int j = 0; j < N; ++j)\n      if (grid[i][j] != '.') non_dots.emplace_back(i, j);\n  const int num_sweeps = 3;\n  const int max_tries_per_sweep = 200;\n  for (int sw = 0; sw < num_sweeps; ++sw) {\n    random_shuffle(non_dots.begin(), non_dots.end());\n    int tries = 0;\n    for (auto [ri, ci] : non_dots) {\n      if (tries++ >= max_tries_per_sweep) break;\n      char old = grid[ri][ci];\n      grid[ri][ci] = '.';\n      if (get_covered() != M) {\n        grid[ri][ci] = old;\n      }\n    }\n  }\n}\n\nint main() {\n  srand(42);\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cin >> N >> M;\n  for (int i = 0; i < M; ++i) {\n    cin >> SS[i];\n    Lens[i] = SS[i].size();\n  }\n  memset(grid, '.', sizeof(grid));\n  // Greedy: sampled positions\n  int passes = 0;\n  bool changed;\n  do {\n    changed = false;\n    bool cov[805];\n    if (get_covered_vec(cov) && passes > 0) break;\n    vector<int> unc;\n    for (int si = 0; si < M; ++si) if (!cov[si]) unc.push_back(si);\n    if (unc.empty()) break;\n    // top 60 longest\n    sort(unc.begin(), unc.end(), [](int a, int b){ return Lens[a] > Lens[b]; });\n    unc.resize(min(60, (int)unc.size()));\n    // sample 1000 pos per str\n    uint64_t prng = 42 + passes;\n    auto rnd = [&](int mod) {\n      prng = prng * 1103515245ULL + 12345;\n      return (int)(prng % mod);\n    };\n    for (int si : unc) {\n      const string& s = SS[si];\n      int k = s.size();\n      int best_cost = 99;\n      int best_ndot = -1;\n      int best_dir = -1, best_fix = -1, best_st = -1;\n      for (int tr = 0; tr < 1000; ++tr) {\n        int dir = rnd(2);\n        int fix = rnd(N);\n        int st = rnd(N);\n        int cost = 0;\n        int ndot = 0;\n        for (int p = 0; p < k; ++p) {\n          int rr = dir ? (st + p) % N : fix;\n          int cc = dir ? fix : (st + p) % N;\n          char cur = grid[rr][cc];\n          if (cur != '.' && cur != s[p]) ++cost;\n          if (cur == '.') ++ndot;\n        }\n        if (cost > best_cost) continue;\n        if (cost < best_cost || ndot > best_ndot) {\n          best_cost = cost;\n          best_ndot = ndot;\n          best_dir = dir;\n          best_fix = fix;\n          best_st = st;\n        }\n      }\n      if (best_cost == 0) {\n        // place\n        int dir = best_dir, fix = best_fix, st = best_st;\n        for (int p = 0; p < k; ++p) {\n          int rr = dir ? (st + p) % N : fix;\n          int cc = dir ? fix : (st + p) % N;\n          grid[rr][cc] = s[p];\n        }\n        changed = true;\n      }\n    }\n    passes++;\n  } while (changed && passes < 8);\n  memcpy(best_grid, grid, sizeof(grid));\n  int best_c = get_covered();\n  // Try uniform fills\n  for (int ci = 0; ci < 8; ++ci) {\n    char fill_ch = chars[ci];\n    memcpy(temp_grid, best_grid, sizeof(grid));\n    for (int i = 0; i < N; ++i)\n      for (int j = 0; j < N; ++j)\n        if (temp_grid[i][j] == '.') temp_grid[i][j] = fill_ch;\n    memcpy(grid, temp_grid, sizeof(grid));\n    int tc = get_covered();\n    if (tc > best_c) {\n      best_c = tc;\n      memcpy(best_grid, grid, sizeof(grid));\n    }\n  }\n  memcpy(grid, best_grid, sizeof(grid));\n  // If full coverage, blanking\n  if (get_covered() == M) {\n    do_blanking();\n  }\n  // Output\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) cout << grid[i][j];\n    cout << '\\n';\n  }\n  return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nchar get_move(int fi, int fj, int ti, int tj) {\n    int di = ti - fi, dj = tj - fj;\n    if (di == -1 && dj == 0) return 'U';\n    if (di == 1 && dj == 0) return 'D';\n    if (di == 0 && dj == 1) return 'R';\n    if (di == 0 && dj == -1) return 'L';\n    return '?';\n}\n\nll tour_cost(const vector<int>& ord, const vector<vector<ll>>& dists, int nt) {\n    ll c = 0;\n    for (int i = 0; i < nt; ++i) c += dists[ord[i]][ord[(i + 1) % nt]];\n    return c;\n}\n\nstring build_tsp_path(const vector<int>& ord, const vector<vector<string>>& pathstr, int nt) {\n    string path;\n    path.reserve(4000000);\n    for (int i = 0; i < nt; ++i) {\n        path += pathstr[ord[i]][ord[(i + 1) % nt]];\n    }\n    return path;\n}\n\nstring build_mst_path(int start_tid, const vector<vector<string>>& pathstr, const vector<vector<int>>& tadj) {\n    string path;\n    path.reserve(4000000);\n    function<void(int, int)> dfs = [&](int u, int p) {\n        for (int v : tadj[u]) if (v != p) {\n            path += pathstr[u][v];\n            dfs(v, u);\n            path += pathstr[v][u];\n        }\n    };\n    dfs(start_tid, -1);\n    return path;\n}\n\npair<ll, string> compute_best(const vector<pair<int, int>>& base_terms, int si, int sj, int numcells,\n                              const vector<pair<int, int>>& cells, const vector<vector<pair<int, int>>>& graph,\n                              const vector<vector<int>>& cellid, int N) {\n    vector<pair<int, int>> terms = base_terms;\n    set<pair<int, int>> uniq;\n    for (auto p : terms) uniq.insert(p);\n    if (!uniq.count({si, sj})) terms.emplace_back(si, sj);\n    int nt = terms.size();\n    if (nt == 0) return {0, \"\"};\n    vector<int> termids(nt);\n    for (int k = 0; k < nt; ++k) termids[k] = cellid[terms[k].first][terms[k].second];\n    // Find start_tid correctly\n    int start_tid = -1;\n    for (int k = 0; k < nt; ++k) {\n        if (terms[k].first == si && terms[k].second == sj) {\n            start_tid = k;\n            break;\n        }\n    }\n    if (start_tid == -1) return {LLONG_MAX / 2, \"\"};  // impossible\n    const ll INF = 1LL << 60;\n    vector<vector<ll>> dists(nt, vector<ll>(nt, INF));\n    vector<vector<string>> pathstr(nt, vector<string>(nt));\n    int dx[4] = {-1, 0, 1, 0};\n    int dy[4] = {0, 1, 0, -1};\n    for (int s = 0; s < nt; ++s) {\n        int sid = termids[s];\n        vector<ll> d(numcells, INF);\n        vector<int> pred(numcells, -1);\n        d[sid] = 0;\n        priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;\n        pq.emplace(0, sid);\n        while (!pq.empty()) {\n            auto [dc, u] = pq.top(); pq.pop();\n            if (dc > d[u]) continue;\n            for (auto [v, wc] : graph[u]) {\n                ll nc = d[u] + wc;\n                if (nc < d[v]) {\n                    d[v] = nc;\n                    pred[v] = u;\n                    pq.emplace(nc, v);\n                }\n            }\n        }\n        for (int t = 0; t < nt; ++t) {\n            int tid = termids[t];\n            if (d[tid] >= INF / 2) continue;\n            dists[s][t] = d[tid];\n            string& pth = pathstr[s][t];\n            int cur = tid;\n            while (cur != sid) {\n                int prv = pred[cur];\n                if (prv == -1) break;\n                auto [pi, pj] = cells[prv];\n                auto [ci, cj] = cells[cur];\n                pth += get_move(pi, pj, ci, cj);\n                cur = prv;\n            }\n            reverse(pth.begin(), pth.end());\n        }\n    }\n    // MST\n    vector<tuple<ll, int, int>> edges;\n    for (int a = 0; a < nt; ++a)\n        for (int b = a + 1; b < nt; ++b) {\n            ll dab = dists[a][b], dba = dists[b][a];\n            if (dab < INF / 2 && dba < INF / 2) edges.emplace_back(dab + dba, a, b);\n        }\n    sort(edges.begin(), edges.end());\n    vector<int> par(nt);\n    iota(par.begin(), par.end(), 0);\n    auto find = [&](auto self, int x) -> int { return par[x] == x ? x : par[x] = self(self, par[x]); };\n    vector<vector<int>> tadj(nt);\n    ll mst_cost = 0;\n    int nedges = 0;\n    for (auto [w, a, b] : edges) {\n        int pa = find(find, a), pb = find(find, b);\n        if (pa != pb) {\n            par[pa] = pb;\n            tadj[a].push_back(b);\n            tadj[b].push_back(a);\n            mst_cost += w;\n            ++nedges;\n            if (nedges == nt - 1) break;\n        }\n    }\n    string mst_path = build_mst_path(start_tid, pathstr, tadj);\n    // TSP: NN + 2opt fwd/rev\n    ll best_tsp_c = LLONG_MAX / 2;\n    string best_tsp_p;\n    {\n        vector<int> ord(nt);\n        vector<bool> vis(nt);\n        ord[0] = start_tid;\n        vis[start_tid] = true;\n        int cur = start_tid;\n        for (int st = 1; st < nt; ++st) {\n            ll mn = INF;\n            int nxt = -1;\n            for (int c = 0; c < nt; ++c)\n                if (!vis[c] && dists[cur][c] < mn) {\n                    mn = dists[cur][c];\n                    nxt = c;\n                }\n            ord[st] = nxt;\n            vis[nxt] = true;\n            cur = nxt;\n        }\n        auto improve = [&](vector<int> o) -> pair<ll, string> {\n            int passes = 0, maxp = nt * 3;\n            bool ch = true;\n            while (ch && passes++ < maxp) {\n                ch = false;\n                for (int i = 0; i < nt - 2; ++i)\n                    for (int k = i + 2; k < nt - 1; ++k) {\n                        ll d1 = dists[o[i]][o[i + 1]], d2 = dists[o[k]][o[k + 1]];\n                        ll nd1 = dists[o[i]][o[k]], nd2 = dists[o[i + 1]][o[k + 1]];\n                        if (nd1 + nd2 < d1 + d2) {\n                            reverse(o.begin() + i + 1, o.begin() + k + 1);\n                            ch = true;\n                        }\n                    }\n            }\n            ll cc = tour_cost(o, dists, nt);\n            return {cc, build_tsp_path(o, pathstr, nt)};\n        };\n        auto [c1, p1] = improve(ord);\n        vector<int> rev_ord = ord;\n        reverse(rev_ord.begin() + 1, rev_ord.end());\n        auto [c2, p2] = improve(rev_ord);\n        if (c1 < best_tsp_c) {\n            best_tsp_c = c1;\n            best_tsp_p = p1;\n        }\n        if (c2 < best_tsp_c) {\n            best_tsp_c = c2;\n            best_tsp_p = p2;\n        }\n    }\n    if (nt == 1) return {0, \"\"};\n    if (best_tsp_c <= mst_cost) return {best_tsp_c, best_tsp_p};\n    return {mst_cost, mst_path};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\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    vector<vector<bool>> road(N, vector<bool>(N));\n    vector<vector<int>> enter(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (grid[i][j] != '#') {\n                road[i][j] = true;\n                enter[i][j] = grid[i][j] - '0';\n            }\n    // H_reps\n    vector<pair<int, int>> h_reps;\n    for (int i = 0; i < N; ++i) {\n        int j = 0;\n        while (j < N) {\n            if (!road[i][j]) {\n                ++j;\n                continue;\n            }\n            int sjj = j;\n            while (j < N && road[i][j]) ++j;\n            h_reps.emplace_back(i, (sjj + j - 1) / 2);\n        }\n    }\n    // V_reps\n    vector<pair<int, int>> v_reps;\n    for (int j = 0; j < N; ++j) {\n        int i = 0;\n        while (i < N) {\n            if (!road[i][j]) {\n                ++i;\n                continue;\n            }\n            int sii = i;\n            while (i < N && road[i][j]) ++i;\n            v_reps.emplace_back((sii + i - 1) / 2, j);\n        }\n    }\n    // Cells, graph shared\n    vector<pair<int, int>> cells;\n    vector<vector<int>> cellid(N, vector<int>(N, -1));\n    int numcells = 0;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (road[i][j]) {\n                cellid[i][j] = numcells++;\n                cells.push_back({i, j});\n            }\n    vector<vector<pair<int, int>>> graph(numcells);\n    int dx[4] = {-1, 0, 1, 0};\n    int dy[4] = {0, 1, 0, -1};\n    for (int u = 0; u < numcells; ++u) {\n        auto [x, y] = cells[u];\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 && road[nx][ny]) {\n                graph[u].emplace_back(cellid[nx][ny], enter[nx][ny]);\n            }\n        }\n    }\n    auto [ch, ph] = compute_best(h_reps, si, sj, numcells, cells, graph, cellid, N);\n    auto [cv, pv] = compute_best(v_reps, si, sj, numcells, cells, graph, cellid, N);\n    if (ch <= cv) {\n        cout << ph << '\\n';\n    } else {\n        cout << pv << '\\n';\n    }\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout << fixed << setprecision(10);\n  int N, M, K, R;\n  cin >> N >> M >> K >> R;\n  vector<vector<int>> D(N + 1, vector<int>(K));\n  vector<double> avg_d(K, 0.0);\n  for (int i = 1; i <= N; ++i) {\n    for (int k = 0; k < K; ++k) {\n      cin >> D[i][k];\n      avg_d[k] += D[i][k];\n    }\n  }\n  for (int k = 0; k < K; ++k) {\n    avg_d[k] /= N;\n  }\n  vector<vector<int>> adj(N + 1);\n  vector<int> pending(N + 1, 0);\n  for (int r = 0; r < R; ++r) {\n    int u, v;\n    cin >> u >> v;\n    adj[u].push_back(v);\n    ++pending[v];\n  }\n  vector<int> crit(N + 1, 0);\n  auto get_crit = [&](auto&& self, int i) -> int {\n    if (crit[i] != 0) return crit[i];\n    int mx = 0;\n    for (int suc : adj[i]) {\n      mx = max(mx, self(self, suc));\n    }\n    crit[i] = 1 + mx;\n    return crit[i];\n  };\n  for (int i = 1; i <= N; ++i) {\n    get_crit(get_crit, i);\n  }\n  vector<vector<double>> est_s(M + 1, vector<double>(K, 0.0));\n  vector<int> obs_count(M + 1, 0);\n  for (int j = 1; j <= M; ++j) {\n    for (int k = 0; k < K; ++k) {\n      est_s[j][k] = avg_d[k] * 1.6;\n    }\n  }\n  vector<int> task_worker(N + 1, 0);\n  vector<int> task_start(N + 1, 0);\n  vector<bool> task_completed(N + 1, false);\n  vector<int> worker_task(M + 1, 0);\n  set<int> ready_set;\n  for (int i = 1; i <= N; ++i) {\n    if (pending[i] == 0) {\n      ready_set.insert(i);\n    }\n  }\n  int day = 0;\n  while (true) {\n    ++day;\n    vector<int> idles;\n    for (int j = 1; j <= M; ++j) {\n      if (worker_task[j] == 0) {\n        idles.push_back(j);\n      }\n    }\n    vector<int> readies_vec(ready_set.begin(), ready_set.end());\n    if (idles.empty() || readies_vec.empty()) {\n      cout << 0 << '\\n';\n      cout.flush();\n    } else {\n      vector<pair<int, double>> ready_list;\n      for (int ti : readies_vec) {\n        double min_pt = 1e100;\n        for (int j : idles) {\n          double w = 0.0;\n          for (int k = 0; k < K; ++k) {\n            w += max(0.0, (double)D[ti][k] - est_s[j][k]);\n          }\n          double pt = (w <= 0 ? 1.0 : max(1.0, w));\n          if (pt < min_pt) min_pt = pt;\n        }\n        ready_list.emplace_back(ti, min_pt);\n      }\n      sort(ready_list.begin(), ready_list.end(), [&](const pair<int, double>& a, const pair<int, double>& b) {\n        if (crit[a.first] != crit[b.first]) return crit[a.first] > crit[b.first];\n        if (fabs(a.second - b.second) > 1e-9) return a.second < b.second;\n        return a.first < b.first;\n      });\n      set<int> avail(idles.begin(), idles.end());\n      vector<pair<int, int>> assignment;\n      for (auto [ti, mpt] : ready_list) {\n        if (avail.empty()) break;\n        double best_pt = 1e100;\n        int best_j = -1;\n        for (int j : avail) {\n          double w = 0.0;\n          for (int k = 0; k < K; ++k) {\n            w += max(0.0, (double)D[ti][k] - est_s[j][k]);\n          }\n          double pt = (w <= 0 ? 1.0 : max(1.0, w));\n          if (pt < best_pt || (fabs(pt - best_pt) < 1e-9 && j < best_j)) {\n            best_pt = pt;\n            best_j = j;\n          }\n        }\n        if (best_j != -1) {\n          assignment.emplace_back(best_j, ti);\n          avail.erase(best_j);\n        }\n      }\n      cout << assignment.size();\n      for (auto p : assignment) {\n        cout << \" \" << p.first << \" \" << p.second;\n      }\n      cout << '\\n';\n      cout.flush();\n      for (auto [wj, ti] : assignment) {\n        task_worker[ti] = wj;\n        task_start[ti] = day;\n        worker_task[wj] = ti;\n        ready_set.erase(ti);\n      }\n    }\n    int n;\n    cin >> n;\n    if (n == -1) {\n      return 0;\n    }\n    vector<int> finished_workers(n);\n    for (int i = 0; i < n; ++i) {\n      cin >> finished_workers[i];\n    }\n    for (int jj : finished_workers) {\n      int tsk = worker_task[jj];\n      if (tsk == 0) continue;\n      int t_obs = day - task_start[tsk] + 1;\n      double w_est = max(0.0, (double)t_obs - 1.0);\n      ++obs_count[jj];\n      double alpha = 1.0 / obs_count[jj];\n      double current_w = 0.0;\n      vector<double> contrib(K, 0.0);\n      for (int k = 0; k < K; ++k) {\n        double defk = max(0.0, (double)D[tsk][k] - est_s[jj][k]);\n        contrib[k] = defk;\n        current_w += defk;\n      }\n      double error = current_w - w_est;\n      if (current_w > 1e-6) {\n        for (int k = 0; k < K; ++k) {\n          if (contrib[k] > 1e-6) {\n            double frac = contrib[k] / current_w;\n            double delta = alpha * error * frac;\n            est_s[jj][k] += delta;\n            if (est_s[jj][k] < 0.0) est_s[jj][k] = 0.0;\n          }\n        }\n      } else if (w_est > 1.0) {\n        double total_d = 0.0;\n        for (int k = 0; k < K; ++k) total_d += D[tsk][k];\n        if (total_d > 0) {\n          double delta = -alpha * (w_est / (double)K);\n          for (int k = 0; k < K; ++k) {\n            est_s[jj][k] += delta;\n            if (est_s[jj][k] < 0.0) est_s[jj][k] = 0.0;\n          }\n        }\n      }\n      task_completed[tsk] = true;\n      task_worker[tsk] = 0;\n      worker_task[jj] = 0;\n      for (int suc : adj[tsk]) {\n        --pending[suc];\n        if (pending[suc] == 0 && task_worker[suc] == 0 && !task_completed[suc]) {\n          ready_set.insert(suc);\n        }\n      }\n    }\n  }\n  return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int xx = 0, int yy = 0) : x(xx), y(yy) {}\n};\n\nint dist(Point a, Point b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\ndouble get_angle(const Point& pp) {\n    return atan2(pp.y - 400, pp.x - 400);\n}\n\nstruct Order {\n    Point p, d;\n    int id;\n    int len() const { return dist(p, d); }\n};\n\nconst int N = 50;\nconst Point O(400, 400);\n\nint get_var_cost(const vector<int>& perm, const vector<Point>& Ps, const vector<Point>& Ds) {\n    if (perm.empty()) return 0;\n    int res = dist(O, Ps[perm[0]]);\n    for (size_t i = 0; i + 1 < perm.size(); ++i) {\n        res += dist(Ds[perm[i]], Ps[perm[i + 1]]);\n    }\n    res += dist(Ds[perm.back()], O);\n    return res;\n}\n\nbool improve2opt(vector<int>& perm, const vector<Point>& Ps, const vector<Point>& Ds) {\n    int cur_cost = get_var_cost(perm, Ps, Ds);\n    bool any_improved;\n    int passes = 0;\n    const int MAX_PASSES = 500;\n    do {\n        any_improved = false;\n        for (int i = 0; i < N; ++i) {\n            bool local_improved = false;\n            for (int j = i + 1; j < N; ++j) {\n                vector<int> candidate = perm;\n                reverse(candidate.begin() + i, candidate.begin() + j + 1);\n                int cand_cost = get_var_cost(candidate, Ps, Ds);\n                if (cand_cost < cur_cost) {\n                    perm = move(candidate);\n                    cur_cost = cand_cost;\n                    any_improved = true;\n                    local_improved = true;\n                    break;\n                }\n            }\n            if (local_improved) {\n                break;  // restart i from 0\n            }\n        }\n        ++passes;\n    } while (any_improved && passes < MAX_PASSES);\n    return any_improved;\n}\n\npair<int, vector<Point>> get_best_pallpd(const vector<Point>& Ps, const vector<Point>& Ds) {\n    int best_tt = INT_MAX;\n    vector<Point> best_route;\n    for (int pcw = 0; pcw < 2; ++pcw) {\n        vector<pair<double, int>> pang(N);\n        for (int k = 0; k < N; ++k) {\n            double a = get_angle(Ps[k]);\n            if (pcw) a = -a;\n            pang[k] = {a, k};\n        }\n        sort(pang.begin(), pang.end());\n        vector<Point> pseq(N);\n        for (int k = 0; k < N; ++k) pseq[k] = Ps[pang[k].second];\n        for (int dcw = 0; dcw < 2; ++dcw) {\n            vector<pair<double, int>> dang(N);\n            for (int k = 0; k < N; ++k) {\n                double a = get_angle(Ds[k]);\n                if (dcw) a = -a;\n                dang[k] = {a, k};\n            }\n            sort(dang.begin(), dang.end());\n            vector<Point> dseq(N);\n            for (int k = 0; k < N; ++k) dseq[k] = Ds[dang[k].second];\n            vector<Point> route{O};\n            route.insert(route.end(), pseq.begin(), pseq.end());\n            route.insert(route.end(), dseq.begin(), dseq.end());\n            route.push_back(O);\n            int tt = 0;\n            for (size_t k = 0; k + 1 < route.size(); ++k) {\n                tt += dist(route[k], route[k + 1]);\n            }\n            if (tt < best_tt) {\n                best_tt = tt;\n                best_route = route;\n            }\n        }\n    }\n    return {best_tt, best_route};\n}\n\npair<int, vector<int>> optimize_rigid(const vector<Point>& Ps, const vector<Point>& Ds) {\n    vector<vector<int>> inits;\n    // CCW P\n    {\n        vector<pair<double, int>> ang(N);\n        for (int ii = 0; ii < N; ++ii) ang[ii] = {get_angle(Ps[ii]), ii};\n        sort(ang.begin(), ang.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = ang[ii].second;\n        inits.push_back(ini);\n    }\n    // CW P\n    {\n        vector<pair<double, int>> ang(N);\n        for (int ii = 0; ii < N; ++ii) ang[ii] = {-get_angle(Ps[ii]), ii};\n        sort(ang.begin(), ang.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = ang[ii].second;\n        inits.push_back(ini);\n    }\n    // Manh P\n    {\n        vector<pair<pair<int, int>, int>> mng(N);\n        for (int ii = 0; ii < N; ++ii) {\n            int u = Ps[ii].x + Ps[ii].y;\n            int v = Ps[ii].x - Ps[ii].y;\n            mng[ii] = {{u, v}, ii};\n        }\n        sort(mng.begin(), mng.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = mng[ii].second;\n        inits.push_back(ini);\n    }\n    // Dist O P\n    {\n        vector<pair<int, int>> dsp(N);\n        for (int ii = 0; ii < N; ++ii) dsp[ii] = {dist(O, Ps[ii]), ii};\n        sort(dsp.begin(), dsp.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = dsp[ii].second;\n        inits.push_back(ini);\n    }\n    // CCW D\n    {\n        vector<pair<double, int>> ang(N);\n        for (int ii = 0; ii < N; ++ii) ang[ii] = {get_angle(Ds[ii]), ii};\n        sort(ang.begin(), ang.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = ang[ii].second;\n        inits.push_back(ini);\n    }\n    // CW D\n    {\n        vector<pair<double, int>> ang(N);\n        for (int ii = 0; ii < N; ++ii) ang[ii] = {-get_angle(Ds[ii]), ii};\n        sort(ang.begin(), ang.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = ang[ii].second;\n        inits.push_back(ini);\n    }\n    int best_var = INT_MAX;\n    vector<int> best_perm(N);\n    mt19937 gen(random_device{}());\n    uniform_real_distribution<double> rdis(0.0, 1.0);\n    uniform_int_distribution<int> randpos(0, N - 1);\n    for (auto ini : inits) {\n        vector<int> curp = ini;\n        improve2opt(curp, Ps, Ds);\n        int cc = get_var_cost(curp, Ps, Ds);\n        if (cc < best_var) {\n            best_var = cc;\n            best_perm = curp;\n        }\n        reverse(curp.begin(), curp.end());\n        improve2opt(curp, Ps, Ds);\n        cc = get_var_cost(curp, Ps, Ds);\n        if (cc < best_var) {\n            best_var = cc;\n            best_perm = curp;\n        }\n    }\n    // SA rev-moves\n    vector<int> path = best_perm;\n    int current_cost = best_var;\n    double temp = 10000.0;\n    double alpha = 0.99994;\n    const int MAX_ATT = 10000000;\n    for (int att = 0; att < MAX_ATT; ++att) {\n        int i = randpos(gen), j = randpos(gen);\n        if (i > j) swap(i, j);\n        if (i == j) continue;\n        vector<int> newp = path;\n        reverse(newp.begin() + i, newp.begin() + j + 1);\n        int nc = get_var_cost(newp, Ps, Ds);\n        int delta = nc - current_cost;\n        if (delta < 0 || rdis(gen) < exp(-double(delta) / temp)) {\n            path = move(newp);\n            current_cost = nc;\n            if (nc < best_var) {\n                best_var = nc;\n                best_perm = path;\n            }\n        }\n        temp *= alpha;\n        if (temp < 0.1) break;\n    }\n    improve2opt(best_perm, Ps, Ds);\n    best_var = get_var_cost(best_perm, Ps, Ds);\n    // Final rev check\n    {\n        vector<int> revp = best_perm;\n        reverse(revp.begin(), revp.end());\n        int rvar = get_var_cost(revp, Ps, Ds);\n        if (rvar < best_var) {\n            best_var = rvar;\n            best_perm = revp;\n        }\n    }\n    return {best_var, best_perm};\n}\n\nstruct Sel {\n    vector<int> ids;\n    vector<Point> Ps, Ds;\n    int sum_len = 0;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        orders[i].p = {a, b};\n        orders[i].d = {c, d};\n        orders[i].id = i + 1;\n    }\n    vector<Sel> sels;\n    // Forward greedy\n    {\n        bool used[1000] = {};\n        vector<int> fsel;\n        Point curr = O;\n        for (int k = 0; k < N; ++k) {\n            int best = -1;\n            int md = INT_MAX;\n            for (int u = 0; u < 1000; ++u) {\n                if (used[u]) continue;\n                int dd = dist(curr, orders[u].p);\n                int tiel = orders[u].len();\n                int bestl = best == -1 ? INT_MAX : orders[best].len();\n                if (dd < md || (dd == md && tiel < bestl)) {\n                    md = dd;\n                    best = u;\n                }\n            }\n            assert(best != -1);\n            fsel.push_back(best);\n            used[best] = true;\n            curr = orders[best].d;\n        }\n        Sel sel;\n        sel.Ps.resize(N);\n        sel.Ds.resize(N);\n        sel.ids.resize(N);\n        for (int k = 0; k < N; ++k) {\n            int oi = fsel[k];\n            sel.Ps[k] = orders[oi].p;\n            sel.Ds[k] = orders[oi].d;\n            sel.ids[k] = orders[oi].id;\n            sel.sum_len += orders[oi].len();\n        }\n        sort(sel.ids.begin(), sel.ids.end());\n        sels.push_back(move(sel));\n    }\n    // Reverse greedy\n    {\n        bool used[1000] = {};\n        vector<int> rsel;\n        Point curr = O;\n        for (int k = 0; k < N; ++k) {\n            int best = -1;\n            int md = INT_MAX;\n            for (int u = 0; u < 1000; ++u) {\n                if (used[u]) continue;\n                int dd = dist(orders[u].d, curr);\n                int tiep = dist(O, orders[u].p);\n                int bestp = best == -1 ? INT_MAX : dist(O, orders[best].p);\n                if (dd < md || (dd == md && tiep < bestp)) {\n                    md = dd;\n                    best = u;\n                }\n            }\n            assert(best != -1);\n            rsel.push_back(best);\n            used[best] = true;\n            curr = orders[best].p;\n        }\n        reverse(rsel.begin(), rsel.end());\n        Sel sel;\n        sel.Ps.resize(N);\n        sel.Ds.resize(N);\n        sel.ids.resize(N);\n        for (int k = 0; k < N; ++k) {\n            int oi = rsel[k];\n            sel.Ps[k] = orders[oi].p;\n            sel.Ds[k] = orders[oi].d;\n            sel.ids[k] = orders[oi].id;\n            sel.sum_len += orders[oi].len();\n        }\n        sort(sel.ids.begin(), sel.ids.end());\n        sels.push_back(move(sel));\n    }\n    // Shortest len\n    {\n        vector<pair<int, int>> sh(1000);\n        for (int i = 0; i < 1000; ++i) sh[i] = {orders[i].len(), i};\n        sort(sh.begin(), sh.end());\n        Sel sel;\n        sel.Ps.resize(N);\n        sel.Ds.resize(N);\n        sel.ids.resize(N);\n        for (int k = 0; k < N; ++k) {\n            int oi = sh[k].second;\n            sel.Ps[k] = orders[oi].p;\n            sel.Ds[k] = orders[oi].d;\n            sel.ids[k] = orders[oi].id;\n            sel.sum_len += orders[oi].len();\n        }\n        sort(sel.ids.begin(), sel.ids.end());\n        sels.push_back(move(sel));\n    }\n    // Solo cheap: O-P + len + D-O\n    {\n        vector<pair<int, int>> sol(1000);\n        for (int i = 0; i < 1000; ++i) {\n            sol[i] = {dist(O, orders[i].p) + orders[i].len() + dist(orders[i].d, O), i};\n        }\n        sort(sol.begin(), sol.end());\n        Sel sel;\n        sel.Ps.resize(N);\n        sel.Ds.resize(N);\n        sel.ids.resize(N);\n        for (int k = 0; k < N; ++k) {\n            int oi = sol[k].second;\n            sel.Ps[k] = orders[oi].p;\n            sel.Ds[k] = orders[oi].d;\n            sel.ids[k] = orders[oi].id;\n            sel.sum_len += orders[oi].len();\n        }\n        sort(sel.ids.begin(), sel.ids.end());\n        sels.push_back(move(sel));\n    }\n    // Close: O-P + O-D\n    {\n        vector<pair<int, int>> cl(1000);\n        for (int i = 0; i < 1000; ++i) {\n            cl[i] = {dist(O, orders[i].p) + dist(O, orders[i].d), i};\n        }\n        sort(cl.begin(), cl.end());\n        Sel sel;\n        sel.Ps.resize(N);\n        sel.Ds.resize(N);\n        sel.ids.resize(N);\n        for (int k = 0; k < N; ++k) {\n            int oi = cl[k].second;\n            sel.Ps[k] = orders[oi].p;\n            sel.Ds[k] = orders[oi].d;\n            sel.ids[k] = orders[oi].id;\n            sel.sum_len += orders[oi].len();\n        }\n        sort(sel.ids.begin(), sel.ids.end());\n        sels.push_back(move(sel));\n    }\n    // Best overall\n    int best_t = INT_MAX;\n    vector<int> best_ids;\n    vector<Point> best_route;\n    for (const auto& sel : sels) {\n        auto [varc, permm] = optimize_rigid(sel.Ps, sel.Ds);\n        int rigid_t = sel.sum_len + varc;\n        vector<Point> rigid_route{O};\n        for (int pi : permm) {\n            rigid_route.push_back(sel.Ps[pi]);\n            rigid_route.push_back(sel.Ds[pi]);\n        }\n        rigid_route.push_back(O);\n        auto [pall_t, pall_route] = get_best_pallpd(sel.Ps, sel.Ds);\n        vector<Point> this_route;\n        int this_t;\n        if (pall_t < rigid_t) {\n            this_route = pall_route;\n            this_t = pall_t;\n        } else {\n            this_route = rigid_route;\n            this_t = rigid_t;\n        }\n        if (this_t < best_t) {\n            best_t = this_t;\n            best_ids = sel.ids;\n            best_route = this_route;\n        }\n    }\n    // Output\n    cout << N;\n    for (int r : best_ids) cout << ' ' << r;\n    cout << '\\n';\n    cout << best_route.size();\n    for (const auto& pt : best_route) {\n        cout << ' ' << pt.x << ' ' << pt.y;\n    }\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    vector<int> X(N), Y(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> X[i] >> Y[i];\n    }\n\n    vector<pair<int, int>> Edge(M);\n    vector<int> D(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        Edge[i] = {u, v};\n        double dx = X[u] - X[v];\n        double dy = Y[u] - Y[v];\n        D[i] = (int)round(hypot(dx, dy));\n    }\n\n    vector<int> par(N), sz(N, 1);\n    vector<double> cminx(N), cmaxx(N), cminy(N), cmaxy(N);\n    for (int i = 0; i < N; ++i) {\n        par[i] = i;\n        cminx[i] = cmaxx[i] = X[i];\n        cminy[i] = cmaxy[i] = Y[i];\n    }\n\n    auto find = [&](auto&& self, int x) -> int {\n        return par[x] == x ? x : par[x] = self(self, par[x]);\n    };\n\n    auto rect_dist = [&](int c1, int c2) -> double {\n        double dx = max({0.0, cminx[c1] - cmaxx[c2], cminx[c2] - cmaxx[c1]});\n        double dy = max({0.0, cminy[c1] - cmaxy[c2], cminy[c2] - cmaxy[c1]});\n        return hypot(dx, dy);\n    };\n\n    auto unite = [&](int a, int b) {\n        a = find(find, a);\n        b = find(find, b);\n        if (a == b) return;\n        if (sz[a] < sz[b]) swap(a, b);\n        par[b] = a;\n        sz[a] += sz[b];\n        cminx[a] = min(cminx[a], cminx[b]);\n        cmaxx[a] = max(cmaxx[a], cmaxx[b]);\n        cminy[a] = min(cminy[a], cminy[b]);\n        cmaxy[a] = max(cmaxy[a], cmaxy[b]);\n    };\n\n    int cur_comp = N;\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;\n\n        int u = Edge[i].first, v = Edge[i].second;\n        int pu = find(find, u), pv = find(find, v);\n        if (pu == pv) {\n            cout << 0 << '\\n' << flush;\n            continue;\n        }\n\n        int s1 = sz[pu], s2 = sz[pv];\n        int smin = min(s1, s2);\n        double sepd = rect_dist(pu, pv);\n        bool separated = (sepd > 1e-6);\n        double ratio = (double)l / D[i];\n\n        // Scan for future only when necessary\n        double min_fut_d = 1e9;\n        bool need_scan = (smin >= 12) && separated && (cur_comp > 20) && (i < M - 20);\n        if (need_scan) {\n            for (int j = i + 1; j < M; ++j) {\n                int qu = find(find, Edge[j].first);\n                int qv = find(find, Edge[j].second);\n                if ((qu == pu && qv == pv) || (qu == pv && qv == pu)) {\n                    min_fut_d = min(min_fut_d, (double)D[j]);\n                }\n            }\n        }\n        double est_sep = (min_fut_d < 5e8) ? min_fut_d : sepd;\n\n        bool too_bad = (ratio > 2.7);\n        bool is_small = (smin <= 32);\n        bool good_dist = !separated || (l <= 1.85 * est_sep + 2.5);\n\n        bool take = !too_bad && (is_small || good_dist);\n\n        // Urgency\n        int remaining = M - i - 1;\n        int needed = cur_comp - 1;\n        double urgency_ratio = (double)needed / max(1, remaining);\n        bool large_comps = (s1 >= 50 && s2 >= 50);\n        bool urgent = (remaining <= needed * 1.8) || (needed <= 15) || (urgency_ratio > 0.20) ||\n                      (large_comps && urgency_ratio > 0.15);\n        if (urgent) {\n            take = !too_bad;\n        }\n\n        if (take) {\n            unite(u, v);\n            --cur_comp;\n            cout << 1 << '\\n' << flush;\n        } else {\n            cout << 0 << '\\n' << flush;\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef pair<int, int> pii;\n\nconst int SZ = 30;\nbool passable[31][31];\nint DX[4] = {-1, 1, 0, 0};\nint DY[4] = {0, 0, -1, 1};\nchar WALLC[4] = {'u', 'd', 'l', 'r'};\nchar MOVEC[4] = {'U', 'D', 'L', 'R'};\nconst int GCX = 15, GCY = 15;\n\nbool in_bound(int x, int y) { return x >= 1 && x <= SZ && y >= 1 && y <= SZ; }\n\nbool can_wall(const vector<pii>& hpos, const vector<pii>& ppos, int hi, int d, int NN, int MM) {\n  int hx = hpos[hi].first, hy = hpos[hi].second;\n  int tx = hx + DX[d], ty = hy + DY[d];\n  if (!in_bound(tx, ty)) return false;\n  for (int k = 0; k < MM; k++) if (hpos[k].first == tx && hpos[k].second == ty) return false;\n  for (int k = 0; k < NN; k++) if (ppos[k].first == tx && ppos[k].second == ty) return false;\n  for (int dd = 0; dd < 4; dd++) {\n    int ax = tx + DX[dd], ay = ty + DY[dd];\n    if (!in_bound(ax, ay)) continue;\n    for (int k = 0; k < NN; k++) if (ppos[k].first == ax && ppos[k].second == ay) return false;\n  }\n  return true;\n}\n\nstruct CCInfo {\n  int id, size, min_pd, npet;\n  double score;\n  int bary_x, bary_y;\n};\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n\n  int N; cin >> N;\n  vector<pii> ppos(N);\n  vector<int> ptype(N);\n  for (int i = 0; i < N; i++) { int x, y, t; cin >> x >> y >> t; ppos[i]={x,y}; ptype[i]=t; }\n  int M; cin >> M;\n  vector<pii> hpos(M);\n  for (int i = 0; i < M; i++) { int x, y; cin >> x >> y; hpos[i]={x,y}; }\n\n  memset(passable, 0, sizeof(passable));\n  for (int i=1; i<=SZ; i++) for (int j=1; j<=SZ; j++) passable[i][j] = true;\n\n  vector<double> pet_threat(N);\n  double threat_base[6] = {0,1.0,4.0,12.0,65.0,25.0};\n  for (int i=0; i<N; i++) pet_threat[i] = threat_base[ptype[i]];\n\n  int pet_dist[31][31];\n  int comp_id[31][31];\n\n  for (int turn=0; turn<300; turn++) {\n    int sumx=0, sumy=0;\n    for (auto& hp : hpos) { sumx += hp.first; sumy += hp.second; }\n    int cur_cx = sumx / M, cur_cy = sumy / M;\n    int spread = 0;\n    for (auto& hp : hpos) spread = max(spread, abs(hp.first - cur_cx) + abs(hp.second - cur_cy));\n\n    // pet_dist BFS\n    memset(pet_dist, -1, sizeof(pet_dist));\n    queue<pii> q;\n    for (int i=0; i<N; i++) {\n      int px=ppos[i].first, py=ppos[i].second;\n      if (passable[px][py] && pet_dist[px][py]==-1) { pet_dist[px][py]=0; q.push({px,py}); }\n    }\n    while (!q.empty()) {\n      auto [x,y] = q.front(); q.pop();\n      for (int d=0; d<4; d++) {\n        int nx = x + DX[d], ny = y + DY[d];\n        if (in_bound(nx,ny) && passable[nx][ny] && pet_dist[nx][ny]==-1) {\n          pet_dist[nx][ny] = pet_dist[x][y] + 1;\n          q.push({nx,ny});\n        }\n      }\n    }\n\n    int min_human_pd = 999;\n    for (int hi=0; hi<M; hi++) {\n      int hx=hpos[hi].first, hy=hpos[hi].second;\n      int pd = pet_dist[hx][hy]; if (pd==-1) pd=999;\n      min_human_pd = min(min_human_pd, pd);\n    }\n\n    // CC analysis\n    memset(comp_id, -1, sizeof(comp_id));\n    int cid = 0;\n    vector<CCInfo> ccs;\n    vector<int> h_cc(M, -1);\n    double best_cc_score = 0;\n    int best_cid = -1;\n    for (int i=1; i<=SZ; i++) for (int j=1; j<=SZ; j++) {\n      if (passable[i][j] && comp_id[i][j]==-1) {\n        int csize=0, cmin_pd=999, sumx_cc=0, sumy_cc=0, cnp=0;\n        queue<pii> qq;\n        qq.push({i,j}); comp_id[i][j]=cid;\n        while (!qq.empty()) {\n          auto [x,y]=qq.front(); qq.pop();\n          csize++;\n          sumx_cc += x; sumy_cc += y;\n          cmin_pd = min(cmin_pd, pet_dist[x][y]==-1 ? 999 : pet_dist[x][y]);\n          for (int d=0; d<4; d++) {\n            int nx=x+DX[d], ny=y+DY[d];\n            if (in_bound(nx,ny) && passable[nx][ny] && comp_id[nx][ny]==-1) {\n              comp_id[nx][ny]=cid;\n              qq.push({nx,ny});\n            }\n          }\n        }\n        // npet\n        for (int pi=0; pi<N; pi++) {\n          int px=ppos[pi].first, py=ppos[pi].second;\n          if (in_bound(px,py) && comp_id[px][py]==cid) cnp++;\n        }\n        double ccscore = csize * (cmin_pd / 20.0) * pow(0.6, cnp);\n        ccs.push_back({cid, csize, cmin_pd, cnp, ccscore, sumx_cc/csize, sumy_cc/csize});\n        if (ccscore > best_cc_score) { best_cc_score = ccscore; best_cid = cid; }\n        cid++;\n      }\n    }\n\n    // human CC\n    double human_cc_score = 0;\n    if (M>0) {\n      int hx0 = hpos[0].first, hy0 = hpos[0].second;\n      int hcid = comp_id[hx0][hy0];\n      h_cc[0] = hcid;\n      bool all_same = true;\n      for (int hi=1; hi<M; hi++) {\n        int hx=hpos[hi].first, hy=hpos[hi].second;\n        int cc = comp_id[hx][hy];\n        h_cc[hi] = cc;\n        if (cc != hcid) all_same = false;\n      }\n      if (all_same && hcid >=0 && hcid < ccs.size()) human_cc_score = ccs[hcid].score;\n    }\n\n    bool wall_mode = (spread <= 5) || (turn > 140 && spread <= 9) || (min_human_pd <= 3) ||\n                     (human_cc_score > best_cc_score * 0.8);\n\n    pii target = {cur_cx, cur_cy};\n    if (best_cid != -1) {\n      auto& bestcc = ccs[best_cid];\n      target = {bestcc.bary_x, bestcc.bary_y};\n    } else if (turn > 220 && min_human_pd >=4 && spread <=5) {\n      target = {cur_cx, cur_cy};\n    }\n\n    int tx = target.first, ty = target.second;\n    int target_cid = comp_id[tx][ty];\n\n    string action(M, '.');\n    if (wall_mode) {\n      for (int hi=0; hi<M; hi++) {\n        double bsc = -1e100; int bestd=-1;\n        auto [hx, hy] = hpos[hi];\n        for (int d=0; d<4; d++) {\n          if (!can_wall(hpos, ppos, hi, d, N, M)) continue;\n          int wtx = hx + DX[d], wty = hy + DY[d];\n          double sc = 0.0;\n          double dist_c = abs(wtx - cur_cx) + abs(wty - cur_cy) + 2.0;\n          int w_pd = pet_dist[wtx][wty]; if (w_pd==-1) w_pd=999;\n          int w_ccid = comp_id[wtx][wty];\n          double cc_bonus = (w_ccid == target_cid ? w_pd * 0.2 : 0);\n          for (int pi=0; pi<N; pi++) {\n            int pdist = abs(wtx - ppos[pi].first) + abs(wty - ppos[pi].second);\n            sc += pet_threat[pi] / (pdist + 1);\n          }\n          sc /= dist_c;\n          sc += 0.08 * (abs(wtx - cur_cx) + abs(wty - cur_cy)) + cc_bonus;\n          if (sc > bsc) { bsc=sc; bestd=d; }\n        }\n        if (bestd != -1) action[hi] = WALLC[bestd];\n      }\n    } else {\n      for (int hi=0; hi<M; hi++) {\n        auto [hx, hy] = hpos[hi];\n        int mdist = abs(hx-tx) + abs(hy-ty);\n        if (mdist==0) continue;\n        int best_red=-1, best_pd=-1; int bestd=-1;\n        for (int d=0; d<4; d++) {\n          int nx=hx+DX[d], ny=hy+DY[d];\n          if (!in_bound(nx,ny) || !passable[nx][ny]) continue;\n          int nmdist = abs(nx-tx) + abs(ny-ty);\n          int red = mdist - nmdist;\n          int npd = pet_dist[nx][ny]; if (npd==-1) npd=999;\n          if (red > best_red || (red==best_red && npd > best_pd)) {\n            best_red = red; best_pd = npd; bestd = d;\n          }\n        }\n        if (bestd !=-1 && best_red>0) action[hi] = MOVEC[bestd];\n      }\n    }\n\n    cout << \"#\" << turn << \" s:\" << spread << \" pd:\" << min_human_pd << \" wm:\" << wall_mode\n         << \" best_cc:\" << best_cc_score << \" h_cc:\" << human_cc_score << \" t(\" << tx << \",\" << ty << \")\" << endl;\n    cout << action << endl << flush;\n\n    // pets\n    for (int i=0; i<N; i++) {\n      string s; cin >> s;\n      int x=ppos[i].first, y=ppos[i].second;\n      for (char c:s) {\n        if (c=='U') x--; else if (c=='D') x++; else if (c=='L') y--; else if (c=='R') y++;\n      }\n      ppos[i]={x,y};\n    }\n\n    // humans/walls\n    for (int hi=0; hi<M; hi++) {\n      char c=action[hi];\n      if (c=='.') continue;\n      bool ism = isupper((unsigned char)c);\n      int dd=-1;\n      if (ism) {\n        if (c=='U') dd=0; else if (c=='D') dd=1; else if (c=='L') dd=2; else dd=3;\n        hpos[hi].first += DX[dd]; hpos[hi].second += DY[dd];\n      } else {\n        if (c=='u') dd=0; else if (c=='d') dd=1; else if (c=='l') dd=2; else dd=3;\n        int wx = hpos[hi].first + DX[dd], wy = hpos[hi].second + DY[dd];\n        if (in_bound(wx,wy)) passable[wx][wy]=false;\n      }\n    }\n  }\n  return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int ROWS = 20, COLS = 20, N = ROWS * COLS;\n\nint get_row(int pos) { return pos / COLS; }\nint get_col(int pos) { return pos % COLS; }\n\nint attempt_move(int cur_pos, char direction, const vector<string>& h_walls, const vector<string>& v_walls) {\n  int r = get_row(cur_pos), c = get_col(cur_pos);\n  int dr = 0, dc = 0;\n  switch (direction) {\n    case 'U': dr = -1; break;\n    case 'D': dr = 1; break;\n    case 'L': dc = -1; break;\n    case 'R': dc = 1; break;\n    default: return cur_pos;\n  }\n  int nr = r + dr, nc = c + dc;\n  if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) return cur_pos;\n  if (dr != 0) {\n    if (dr > 0 && v_walls[r][c] == '1') return cur_pos;\n    if (dr < 0 && v_walls[nr][c] == '1') return cur_pos;\n  } else {\n    if (dc > 0 && h_walls[r][c] == '1') return cur_pos;\n    if (dc < 0 && h_walls[r][nc] == '1') return cur_pos;\n  }\n  return nr * COLS + nc;\n}\n\nstring shortest_path(int start_pos, int target_pos, const vector<string>& h_walls, const vector<string>& v_walls, const string& dir_order) {\n  vector<int> dist(N, -1), parent(N, -1);\n  dist[start_pos] = 0;\n  queue<int> q; q.push(start_pos);\n  while (!q.empty()) {\n    int u = q.front(); q.pop();\n    if (u == target_pos) break;\n    for (char dch : dir_order) {\n      int v = attempt_move(u, dch, h_walls, v_walls);\n      if (dist[v] == -1) {\n        dist[v] = dist[u] + 1;\n        parent[v] = u;\n        q.push(v);\n      }\n    }\n  }\n  if (dist[target_pos] == -1) return \"\";\n  string path_str;\n  int cur = target_pos;\n  while (cur != start_pos) {\n    int prev = parent[cur];\n    int pr = get_row(prev), pc = get_col(prev);\n    int cr = get_row(cur), cc = get_col(cur);\n    char dch = (cr == pr + 1 ? 'D' : (cr == pr - 1 ? 'U' : (cc == pc + 1 ? 'R' : 'L')));\n    path_str += dch;\n    cur = prev;\n  }\n  reverse(path_str.begin(), path_str.end());\n  return path_str;\n}\n\ndouble evaluate(const string& path_str, double forget_p, int start_pos, int target_pos,\n                const vector<string>& h_walls, const vector<string>& v_walls) {\n  if (start_pos == target_pos) return 401.0;\n  int L = path_str.size();\n  vector<double> curr_prob(N, 0.0);\n  curr_prob[start_pos] = 1.0;\n  double total_es = 0.0;\n  for (int t = 0; t < L; ++t) {\n    char ch = path_str[t];\n    vector<double> next_prob(N, 0.0);\n    double arr_this = 0.0;\n    for (int ps = 0; ps < N; ++ps) {\n      double pr = curr_prob[ps];\n      if (pr < 1e-12) continue;\n      // forget: stay\n      int stay_pos = ps;\n      if (stay_pos == target_pos) {\n        arr_this += pr * forget_p;\n      } else {\n        next_prob[stay_pos] += pr * forget_p;\n      }\n      // move\n      int move_pos = attempt_move(ps, ch, h_walls, v_walls);\n      if (move_pos == target_pos) {\n        arr_this += pr * (1.0 - forget_p);\n      } else {\n        next_prob[move_pos] += pr * (1.0 - forget_p);\n      }\n    }\n    total_es += arr_this * (401.0 - (t + 1));\n    curr_prob = std::move(next_prob);\n  }\n  return total_es;\n}\n\nstruct Cand {\n  string path;\n  double es;\n  bool operator>(const Cand& o) const { return es > o.es; }\n};\n\nint main() {\n  int si, sj, ti, tj;\n  double forget_p;\n  cin >> si >> sj >> ti >> tj >> forget_p;\n  vector<string> h_walls(20);\n  for (auto& s : h_walls) cin >> s;\n  vector<string> v_walls(19);\n  for (auto& s : v_walls) cin >> s;\n  int start_pos = si * COLS + sj;\n  int target_pos = ti * COLS + tj;\n  if (start_pos == target_pos) {\n    cout << \"\" << endl;\n    return 0;\n  }\n\n  // More biased shortest paths\n  vector<string> dir_orders = {\n    \"DRUL\", \"RDUL\", \"DDRR\", \"RRDD\", \"DRDR\", \"UDLR\"\n  };\n  vector<string> base_paths;\n  string sp_all = shortest_path(start_pos, target_pos, h_walls, v_walls, \"UDLR\");\n  base_paths.push_back(sp_all);\n  for (const string& order : dir_orders) {\n    string sp = shortest_path(start_pos, target_pos, h_walls, v_walls, order);\n    if (!sp.empty() && find(base_paths.begin(), base_paths.end(), sp) == base_paths.end()) {\n      base_paths.push_back(sp);\n    }\n  }\n\n  // Adaptive repeats/cycles\n  int max_rpm = max(5, (int)(4.0 / (1.0 - forget_p) + 1));\n  set<string> seen_paths;  // Dedup\n  vector<Cand> candidates;\n  for (const string& bsp : base_paths) {\n    size_t blen = bsp.size();\n    if (blen == 0 || blen > 50) continue;  // Skip invalid/long\n    // Singles\n    double es_single = evaluate(bsp, forget_p, start_pos, target_pos, h_walls, v_walls);\n    candidates.push_back({bsp, es_single});\n    seen_paths.insert(bsp);\n    // Per-move repeats\n    for (int rpm = 2; rpm <= max_rpm; ++rpm) {\n      string cand;\n      cand.reserve(blen * rpm);\n      bool too_long = false;\n      for (char ch : bsp) {\n        if (cand.size() + size_t(rpm) > 200u) {\n          too_long = true;\n          break;\n        }\n        cand.append(size_t(rpm), ch);\n      }\n      if (too_long || cand.empty()) continue;\n      if (seen_paths.count(cand)) continue;\n      double esc = evaluate(cand, forget_p, start_pos, target_pos, h_walls, v_walls);\n      candidates.push_back({cand, esc});\n      seen_paths.insert(cand);\n    }\n    // Path cycles\n    for (int cycles = 2; cycles <= 6; ++cycles) {\n      size_t tlen = blen * cycles;\n      if (tlen > 200) break;\n      string cand;\n      cand.reserve(tlen);\n      for (int i = 0; i < cycles; ++i) {\n        cand += bsp;\n      }\n      if (seen_paths.count(cand)) continue;\n      double esc = evaluate(cand, forget_p, start_pos, target_pos, h_walls, v_walls);\n      candidates.push_back({cand, esc});\n      seen_paths.insert(cand);\n    }\n  }\n\n  // Top candidate\n  sort(candidates.begin(), candidates.end(), greater<Cand>());\n  string best = candidates[0].path;\n  cout << best << endl;\n  return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nconst int N = 30;\nconst int NN = N * N;\nconst int SZ = NN * 4;\nint di[4] = {0, -1, 0, 1};\nint dj[4] = {-1, 0, 1, 0};\nint TO[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\nint next_tile[8] = {1, 2, 3, 0, 5, 4, 7, 6};\nbool conn[8][4];\n\nint P_IDX[SZ];\nint P_TIME[SZ];\n\nvoid precompute_conn() {\n    memset(conn, 0, sizeof(conn));\n    for (int t = 0; t < 8; t++) {\n        for (int din = 0; din < 4; din++) {\n            int d2 = TO[t][din];\n            if (d2 != -1) conn[t][d2] = true;\n        }\n    }\n}\n\nvector<int> get_cycles(const vector<int>& succ) {\n    vector<int> res;\n    vector<bool> visited(SZ, false);\n    int ts = 0;\n    for (int start = 0; start < SZ; start++) {\n        if (visited[start] || succ[start] == -1) continue;\n        ts++;\n        int cur = start;\n        int pathlen = 0;\n        while (true) {\n            visited[cur] = true;\n            P_IDX[cur] = pathlen++;\n            P_TIME[cur] = ts;\n            int nxt = succ[cur];\n            if (nxt == -1) break;\n            if (P_TIME[nxt] == ts) {\n                int clen = pathlen - P_IDX[nxt];\n                if (clen >= 4) res.push_back(clen);\n                break;\n            }\n            cur = nxt;\n            if (pathlen > SZ) break;\n        }\n    }\n    return res;\n}\n\nll compute_score(const vector<vector<int>>& rot, const vector<vector<int>>& orig, const vector<vector<int>>& eff) {\n    vector<vector<int>> tiles(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = eff[orig[i][j]][rot[i][j]];\n        }\n    }\n    vector<int> succ(SZ, -1);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            for (int d = 0; d < 4; d++) {\n                int tid = (i * N + j) * 4 + d;\n                int d2 = TO[tiles[i][j]][d];\n                if (d2 == -1) continue;\n                int ni = i + di[d2];\n                int nj = j + dj[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) % 4;\n                int nid = (ni * N + nj) * 4 + nd;\n                succ[tid] = nid;\n            }\n        }\n    }\n    vector<int> cycles = get_cycles(succ);\n    if (cycles.size() < 2) return 0;\n    sort(cycles.rbegin(), cycles.rend());\n    return (ll)cycles[0] * cycles[1];\n}\n\nvector<vector<int>> do_local_opt(vector<vector<int>> rot, const vector<vector<int>>& orig, const vector<vector<int>>& eff,\n                                 const vector<vector<bool>>& active, mt19937& rng) {\n    vector<vector<int>> tiles(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = eff[orig[i][j]][rot[i][j]];\n        }\n    }\n    vector<pair<int, int>> actives;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (active[i][j]) actives.emplace_back(i, j);\n        }\n    }\n    bool improved = true;\n    int iters = 0;\n    while (improved && iters++ < 200) {\n        shuffle(actives.begin(), actives.end(), rng);\n        improved = false;\n        for (auto [i, j] : actives) {\n            int ot = orig[i][j];\n            int curr = rot[i][j];\n            int best_sc = -1;\n            int best_r = curr;\n            for (int tr = 0; tr < 4; tr++) {\n                int tt = eff[ot][tr];\n                int lsc = 0;\n                for (int dd = 0; dd < 4; dd++) {\n                    int ni = i + di[dd];\n                    int nj = j + dj[dd];\n                    if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                    int opp = (dd + 2) % 4;\n                    int nt = tiles[ni][nj];\n                    if (conn[tt][dd] && conn[nt][opp]) lsc++;\n                }\n                if (lsc > best_sc || (lsc == best_sc && tr < best_r)) {\n                    best_sc = lsc;\n                    best_r = tr;\n                }\n            }\n            if (best_r != curr) {\n                rot[i][j] = best_r;\n                tiles[i][j] = eff[ot][best_r];\n                improved = true;\n            }\n        }\n    }\n    return rot;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    precompute_conn();\n    vector<vector<int>> eff(8, vector<int>(4));\n    for (int t = 0; t < 8; t++) {\n        for (int r = 0; r < 4; r++) {\n            int tt = t;\n            for (int k = 0; k < r; k++) tt = next_tile[tt];\n            eff[t][r] = tt;\n        }\n    }\n    vector<vector<int>> orig(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            orig[i][j] = s[j] - '0';\n        }\n    }\n    vector<vector<int>> best_rot(N, vector<int>(N, 0));\n    ll best_score = -1LL;\n    auto try_config = [&](const vector<vector<int>>& rot) {\n        ll sc = compute_score(rot, orig, eff);\n        if (sc > best_score) {\n            best_score = sc;\n            best_rot = rot;\n        }\n    };\n    vector<vector<bool>> active(N, vector<bool>(N, true));\n    const int NUM_TRIALS = 2048;\n    for (int tr = 0; tr < NUM_TRIALS; tr++) {\n        vector<vector<int>> rot_rand(N, vector<int>(N));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                rot_rand[i][j] = uniform_int_distribution<int>(0, 3)(rng);\n            }\n        }\n        auto rot_opt = do_local_opt(rot_rand, orig, eff, active, rng);\n        try_config(rot_opt);\n    }\n    // All uniform rots\n    for (int k = 0; k < 4; k++) {\n        vector<vector<int>> rot_uni(N, vector<int>(N, k));\n        auto rot_opt = do_local_opt(rot_uni, orig, eff, active, rng);\n        try_config(rot_opt);\n    }\n    // Vertical splits\n    vector<int> vsplits = {10, 12, 15, 18, 20};\n    for (int sp : vsplits) {\n        vector<vector<bool>> act_left(N, vector<bool>(N, false));\n        for (int i = 0; i < N; i++) for (int j = 0; j < sp; j++) act_left[i][j] = true;\n        vector<vector<int>> rot_left(N, vector<int>(N, 0));\n        for (int i = 0; i < N; i++) for (int j = 0; j < sp; j++) rot_left[i][j] = uniform_int_distribution<int>(0, 3)(rng);\n        rot_left = do_local_opt(rot_left, orig, eff, act_left, rng);\n        vector<vector<bool>> act_right(N, vector<bool>(N, false));\n        for (int i = 0; i < N; i++) for (int j = sp; j < N; j++) act_right[i][j] = true;\n        vector<vector<int>> rot_right(N, vector<int>(N, 0));\n        for (int i = 0; i < N; i++) for (int j = sp; j < N; j++) rot_right[i][j] = uniform_int_distribution<int>(0, 3)(rng);\n        rot_right = do_local_opt(rot_right, orig, eff, act_right, rng);\n        vector<vector<int>> rotc(N, vector<int>(N));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                rotc[i][j] = (j < sp ? rot_left[i][j] : rot_right[i][j]);\n            }\n        }\n        // Boundary opt\n        vector<vector<bool>> actb(N, vector<bool>(N, false));\n        if (sp > 0) for (int i = 0; i < N; i++) actb[i][sp - 1] = true;\n        for (int i = 0; i < N; i++) actb[i][sp] = true;\n        rotc = do_local_opt(rotc, orig, eff, actb, rng);\n        try_config(rotc);\n    }\n    // Horizontal splits (symmetric)\n    for (int sp : vsplits) {\n        vector<vector<bool>> act_top(N, vector<bool>(N, false));\n        for (int i = 0; i < sp; i++) for (int j = 0; j < N; j++) act_top[i][j] = true;\n        vector<vector<int>> rot_top(N, vector<int>(N, 0));\n        for (int i = 0; i < sp; i++) for (int j = 0; j < N; j++) rot_top[i][j] = uniform_int_distribution<int>(0, 3)(rng);\n        rot_top = do_local_opt(rot_top, orig, eff, act_top, rng);\n        vector<vector<bool>> act_bot(N, vector<bool>(N, false));\n        for (int i = sp; i < N; i++) for (int j = 0; j < N; j++) act_bot[i][j] = true;\n        vector<vector<int>> rot_bot(N, vector<int>(N, 0));\n        for (int i = sp; i < N; i++) for (int j = 0; j < N; j++) rot_bot[i][j] = uniform_int_distribution<int>(0, 3)(rng);\n        rot_bot = do_local_opt(rot_bot, orig, eff, act_bot, rng);\n        vector<vector<int>> rotc(N, vector<int>(N));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                rotc[i][j] = (i < sp ? rot_top[i][j] : rot_bot[i][j]);\n            }\n        }\n        // Boundary opt\n        vector<vector<bool>> actb(N, vector<bool>(N, false));\n        if (sp > 0) for (int j = 0; j < N; j++) actb[sp - 1][j] = true;\n        for (int j = 0; j < N; j++) actb[sp][j] = true;\n        rotc = do_local_opt(rotc, orig, eff, actb, rng);\n        try_config(rotc);\n    }\n    // Quadrants\n    int qsp = 15;\n    array<vector<vector<bool>>, 4> acts;\n    acts[0] = vector<vector<bool>>(N, vector<bool>(N, false)); // TL\n    acts[1] = vector<vector<bool>>(N, vector<bool>(N, false)); // TR\n    acts[2] = vector<vector<bool>>(N, vector<bool>(N, false)); // BL\n    acts[3] = vector<vector<bool>>(N, vector<bool>(N, false)); // BR\n    for (int qi = 0; qi < 4; qi++) {\n        int si = (qi / 2) * qsp;\n        int sj = (qi % 2) * qsp;\n        for (int i = si; i < si + qsp; i++) {\n            for (int j = sj; j < sj + qsp; j++) {\n                acts[qi][i][j] = true;\n            }\n        }\n    }\n    array<vector<vector<int>>, 4> rots_q;\n    for (int qi = 0; qi < 4; qi++) {\n        rots_q[qi] = vector<vector<int>>(N, vector<int>(N, 0));\n        int si = (qi / 2) * qsp;\n        int sj = (qi % 2) * qsp;\n        for (int i = si; i < si + qsp && i < N; i++) {\n            for (int j = sj; j < sj + qsp && j < N; j++) {\n                rots_q[qi][i][j] = uniform_int_distribution<int>(0, 3)(rng);\n            }\n        }\n        rots_q[qi] = do_local_opt(rots_q[qi], orig, eff, acts[qi], rng);\n    }\n    vector<vector<int>> rotq(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int qi = (i >= qsp ? 2 : 0) + (j >= qsp ? 1 : 0);\n            rotq[i][j] = rots_q[qi][i][j];\n        }\n    }\n    // Quadrant boundaries\n    vector<vector<bool>> actqb(N, vector<bool>(N, false));\n    for (int j = 0; j < N; j++) {\n        actqb[qsp - 1][j] = true;\n        actqb[qsp][j] = true;\n    }\n    for (int i = 0; i < N; i++) {\n        actqb[i][qsp - 1] = true;\n        actqb[i][qsp] = true;\n    }\n    rotq = do_local_opt(rotq, orig, eff, actqb, rng);\n    try_config(rotq);\n    // Final polish on best\n    best_rot = do_local_opt(best_rot, orig, eff, active, rng);\n    try_config(best_rot);\n    // Output\n    string ans = \"\";\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            ans += '0' + best_rot[i][j];\n        }\n    }\n    cout << ans << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint dx[4] = {-1, 1, 0, 0};\nint dy[4] = {0, 0, -1, 1};\nchar dc[4] = {'U', 'D', 'L', 'R'};\n\nint get_max_tree(const vector<vector<int>>& brd, int ex, int ey, int N) {\n  int emp_id = ex * N + ey;\n  int NN = N * N;\n  vector<vector<int>> adj(NN);\n  // vertical edges\n  for (int i = 0; i < N - 1; ++i) {\n    for (int j = 0; j < N; ++j) {\n      int id1 = i * N + j;\n      int id2 = (i + 1) * N + j;\n      if (id1 == emp_id || id2 == emp_id) continue;\n      int m1 = brd[i][j];\n      int m2 = brd[i + 1][j];\n      if ((m1 & 8) && (m2 & 2)) {\n        adj[id1].push_back(id2);\n        adj[id2].push_back(id1);\n      }\n    }\n  }\n  // horizontal edges\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N - 1; ++j) {\n      int id1 = i * N + j;\n      int id2 = i * N + j + 1;\n      if (id1 == emp_id || id2 == emp_id) continue;\n      int m1 = brd[i][j];\n      int m2 = brd[i][j + 1];\n      if ((m1 & 4) && (m2 & 1)) {\n        adj[id1].push_back(id2);\n        adj[id2].push_back(id1);\n      }\n    }\n  }\n  vector<char> vis(NN, 0);\n  vis[emp_id] = 1;\n  int maxt = 1;\n  for (int sid = 0; sid < NN; ++sid) {\n    if (vis[sid]) continue;\n    stack<int> st;\n    st.push(sid);\n    vis[sid] = 1;\n    int vv = 0;\n    int degsum = 0;\n    while (!st.empty()) {\n      int u = st.top();\n      st.pop();\n      ++vv;\n      degsum += adj[u].size();\n      for (int v : adj[u]) {\n        if (!vis[v]) {\n          vis[v] = 1;\n          st.push(v);\n        }\n      }\n    }\n    int ee = degsum / 2;\n    if (ee == vv - 1) {\n      maxt = max(maxt, vv);\n    }\n  }\n  return maxt;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  srand(time(nullptr));\n  int N;\n  long long T;\n  cin >> N >> T;\n  vector<vector<int>> orig_board(N, vector<int>(N));\n  int ox = -1, oy = -1;\n  for (int i = 0; i < N; ++i) {\n    string s;\n    cin >> s;\n    for (int j = 0; j < N; ++j) {\n      char ch = s[j];\n      int val = isdigit(ch) ? ch - '0' : 10 + (ch - 'a');\n      orig_board[i][j] = val;\n      if (val == 0) {\n        ox = i;\n        oy = j;\n      }\n    }\n  }\n  vector<vector<int>> board = orig_board;\n  int ex = ox, ey = oy;\n  int targetV = N * N - 1;\n  int cur_S = get_max_tree(board, ex, ey, N);\n  if (cur_S == targetV) {\n    cout << \"\" << endl;\n    return 0;\n  }\n  string ans;\n  double temp = 20.0;\n  double cool_rate = 0.999;\n  int max_total_steps = min(100000LL, 10LL * T);\n  int step = 0;\n  while (ans.size() < (size_t)T && step < max_total_steps) {\n    ++step;\n    vector<int> newS(4, -1);\n    vector<bool> can(4, false);\n    int ncan = 0;\n    for (int d = 0; d < 4; ++d) {\n      int nx = ex + dx[d];\n      int ny = ey + dy[d];\n      if (nx >= 0 && nx < N && ny >= 0 && ny < N) {\n        can[d] = true;\n        ++ncan;\n        int tile = board[nx][ny];\n        board[nx][ny] = 0;\n        board[ex][ey] = tile;\n        newS[d] = get_max_tree(board, nx, ny, N);\n        board[nx][ny] = tile;\n        board[ex][ey] = 0;\n      }\n    }\n    if (ncan == 0) break;\n    vector<double> probs(4, 0.0);\n    double sum_p = 0.0;\n    for (int d = 0; d < 4; ++d) {\n      if (can[d]) {\n        double delta = newS[d] - cur_S;\n        probs[d] = exp(delta / temp);\n        sum_p += probs[d];\n      }\n    }\n    double r = (double)rand() / RAND_MAX * sum_p;\n    double cum = 0.0;\n    int chd = -1;\n    for (int d = 0; d < 4; ++d) {\n      if (can[d]) {\n        cum += probs[d];\n        if (cum > r) {\n          chd = d;\n          break;\n        }\n      }\n    }\n    if (chd == -1) {\n      // fallback to best\n      int bestd = 0;\n      int bs = -1e9;\n      for (int d = 0; d < 4; ++d) {\n        if (can[d] && newS[d] > bs) {\n          bs = newS[d];\n          bestd = d;\n        }\n      }\n      chd = bestd;\n    }\n    // perform move\n    int nx = ex + dx[chd];\n    int ny = ey + dy[chd];\n    int tile = board[nx][ny];\n    board[nx][ny] = 0;\n    board[ex][ey] = tile;\n    ex = nx;\n    ey = ny;\n    ans += dc[chd];\n    cur_S = newS[chd];\n    if (cur_S == targetV) {\n      break;\n    }\n    temp *= cool_rate;\n    if (temp < 0.1) temp = 0.1;\n  }\n  cout << ans << endl;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Line {\n  ll px, py, qx, qy;\n};\n\nint side(const Line& l, ll x, ll y) {\n  ll dx1 = l.qx - l.px;\n  ll dy1 = l.qy - l.py;\n  ll dx2 = x - l.px;\n  ll dy2 = y - l.py;\n  __int128 cross = (__int128)dx1 * dy2 - (__int128)dy1 * dx2;\n  if (cross == 0) return 0;\n  return cross > 0 ? 1 : -1;\n}\n\ntuple<ll, ll, ll> exgcd(ll a, ll b) {\n  if (b == 0) return {a, 1, 0};\n  auto [g, x, y] = exgcd(b, a % b);\n  return {g, y, x - (a / b) * y};\n}\n\nint compute_current_score(const vector<vector<int>>& groups, const vector<int>& a) {\n  vector<int> b(11, 0);\n  for (const auto& g : groups) {\n    int sz = g.size();\n    if (sz >= 1 && sz <= 10) ++b[sz];\n  }\n  int sc = 0;\n  for (int d = 1; d <= 10; ++d) sc += min(a[d], b[d]);\n  return sc;\n}\n\nint eval_add(const Line& cand, const vector<vector<int>>& groups, const vector<pair<ll, ll>>& points, const vector<int>& a) {\n  vector<int> tent_b(11, 0);\n  for (const auto& grp : groups) {\n    int L = 0, R = 0;\n    for (int id : grp) {\n      int s = side(cand, points[id].first, points[id].second);\n      if (s == 1) ++L;\n      else if (s == -1) ++R;\n    }\n    if (L >= 1 && L <= 10) ++tent_b[L];\n    if (R >= 1 && R <= 10) ++tent_b[R];\n  }\n  int sc = 0;\n  for (int d = 1; d <= 10; ++d) sc += min(a[d], tent_b[d]);\n  return sc;\n}\n\nvoid add_line(vector<Line>& lines, vector<vector<int>>& groups, const vector<pair<ll, ll>>& points, const Line& newline) {\n  vector<vector<int>> newgroups;\n  newgroups.reserve(groups.size() * 2);\n  for (const auto& grp : groups) {\n    vector<int> left, right;\n    left.reserve(grp.size() / 2);\n    right.reserve(grp.size() / 2);\n    for (int id : grp) {\n      int s = side(newline, points[id].first, points[id].second);\n      if (s == 1) left.push_back(id);\n      else if (s == -1) right.push_back(id);\n    }\n    if (!left.empty()) newgroups.push_back(move(left));\n    if (!right.empty()) newgroups.push_back(move(right));\n  }\n  groups = move(newgroups);\n  lines.push_back(newline);\n}\n\nvector<Line> generate_cands(const vector<vector<int>>& groups, const vector<pair<ll, ll>>& points, uint64_t gseed) {\n  vector<pair<int, int>> large_groups;\n  large_groups.reserve(30);\n  for (int gi = 0; gi < (int)groups.size(); ++gi) {\n    int sz = groups[gi].size();\n    if (sz >= 2) large_groups.emplace_back(-sz, gi);\n  }\n  sort(large_groups.begin(), large_groups.end());\n  large_groups.resize(min(20, (int)large_groups.size()));\n\n  const int MAX_CANDS = 128;\n  vector<Line> cands;\n  cands.reserve(MAX_CANDS);\n  mt19937_64 global_rng(gseed);\n  for (auto [_, gi] : large_groups) {\n    if ((int)cands.size() >= MAX_CANDS) break;\n    const auto& grp = groups[gi];\n    int gsz = grp.size();\n    mt19937_64 rng(gi * 10007LL ^ global_rng());\n    int ngen = 35;\n    int range = 150;\n    for (int tr = 0; tr < ngen && (int)cands.size() < MAX_CANDS; ++tr) {\n      ll aa = (rng() % (2LL * range + 1)) - range;\n      ll bb = (rng() % (2LL * range + 1)) - range;\n      if (aa == 0 && bb == 0) continue;\n      ll gg = __gcd(abs(aa), abs(bb));\n      aa /= gg;\n      bb /= gg;\n      vector<pair<ll, int>> projs(gsz);\n      for (int j = 0; j < gsz; ++j) {\n        int id = grp[j];\n        ll x = points[id].first;\n        ll y = points[id].second;\n        projs[j].first = aa * x + bb * y;\n        projs[j].second = id;\n      }\n      sort(projs.begin(), projs.end());\n      int gm = min(10, gsz - 1);\n      for (int m = 1; m <= gm; ++m) {\n        if ((int)cands.size() >= MAX_CANDS) break;\n        ll ml = projs[m - 1].first;\n        ll mr = projs[m].first;\n        if (ml + 1 >= mr) continue;\n        ll kk = ml + 1;\n        auto [g, x0, y0] = exgcd(aa, bb);\n        if (g == 0 || kk % g != 0) continue;\n        if (g < 0) {\n          g = -g;\n          x0 = -x0;\n          y0 = -y0;\n        }\n        ll mul = kk / g;\n        ll xx = x0 * mul;\n        ll yy = y0 * mul;\n        ll ppx = xx;\n        ll ppy = yy;\n        ll qqx = ppx + bb;\n        ll qqy = ppy - aa;\n        if (abs(ppx) > 1000000000LL || abs(ppy) > 1000000000LL ||\n            abs(qqx) > 1000000000LL || abs(qqy) > 1000000000LL) continue;\n        if (ppx == qqx && ppy == qqy) continue;\n        cands.push_back({ppx, ppy, qqx, qqy});\n      }\n    }\n  }\n  return cands;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, K;\n  cin >> N >> K;\n  vector<int> a(11, 0);\n  int max_score = 0;\n  for (int d = 1; d <= 10; ++d) {\n    cin >> a[d];\n    max_score += a[d];\n  }\n  vector<pair<ll, ll>> points(N);\n  for (auto& p : points) {\n    cin >> p.first >> p.second;\n  }\n  const int num_restarts = 6;\n  vector<Line> best_sol;\n  int best_s = -1;\n  for (int rst = 0; rst < num_restarts; ++rst) {\n    vector<vector<int>> groups;\n    groups.reserve(4096);\n    groups.emplace_back(N);\n    iota(groups.back().begin(), groups.back().end(), 0);\n    vector<Line> curr_lines;\n    curr_lines.reserve(100);\n    uint64_t gseed = (uint64_t)rst * 1000000007ULL + 123456789ULL;\n    while (curr_lines.size() < (size_t)K) {\n      int current_sc = compute_current_score(groups, a);\n      if (current_sc == max_score || (int)groups.size() > 4000) break;\n      auto cands = generate_cands(groups, points, gseed ^ (uint64_t)curr_lines.size());\n      if (cands.empty()) break;\n      int best_new_sc = current_sc;\n      Line best_cand;\n      for (const auto& cand : cands) {\n        int nsc = eval_add(cand, groups, points, a);\n        if (nsc > best_new_sc) {\n          best_new_sc = nsc;\n          best_cand = cand;\n        }\n      }\n      if (best_new_sc <= current_sc) break;\n      add_line(curr_lines, groups, points, best_cand);\n    }\n    int this_s = compute_current_score(groups, a);\n    if (this_s > best_s) {\n      best_s = this_s;\n      best_sol = move(curr_lines);\n    }\n  }\n  cout << best_sol.size() << '\\n';\n  for (const auto& l : best_sol) {\n    cout << l.px << ' ' << l.py << ' ' << l.qx << ' ' << l.qy << '\\n';\n  }\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 64;\nconst int MAX_SIDE = 30;\nbool occupied[MAXN][MAXN];\nbool used_h[MAXN][MAXN];\nbool used_v[MAXN][MAXN];\nbool used_ne[MAXN][MAXN];\nbool used_nw[MAXN][MAXN];\nint N, c, M, num_occupied;\n\nstruct Move {\n    int x1,y1,x2,y2,x3,y3,x4,y4,rsize,area;\n    long long prio;\n};\n\nvector<Move> cands, ans_moves;\n\nlong long distsq(int x,int y){ long long dx=x-c,dy=y-c; return dx*dx+dy*dy+1; }\n\npair<int,int> getxy(int u,int v){ return {(u+v)/2,(u-v)/2}; }\n\nbool in_grid(int x,int y){ return x>=0&&x<N&&y>=0&&y<N; }\n\nbool check_clean(int x0,int y0,int x1,int y1){\n    int dx=x1-x0,dy=y1-y0,adx=abs(dx),ady=abs(dy);\n    if(adx==0&&ady==0)return false;\n    if(adx&&ady&&adx!=ady)return false;\n    int k=max(adx,ady),sx=dx>0?1:dx<0?-1:0,sy=dy>0?1:dy<0?-1:0;\n    for(int i=1;i<k;++i){\n        int xx=x0+i*sx,yy=y0+i*sy;\n        if(!in_grid(xx,yy)||occupied[xx][yy])return false;\n    }\n    for(int i=0;i<k;++i){\n        int x=x0+i*sx,y=y0+i*sy,nx=x+sx,ny=y+sy;\n        if(!in_grid(x,y)||!in_grid(nx,ny))return false;\n        int lx=min(x,nx),ly=x==lx?y:ny,ry=x==lx?ny:y;\n        if(sx==0){//vert\n            int by=min(y,ny);\n            if(by<0||by>=N-1||used_v[x][by])return false;\n        }else if(sy==0){//horiz\n            if(lx<0||lx>=N-1||used_h[y][lx])return false;\n        }else{//diag\n            if(ry==ly+1){//NE\n                if(lx<0||lx>=N-1||ly<0||ly>=N-1||used_ne[lx][ly])return false;\n            }else if(ry==ly-1){// NW\n                if(lx<0||lx>=N-1||ly<1||ly>=N||used_nw[lx][ly])return false;\n            }else return false;\n        }\n    }\n    return true;\n}\n\nvoid mark_side(int x0,int y0,int x1,int y1){\n    int dx=x1-x0,dy=y1-y0,adx=abs(dx),ady=abs(dy);\n    if(adx==0&&ady==0)return;\n    int k=max(adx,ady),sx=dx>0?1:dx<0?-1:0,sy=dy>0?1:dy<0?-1:0;\n    for(int i=0;i<k;++i){\n        int x=x0+i*sx,y=y0+i*sy,nx=x+sx,ny=y+sy;\n        int lx=min(x,nx),ly=x==lx?y:ny,ry=x==lx?ny:y;\n        if(sx==0){\n            int by=min(y,ny);\n            used_v[x][by]=true;\n        }else if(sy==0){\n            used_h[y][lx]=true;\n        }else{\n            if(ry==ly+1)used_ne[lx][ly]=true;\n            else if(ry==ly-1)used_nw[lx][ly]=true;\n        }\n    }\n}\n\nvoid scan_axis(){\n    cands.clear();\n    for(int w=1;w<=MAX_SIDE;++w)for(int xl=0;xl+w<N;++xl){\n        int xr=xl+w;\n        for(int h=1;h<=MAX_SIDE;++h)for(int yb=0;yb+h<N;++yb){\n            int yt=yb+h;\n            array<pair<int,int>,4> corns{{{xl,yb},{xr,yb},{xr,yt},{xl,yt}}};\n            int cnt=0;\n            for(auto [xx,yy]:corns)if(occupied[xx][yy])++cnt;\n            if(cnt!=3)continue;\n            int miss=-1;\n            for(int i=0;i<4;++i)if(!occupied[corns[i].first][corns[i].second]){miss=i;break;}\n            if(miss==-1|| !check_clean(corns[0].first,corns[0].second,corns[1].first,corns[1].second)||\n                       !check_clean(corns[1].first,corns[1].second,corns[2].first,corns[2].second)||\n                       !check_clean(corns[2].first,corns[2].second,corns[3].first,corns[3].second)||\n                       !check_clean(corns[3].first,corns[3].second,corns[0].first,corns[0].second))continue;\n            int i2=(miss+1)%4,i3=(miss+2)%4,i4=(miss+3)%4;\n            Move m;\n            m.x1=corns[miss].first;m.y1=corns[miss].second;\n            m.x2=corns[i2].first;m.y2=corns[i2].second;\n            m.x3=corns[i3].first;m.y3=corns[i3].second;\n            m.x4=corns[i4].first;m.y4=corns[i4].second;\n            m.rsize=w+h;m.area=w*h;m.prio=0;\n            cands.push_back(m);\n        }\n    }\n}\n\nvoid scan_45(int parity){\n    vector<int> us,vs;\n    for(int u=parity;u<=2*(N-1);u+=2)us.push_back(u);\n    int vmin=-(N-1),voff=parity?1:0;\n    for(int v=vmin+voff;v<=N-1;v+=2)vs.push_back(v);\n    for(size_t i=0;i<us.size();++i)for(size_t j=i+1;j<us.size();++j){\n        int u1=us[i],u2=us[j];\n        for(size_t k=0;k<vs.size();++k)for(size_t l=k+1;l<vs.size();++l){\n            int v1=vs[k],v2=vs[l];\n            auto [x0,y0]=getxy(u1,v1);if(!in_grid(x0,y0))continue;\n            auto [x1,y1]=getxy(u1,v2);if(!in_grid(x1,y1))continue;\n            auto [x2,y2]=getxy(u2,v2);if(!in_grid(x2,y2))continue;\n            auto [x3,y3]=getxy(u2,v1);if(!in_grid(x3,y3))continue;\n            array<pair<int,int>,4> corns{{{x0,y0},{x1,y1},{x2,y2},{x3,y3}}};\n            int cnt=0;\n            for(auto [xx,yy]:corns)if(occupied[xx][yy])++cnt;\n            if(cnt!=3)continue;\n            int miss=-1;\n            for(int p=0;p<4;++p)if(!occupied[corns[p].first][corns[p].second]){miss=p;break;}\n            if(miss==-1)continue;\n            if(!check_clean(x0,y0,x1,y1)||!check_clean(x1,y1,x2,y2)||\n               !check_clean(x2,y2,x3,y3)||!check_clean(x3,y3,x0,y0))continue;\n            int i2=(miss+1)%4,i3=(miss+2)%4,i4=(miss+3)%4;\n            int du=(u2-u1)/2,dv=abs(v2-v1)/2;\n            Move m;\n            m.x1=corns[miss].first;m.y1=corns[miss].second;\n            m.x2=corns[i2].first;m.y2=corns[i2].second;\n            m.x3=corns[i3].first;m.y3=corns[i3].second;\n            m.x4=corns[i4].first;m.y4=corns[i4].second;\n            m.rsize=du+dv;m.area=du*dv;m.prio=0;\n            cands.push_back(m);\n        }\n    }\n}\n\nint main(){\n    ios::sync_with_stdio(false);cin.tie(0);\n    clock_t clk=clock();\n    cin>>N>>M;c=(N-1)/2;num_occupied=M;\n    memset(occupied,0,sizeof(occupied));\n    memset(used_h,0,sizeof(used_h));memset(used_v,0,sizeof(used_v));\n    memset(used_ne,0,sizeof(used_ne));memset(used_nw,0,sizeof(used_nw));\n    for(int i=0;i<M;++i){int x,y;cin>>x>>y;occupied[x][y]=true;}\n    int phase=0,stalls=0,max_stalls=8;\n    while(true){\n        double t=(clock()-clk)/(double)CLOCKS_PER_SEC;\n        if(t>4.85||num_occupied>N*N*0.93||stalls>=max_stalls)break;\n        scan_axis();\n        scan_45(0);scan_45(1);\n        if(cands.empty()){++stalls;continue;}\n        auto cmp = [&](const Move& a,const Move& b){\n            long long da=distsq(a.x1,a.y1),db=distsq(b.x1,b.y1);\n            long long sa=a.rsize,sb=b.rsize;\n            long long pra=sa*sa + 1000000000LL/(sa+1);\n            long long prb=sb*sb + 1000000000LL/(sb+1);\n            bool outer=phase%2==0,large=(phase/2)%2==0;\n            long long pa=(outer?da:-da)*100LL + (large?pra:-pra)*10LL + a.area;\n            long long pb=(outer?db:-db)*100LL + (large?prb:-prb)*10LL + b.area;\n            return pa > pb;\n        };\n        sort(cands.begin(),cands.end(),cmp);\n        int added=0,topk=min(8192,(int)cands.size());\n        for(int i=0;i<topk;++i){\n            const auto& m=cands[i];\n            double t2=(clock()-clk)/(double)CLOCKS_PER_SEC;if(t2>4.9)break;\n            if(occupied[m.x1][m.y1])continue;\n            if(check_clean(m.x1,m.y1,m.x2,m.y2)&&check_clean(m.x2,m.y2,m.x3,m.y3)&&\n               check_clean(m.x3,m.y3,m.x4,m.y4)&&check_clean(m.x4,m.y4,m.x1,m.y1)){\n                ans_moves.push_back(m);\n                occupied[m.x1][m.y1]=true;\n                mark_side(m.x1,m.y1,m.x2,m.y2);\n                mark_side(m.x2,m.y2,m.x3,m.y3);\n                mark_side(m.x3,m.y3,m.x4,m.y4);\n                mark_side(m.x4,m.y4,m.x1,m.y1);\n                ++num_occupied;++added;\n            }\n        }\n        if(added==0){++stalls;phase=(phase+1)%4;}\n        else stalls=0;\n    }\n    cout<<ans_moves.size()<<'\\n';\n    for(auto& m:ans_moves){\n        cout<<m.x1<<' '<<m.y1<<' '<<m.x2<<' '<<m.y2<<' '<<m.x3<<' '<<m.y3<<' '<<m.x4<<' '<<m.y4<<'\\n';\n    }\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int, int>;\nusing vv = vector<vector<int>>;\n\npair<int, int> get_new_pos(const vv& g, int pr, int pc, char dir) {\n    int nr = pr, nc = pc;\n    if (dir == 'L') {\n        int rank_left = 0;\n        for (int c = 0; c < pc; ++c) if (g[pr][c] != 0) ++rank_left;\n        nc = rank_left;\n    } else if (dir == 'R') {\n        int total = 0;\n        for (int c = 0; c < 10; ++c) if (g[pr][c] != 0) ++total;\n        int rank_left = 0;\n        for (int c = 0; c < pc; ++c) if (g[pr][c] != 0) ++rank_left;\n        nc = (10 - total) + rank_left;\n    } else if (dir == 'F') {\n        int rank_top = 0;\n        for (int r = 0; r < pr; ++r) if (g[r][pc] != 0) ++rank_top;\n        nr = rank_top;\n    } else if (dir == 'B') {\n        int total = 0;\n        for (int r = 0; r < 10; ++r) if (g[r][pc] != 0) ++total;\n        int rank_top = 0;\n        for (int r = 0; r < pr; ++r) if (g[r][pc] != 0) ++rank_top;\n        nr = (10 - total) + rank_top;\n    }\n    return {nr, nc};\n}\n\nvoid simulate(vv& g, char dir) {\n    if (dir == 'F') {\n        for (int c = 0; c < 10; ++c) {\n            vector<int> lis;\n            for (int r = 0; r < 10; ++r) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            for (int r = 0; r < sz; ++r) g[r][c] = lis[r];\n            for (int r = sz; r < 10; ++r) g[r][c] = 0;\n        }\n    } else if (dir == 'B') {\n        for (int c = 0; c < 10; ++c) {\n            vector<int> lis;\n            for (int r = 0; r < 10; ++r) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            int off = 10 - sz;\n            for (int r = 0; r < off; ++r) g[r][c] = 0;\n            for (int r = 0; r < sz; ++r) g[off + r][c] = lis[r];\n        }\n    } else if (dir == 'L') {\n        for (int r = 0; r < 10; ++r) {\n            vector<int> lis;\n            for (int c = 0; c < 10; ++c) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            for (int c = 0; c < sz; ++c) g[r][c] = lis[c];\n            for (int c = sz; c < 10; ++c) g[r][c] = 0;\n        }\n    } else if (dir == 'R') {\n        for (int r = 0; r < 10; ++r) {\n            vector<int> lis;\n            for (int c = 0; c < 10; ++c) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            int off = 10 - sz;\n            for (int c = 0; c < off; ++c) g[r][c] = 0;\n            for (int c = 0; c < sz; ++c) g[r][off + c] = lis[c];\n        }\n    }\n}\n\nlong long compute(const vv& g) {\n    bool vis[10][10] = {};\n    int dr[] = {-1, 0, 1, 0};\n    int dc[] = {0, 1, 0, -1};\n    long long sumsq = 0;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            if (g[r][c] != 0 && !vis[r][c]) {\n                int flav = g[r][c];\n                queue<pii> q;\n                q.emplace(r, c);\n                vis[r][c] = true;\n                int sz = 1;\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    for (int d = 0; d < 4; ++d) {\n                        int nr = x + dr[d];\n                        int nc = y + dc[d];\n                        if (nr >= 0 && nr < 10 && nc >= 0 && nc < 10 &&\n                            !vis[nr][nc] && g[nr][nc] == flav) {\n                            vis[nr][nc] = true;\n                            q.emplace(nr, nc);\n                            ++sz;\n                        }\n                    }\n                }\n                sumsq += 1LL * sz * sz;\n            }\n        }\n    }\n    return sumsq;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    vector<int> f(101);\n    for (int i = 1; i <= 100; ++i) {\n        cin >> f[i];\n    }\n    vv grid(10, vector<int>(10, 0));\n    set<pii> empties;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            empties.emplace(r, c);\n        }\n    }\n    string dirs = \"FBLR\";\n    int dr[] = {-1, 0, 1, 0};\n    int dc[] = {0, 1, 0, -1};\n    for (int t = 1; t <= 100; ++t) {\n        int p;\n        cin >> p;\n        auto it = empties.begin();\n        advance(it, p - 1);\n        auto [pr, pc] = *it;\n        grid[pr][pc] = f[t];\n        empties.erase(it);\n        int flav = f[t];\n\n        long long best_sc = -1;\n        int best_md = 999;\n        int best_pot = -1;\n        int best_dc = 999;\n        char best_dir = 'Z';\n        for (char d : dirs) {\n            vv temp = grid;\n            simulate(temp, d);\n            long long sc = compute(temp);\n            auto [nr, nc] = get_new_pos(grid, pr, pc, d);\n\n            // min dist to nearest other same\n            int mind = 11;\n            for (int i = 0; i < 10; ++i) {\n                for (int j = 0; j < 10; ++j) {\n                    if (temp[i][j] == flav && (i != nr || j != nc)) {\n                        int dd = abs(i - nr) + abs(j - nc);\n                        if (dd < mind) mind = dd;\n                    }\n                }\n            }\n\n            // line potential and CoM\n            vector<int> rowc(10, 0), colc(10, 0);\n            int sumr = 0, sumc_ = 0, num = 0;\n            for (int i = 0; i < 10; ++i) {\n                for (int j = 0; j < 10; ++j) {\n                    if (temp[i][j] == flav) {\n                        rowc[i]++;\n                        colc[j]++;\n                        sumr += i;\n                        sumc_ += j;\n                        num++;\n                    }\n                }\n            }\n            int pot = rowc[nr] + colc[nc] - 2;\n            int meanr = (num == 0 ? nr : sumr / num);\n            int meanc = (num == 0 ? nc : sumc_ / num);\n            int distc = abs(nr - meanr) + abs(nc - meanc);\n\n            // compare\n            bool better = false;\n            if (sc > best_sc) better = true;\n            else if (sc == best_sc) {\n                if (mind < best_md) better = true;\n                else if (mind == best_md) {\n                    if (pot > best_pot) better = true;\n                    else if (pot == best_pot) {\n                        if (distc < best_dc) better = true;\n                        else if (distc == best_dc) {\n                            if (d < best_dir) better = true;\n                        }\n                    }\n                }\n            }\n            if (better) {\n                best_sc = sc;\n                best_md = mind;\n                best_pot = pot;\n                best_dc = distc;\n                best_dir = d;\n            }\n        }\n        cout << best_dir << endl;\n        simulate(grid, best_dir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <limits>\nusing namespace std;\n\nusing Eigen::MatrixXd;\nusing Eigen::SelfAdjointEigenSolver;\nusing Eigen::VectorXd;\n\nusing Feature = vector<double>;\n\nint tri_index(int N, int i, int j) {\n  if (i > j) swap(i, j);\n  int pos = 0;\n  for (int a = 0; a < i; ++a) {\n    pos += N - 1 - a;\n  }\n  pos += j - i - 1;\n  return pos;\n}\n\nstring make_clique(int s, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  s = min(s, N);\n  for (int i = 0; i < s; ++i) {\n    for (int j = i + 1; j < s; ++j) {\n      g[tri_index(N, i, j)] = '1';\n    }\n  }\n  return g;\n}\n\nstring make_star(int leaves, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  leaves = min(leaves, N - 1);\n  for (int lv = 1; lv <= leaves; ++lv) {\n    g[tri_index(N, 0, lv)] = '1';\n  }\n  return g;\n}\n\nstring make_bipart(int a, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  a = min(a, N / 2);\n  int left = a;\n  for (int i = 0; i < left; ++i) {\n    for (int jj = 0; jj < N - left; ++jj) {\n      int j = left + jj;\n      g[tri_index(N, i, j)] = '1';\n    }\n  }\n  return g;\n}\n\nstring make_path(int s, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  s = min(s, N);\n  for (int i = 0; i < s - 1; ++i) {\n    g[tri_index(N, i, i + 1)] = '1';\n  }\n  return g;\n}\n\nstring make_cycle(int c, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  c = min(c, N);\n  if (c < 3) return make_path(c, N);\n  for (int i = 0; i < c; ++i) {\n    int j = (i + 1) % c;\n    g[tri_index(N, i, j)] = '1';\n  }\n  return g;\n}\n\nstring make_wheel(int rim, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  rim = min(rim, N - 1);\n  int hub = 0;\n  // hub to rim\n  for (int i = 1; i <= rim; ++i) {\n    g[tri_index(N, hub, i)] = '1';\n  }\n  // rim cycle\n  if (rim >= 2) {\n    for (int i = 1; i < rim; ++i) {\n      g[tri_index(N, i, i + 1)] = '1';\n    }\n    g[tri_index(N, rim, 1)] = '1';\n  }\n  return g;\n}\n\nFeature get_feature(const string& s, int N, double flip_prob) {\n  int B = N * (N - 1) / 2;\n  assert((int)s.size() == B);\n  MatrixXd A(N, N);\n  A.setZero();\n  double denom = 1.0 - 2.0 * flip_prob;\n  bool denoise = (flip_prob > 1e-12);\n  for (int i = 0; i < N; ++i) {\n    for (int j = i + 1; j < N; ++j) {\n      double val_obs = s[tri_index(N, i, j)] - '0';\n      double val = denoise ? (val_obs - flip_prob) / denom : val_obs;\n      A(i, j) = val;\n      A(j, i) = val;\n    }\n  }\n  // Adjacency eigenvalues\n  SelfAdjointEigenSolver<MatrixXd> solverA(A);\n  VectorXd evA = solverA.eigenvalues();\n  vector<double> lambdaA(N);\n  for (int k = 0; k < N; ++k) lambdaA[k] = evA(k);\n  sort(lambdaA.rbegin(), lambdaA.rend());\n\n  // Sorted degrees descending\n  VectorXd deg = A.rowwise().sum();\n  vector<double> sdeg(N);\n  for (int k = 0; k < N; ++k) sdeg[k] = deg(k);\n  sort(sdeg.rbegin(), sdeg.rend());\n\n  // Laplacian eigenvalues\n  MatrixXd L(N, N);\n  L.setZero();\n  L.diagonal() = deg;\n  L -= A;\n  SelfAdjointEigenSolver<MatrixXd> solverL(L);\n  VectorXd evL = solverL.eigenvalues();\n  vector<double> lambdaL(N);\n  for (int k = 0; k < N; ++k) lambdaL[k] = evL(k);\n  sort(lambdaL.rbegin(), lambdaL.rend());\n\n  // Concatenate\n  Feature feat;\n  feat.reserve(3 * N);\n  feat.insert(feat.end(), lambdaA.begin(), lambdaA.end());\n  feat.insert(feat.end(), sdeg.begin(), sdeg.end());\n  feat.insert(feat.end(), lambdaL.begin(), lambdaL.end());\n  return feat;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n  int M;\n  double eps;\n  cin >> M >> eps;\n  int N = min(100, max(4, (int)(20 + 80 * (1 - eps))));\n  cout << N << '\\n';\n\n  vector<string> cand_repr;\n  vector<Feature> cand_feat;\n  auto add_cand = [&](const string& g) {\n    cand_repr.push_back(g);\n    cand_feat.push_back(get_feature(g, N, 0.0));\n  };\n  // Cliques\n  for (int s = 1; s <= N; ++s) {\n    add_cand(make_clique(s, N));\n  }\n  // Stars\n  for (int l = 1; l < N; ++l) {\n    add_cand(make_star(l, N));\n  }\n  // Bipartites\n  for (int a = 1; a <= N / 2; ++a) {\n    add_cand(make_bipart(a, N));\n  }\n  // Paths\n  for (int s = 2; s <= N; ++s) {\n    add_cand(make_path(s, N));\n  }\n  // Cycles\n  for (int c = 3; c <= N; ++c) {\n    add_cand(make_cycle(c, N));\n  }\n  // Wheels\n  for (int rim = 3; rim < N; ++rim) {\n    add_cand(make_wheel(rim, N));\n  }\n  int nc = cand_feat.size();\n  vector<bool> used(nc, false);\n  vector<int> chosen;\n  for (int ck = 0; ck < M; ++ck) {\n    int best_ci = -1;\n    double max_mind = -numeric_limits<double>::infinity();\n    for (int ci = 0; ci < nc; ++ci) {\n      if (used[ci]) continue;\n      double mind = numeric_limits<double>::infinity();\n      for (int pi : chosen) {\n        double dd = 0.0;\n        const auto& f1 = cand_feat[ci];\n        const auto& f2 = cand_feat[pi];\n        for (size_t j = 0; j < f1.size(); ++j) {\n          double dif = f1[j] - f2[j];\n          dd += dif * dif;\n        }\n        mind = min(mind, dd);\n      }\n      if (mind > max_mind) {\n        max_mind = mind;\n        best_ci = ci;\n      }\n    }\n    assert(best_ci != -1);\n    used[best_ci] = true;\n    chosen.push_back(best_ci);\n  }\n\n  vector<Feature> codebook_feat(M);\n  for (int k = 0; k < M; ++k) {\n    int ci = chosen[k];\n    cout << cand_repr[ci] << '\\n';\n    codebook_feat[k] = cand_feat[ci];\n  }\n  cout << std::flush;\n\n  for (int q = 0; q < 100; ++q) {\n    string H;\n    cin >> H;\n    Feature fh = get_feature(H, N, eps);\n    double best_d = numeric_limits<double>::infinity();\n    int tk = 0;\n    for (int k = 0; k < M; ++k) {\n      double dd = 0.0;\n      const auto& fk = codebook_feat[k];\n      for (size_t j = 0; j < fh.size(); ++j) {\n        double dif = fh[j] - fk[j];\n        dd += dif * dif;\n      }\n      if (dd < best_d) {\n        best_d = dd;\n        tk = k;\n      }\n    }\n    cout << tk << '\\n' << std::flush;\n  }\n  return 0;\n}","ahc017":"","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Rod {\n    int x, y, zs, len;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int D;\n    cin >> D;\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            cin >> f[i][z];\n        }\n        for (int z = 0; z < D; ++z) {\n            cin >> r[i][z];\n        }\n    }\n    const int N = D * D;\n    const int VOL = D * D * D;\n    bitset<196> remain_front[2], remain_right[2];\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) {\n            for (int k = 0; k < D; ++k) {\n                if (f[i][z][k] == '1') remain_front[i][z * D + k] = 1;\n                if (r[i][z][k] == '1') remain_right[i][z * D + k] = 1;\n            }\n        }\n    }\n    vector<Rod> rods;\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            bitset<16> comz;\n            for (int z = 0; z < D; ++z) {\n                bool p0 = (f[0][z][x] == '1' && r[0][z][y] == '1');\n                bool p1 = (f[1][z][x] == '1' && r[1][z][y] == '1');\n                if (p0 && p1) comz[z] = 1;\n            }\n            int pos = 0;\n            while (pos < D) {\n                if (!comz[pos]) {\n                    ++pos;\n                    continue;\n                }\n                int st = pos;\n                while (pos < D && comz[pos]) ++pos;\n                rods.push_back({x, y, st, pos - st});\n            }\n        }\n    }\n    sort(rods.begin(), rods.end(), [](const Rod& a, const Rod& b) {\n        return a.len > b.len;\n    });\n    vector<vector<int>> bb(2, vector<int>(VOL, 0));\n    int block_id = 1;\n    for (auto& rod : rods) {\n        int x = rod.x, y = rod.y, zs = rod.zs, ln = rod.len;\n        bool can = true;\n        for (int dz = 0; dz < ln; ++dz) {\n            int z = zs + dz;\n            int fx = z * D + x;\n            int ry_ = z * D + y;\n            if (!remain_front[0][fx] || !remain_front[1][fx] ||\n                !remain_right[0][ry_] || !remain_right[1][ry_]) {\n                can = false;\n                break;\n            }\n        }\n        if (!can) continue;\n        for (int dz = 0; dz < ln; ++dz) {\n            int z = zs + dz;\n            int idx = x * D * D + y * D + z;\n            bb[0][idx] = block_id;\n            bb[1][idx] = block_id;\n            int fx = z * D + x;\n            int ry_ = z * D + y;\n            remain_front[0][fx] = 0;\n            remain_front[1][fx] = 0;\n            remain_right[0][ry_] = 0;\n            remain_right[1][ry_] = 0;\n        }\n        ++block_id;\n    }\n    // Now remaining 1x1 sharing\n    using p3 = array<int, 3>;\n    vector<p3> poss_rem[2];\n    for (int i = 0; i < 2; ++i) {\n        poss_rem[i].clear();\n        for (int z = 0; z < D; ++z) {\n            vector<int> rem_rx, rem_ry, orig_rx, orig_ry;\n            for (int k = 0; k < D; ++k) {\n                if (remain_front[i][z * D + k]) rem_rx.push_back(k);\n                if (f[i][z][k] == '1') orig_rx.push_back(k);\n                if (remain_right[i][z * D + k]) rem_ry.push_back(k);\n                if (r[i][z][k] == '1') orig_ry.push_back(k);\n            }\n            int nrx = rem_rx.size();\n            int nry = rem_ry.size();\n            if (nrx == 0 && nry == 0) continue;\n            if (nrx >= nry) {\n                // pair nry\n                for (int j = 0; j < nry; ++j) {\n                    int px = rem_rx[j], py = rem_ry[j];\n                    poss_rem[i].push_back({px, py, z});\n                }\n                // extras nrx - nry\n                if (!orig_ry.empty()) {\n                    int py0 = orig_ry[0];\n                    for (int j = nry; j < nrx; ++j) {\n                        int px = rem_rx[j];\n                        poss_rem[i].push_back({px, py0, z});\n                    }\n                }\n            } else {\n                // pair nrx\n                for (int j = 0; j < nrx; ++j) {\n                    int px = rem_rx[j], py = rem_ry[j];\n                    poss_rem[i].push_back({px, py, z});\n                }\n                // extras nry - nrx\n                int px0;\n                if (!rem_rx.empty()) {\n                    px0 = rem_rx[0];\n                } else if (!orig_rx.empty()) {\n                    px0 = orig_rx[0];\n                } else {\n                    continue;\n                }\n                for (int j = nrx; j < nry; ++j) {\n                    int py = rem_ry[j];\n                    poss_rem[i].push_back({px0, py, z});\n                }\n            }\n        }\n    }\n    size_t rem_sz0 = poss_rem[0].size();\n    size_t rem_sz1 = poss_rem[1].size();\n    size_t min_rem = min(rem_sz0, rem_sz1);\n    for (size_t j = 0; j < min_rem; ++j) {\n        auto [x0, y0, z0] = poss_rem[0][j];\n        int idx0 = x0 * D * D + y0 * D + z0;\n        bb[0][idx0] = block_id;\n        auto [x1, y1, z1] = poss_rem[1][j];\n        int idx1 = x1 * D * D + y1 * D + z1;\n        bb[1][idx1] = block_id;\n        ++block_id;\n    }\n    // extras\n    if (rem_sz0 > rem_sz1) {\n        for (size_t j = min_rem; j < rem_sz0; ++j) {\n            auto [x, y, z] = poss_rem[0][j];\n            int idx = x * D * D + y * D + z;\n            bb[0][idx] = block_id++;\n        }\n    } else if (rem_sz1 > rem_sz0) {\n        for (size_t j = min_rem; j < rem_sz1; ++j) {\n            auto [x, y, z] = poss_rem[1][j];\n            int idx = x * D * D + y * D + z;\n            bb[1][idx] = block_id++;\n        }\n    }\n    int n = block_id - 1;\n    cout << n << '\\n';\n    for (int i = 0; i < 2; ++i) {\n        for (int j = 0; j < VOL; ++j) {\n            if (j > 0) cout << ' ';\n            cout << bb[i][j];\n        }\n        cout << '\\n';\n    }\n    return 0;\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint calc_p(ll d2) {\n    if (d2 == 0) return 0;\n    double sd = sqrt((double)d2);\n    int p = (int)ceil(sd);\n    while ((ll)p * p < d2 && p < 5000) ++p;\n    return min(5000, p);\n}\n\nstruct Edge {\n    int u, v, id;\n    ll w;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    cin >> N >> M >> K;\n    vector<ll> xs(N + 1), ys(N + 1);\n    for (int i = 1; i <= N; ++i) {\n        cin >> xs[i] >> ys[i];\n    }\n    vector<Edge> edgs(M);\n    for (int j = 0; j < M; ++j) {\n        int u, v;\n        ll w;\n        cin >> u >> v >> w;\n        edgs[j] = {u, v, j + 1, w};\n    }\n    vector<ll> as(K + 1), bs(K + 1);\n    for (int k = 1; k <= K; ++k) {\n        cin >> as[k] >> bs[k];\n    }\n    // adj: {nei, eid}\n    vector<vector<pair<int, int>>> adj(N + 1);\n    for (int j = 0; j < M; ++j) {\n        int u = edgs[j].u, v = edgs[j].v, eid = edgs[j].id;\n        adj[u].emplace_back(v, eid);\n        adj[v].emplace_back(u, eid);\n    }\n    // distsq\n    const ll INF_LL = 9e18 / 2;\n    vector<vector<ll>> distsq(N + 1, vector<ll>(K + 1));\n    for (int i = 1; i <= N; ++i) {\n        for (int k = 1; k <= K; ++k) {\n            ll dx = xs[i] - as[k];\n            ll dy = ys[i] - bs[k];\n            distsq[i][k] = dx * dx + dy * dy;\n        }\n    }\n    // benefit\n    vector<ll> benefit(N + 1, 0LL);\n    for (int k = 1; k <= K; ++k) {\n        ll min1 = INF_LL, min2 = INF_LL;\n        int id1 = -1;\n        for (int i = 1; i <= N; ++i) {\n            ll d2 = distsq[i][k];\n            if (d2 < min1) {\n                min2 = min1;\n                min1 = d2;\n                id1 = i;\n            } else if (d2 < min2) {\n                min2 = d2;\n            }\n        }\n        int p1 = calc_p(min1);\n        int p2 = calc_p(min2);\n        benefit[id1] += (ll)p2 * p2 - (ll)p1 * p1;\n    }\n    // Floyd-Warshall + next_node for path recon\n    vector<vector<ll>> gdist(N + 1, vector<ll>(N + 1, INF_LL));\n    vector<vector<int>> nextn(N + 1, vector<int>(N + 1, -1));\n    for (int i = 1; i <= N; ++i) gdist[i][i] = 0;\n    for (auto& e : edgs) {\n        gdist[e.u][e.v] = e.w;\n        gdist[e.v][e.u] = e.w;\n        nextn[e.u][e.v] = e.v;\n        nextn[e.v][e.u] = e.u;\n    }\n    for (int k = 1; k <= N; ++k) {\n        for (int i = 1; i <= N; ++i) {\n            for (int j = 1; j <= N; ++j) {\n                if (gdist[i][k] >= INF_LL || gdist[k][j] >= INF_LL) continue;\n                ll cand = gdist[i][k] + gdist[k][j];\n                if (cand < gdist[i][j]) {\n                    gdist[i][j] = cand;\n                    nextn[i][j] = nextn[i][k];\n                }\n            }\n        }\n    }\n    // Select terminals: benefit[t] >= 1.1 * dist[1][t]\n    set<int> terms;\n    terms.insert(1);\n    double factor = 1.1;\n    for (int t = 2; t <= N; ++t) {\n        ll conn = gdist[1][t];\n        if (conn < INF_LL / 2 && benefit[t] >= factor * conn) {\n            terms.insert(t);\n        }\n    }\n    // Term list\n    vector<int> term_list(terms.begin(), terms.end());\n    int T = term_list.size();\n    // MST on terminals using gdist: generate pairs\n    vector<tuple<ll, int, int>> term_pairs;\n    for (int ii = 0; ii < T; ++ii) {\n        for (int jj = ii + 1; jj < T; ++jj) {\n            int t1 = term_list[ii], t2 = term_list[jj];\n            ll dw = gdist[t1][t2];\n            if (dw < INF_LL / 2) {\n                term_pairs.emplace_back(dw, t1, t2);\n            }\n        }\n    }\n    sort(term_pairs.begin(), term_pairs.end());\n    // UF for terms\n    vector<int> tpar(N + 1);\n    iota(tpar.begin(), tpar.end(), 0);\n    auto tfind = [&](auto self, int x) -> int {\n        return tpar[x] == x ? x : tpar[x] = self(self, tpar[x]);\n    };\n    auto tunite = [&](int a, int b) {\n        a = tfind(tfind, a); b = tfind(tfind, b);\n        if (a == b) return false;\n        tpar[a] = b;\n        return true;\n    };\n    // B init 0\n    vector<int> B(M + 1, 0);\n    // Add paths for MST term edges\n    auto add_path = [&](int s, int t) {\n        int u = s;\n        while (u != t) {\n            int v = nextn[u][t];\n            if (v == -1) return;  // error\n            // find eid u-v\n            for (auto [nei, eid] : adj[u]) {\n                if (nei == v) {\n                    B[eid] = 1;\n                    break;\n                }\n            }\n            u = v;\n        }\n    };\n    for (auto [dw, t1, t2] : term_pairs) {\n        if (tunite(t1, t2)) {\n            add_path(t1, t2);\n        }\n    }\n    // Connected comp from 1\n    vector<bool> vis(N + 1, false);\n    queue<int> qcomp;\n    qcomp.push(1); vis[1] = true;\n    vector<int> comp = {1};\n    while (!qcomp.empty()) {\n        int u = qcomp.front(); qcomp.pop();\n        for (auto [v, eid] : adj[u]) {\n            if (B[eid] && !vis[v]) {\n                vis[v] = true;\n                qcomp.push(v);\n                comp.push_back(v);\n            }\n        }\n    }\n    // needs\n    vector<ll> need(N + 1, 0LL);\n    for (int k = 1; k <= K; ++k) {\n        ll md2 = INF_LL;\n        int bi = -1;\n        for (int i : comp) {\n            ll d2 = distsq[i][k];\n            if (d2 < md2) {\n                md2 = d2;\n                bi = i;\n            }\n        }\n        need[bi] = max(need[bi], md2);\n    }\n    // P\n    vector<int> PP(N + 1, 0);\n    for (int i = 1; i <= N; ++i) {\n        PP[i] = calc_p(need[i]);\n    }\n    // Output\n    for (int i = 1; i <= N; ++i) {\n        cout << PP[i];\n        if (i < N) cout << \" \";\n        else cout << \"\\n\";\n    }\n    for (int j = 1; j <= M; ++j) {\n        cout << B[j];\n        if (j < M) cout << \" \";\n        else cout << \"\\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  int N = 30;\n  int total = N * (N + 1) / 2;\n  vector<int> cum(N + 1, 0);\n  for (int i = 1; i <= N; ++i) {\n    cum[i] = cum[i - 1] + i;\n  }\n  vector<pair<int, int>> coord(total);\n  vector<vector<int>> flat_pos(N, vector<int>(N));\n  for (int x = 0; x < N; ++x) {\n    for (int y = 0; y <= x; ++y) {\n      int id = cum[x] + y;\n      coord[id] = {x, y};\n      flat_pos[x][y] = id;\n    }\n  }\n  vector<int> a(total);\n  for (int i = 0; i < total; ++i) {\n    cin >> a[i];\n  }\n  vector<vector<int>> childs(total);\n  for (int x = 0; x < N - 1; ++x) {\n    for (int y = 0; y <= x; ++y) {\n      int p = flat_pos[x][y];\n      int l = flat_pos[x + 1][y];\n      int r = flat_pos[x + 1][y + 1];\n      childs[p] = {l, r};\n    }\n  }\n  vector<int> cur_a = a;\n  vector<vector<int>> ops;\n  auto sim_siftdown = [&](vector<int>& arr, int node) -> int {\n    int cnt = 0;\n    int cur_node = node;\n    while (true) {\n      const auto& ch = childs[cur_node];\n      if (ch.empty()) return cnt;\n      int l = ch[0], r = ch[1];\n      int sm = cur_node;\n      if (arr[l] < arr[sm]) sm = l;\n      if (arr[r] < arr[sm]) sm = r;\n      if (sm == cur_node) return cnt;\n      swap(arr[cur_node], arr[sm]);\n      ++cnt;\n      cur_node = sm;\n    }\n  };\n  auto real_siftdown = [&](int node) -> void {\n    int cur_node = node;\n    while (true) {\n      const auto& ch = childs[cur_node];\n      if (ch.empty()) return;\n      int l = ch[0], r = ch[1];\n      int sm = cur_node;\n      if (cur_a[l] < cur_a[sm]) sm = l;\n      if (cur_a[r] < cur_a[sm]) sm = r;\n      if (sm == cur_node) return;\n      swap(cur_a[cur_node], cur_a[sm]);\n      auto [x1, y1] = coord[cur_node];\n      auto [x2, y2] = coord[sm];\n      ops.push_back({x1, y1, x2, y2});\n      cur_node = sm;\n    }\n  };\n  const int INF = 100000000;\n  for (int xx = N - 2; xx >= 0; --xx) {\n    // Prepare nodes\n    vector<int> nodes;\n    for (int y = 0; y <= xx; ++y) {\n      nodes.push_back(flat_pos[xx][y]);\n    }\n    // Strategies\n    vector<vector<int>> strategies;\n    // 1. LTR\n    {\n      vector<int> ord = nodes;\n      strategies.push_back(ord);\n    }\n    // 2. RTL\n    {\n      vector<int> ord = nodes;\n      reverse(ord.begin(), ord.end());\n      strategies.push_back(ord);\n    }\n    // 3. Largest parent first\n    {\n      vector<int> ord = nodes;\n      sort(ord.begin(), ord.end(), [&](int i, int j) {\n        return cur_a[i] > cur_a[j];\n      });\n      strategies.push_back(ord);\n    }\n    // 4. Largest violation first\n    {\n      vector<int> ord = nodes;\n      sort(ord.begin(), ord.end(), [&](int i, int j) {\n        int li = min(cur_a[childs[i][0]], cur_a[childs[i][1]]);\n        int lj = min(cur_a[childs[j][0]], cur_a[childs[j][1]]);\n        int vi = cur_a[i] - li;\n        int vj = cur_a[j] - lj;\n        return vi > vj;\n      });\n      strategies.push_back(ord);\n    }\n    // Find best\n    int min_swaps = INF;\n    int best_strat = -1;\n    for (int s = 0; s < (int)strategies.size(); ++s) {\n      vector<int> temp = cur_a;\n      int sw = 0;\n      for (int node : strategies[s]) {\n        sw += sim_siftdown(temp, node);\n      }\n      if (sw < min_swaps) {\n        min_swaps = sw;\n        best_strat = s;\n      }\n    }\n    // Replay best\n    for (int node : strategies[best_strat]) {\n      real_siftdown(node);\n    }\n  }\n  cout << ops.size() << '\\n';\n  for (auto& op : ops) {\n    cout << op[0] << ' ' << op[1] << ' ' << op[2] << ' ' << op[3] << '\\n';\n  }\n}","toyota2023summer-final":"","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n, m;\n  cin >> n >> m;\n  vector<vector<int>> grid(n, vector<int>(n));\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      cin >> grid[i][j];\n    }\n  }\n  vector<int> touches0(m + 1, 0);\n  vector<pair<int, int>> anchor(m + 1, make_pair(-1, -1));\n  vector<int> cursize(m + 1, 0);\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      int c = grid[i][j];\n      cursize[c]++;\n      if ((i == 0 || i == n - 1 || j == 0 || j == n - 1) && anchor[c].first == -1) {\n        anchor[c] = {i, j};\n        touches0[c] = 1;\n      } else if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {\n        touches0[c] = 1;\n      }\n    }\n  }\n  vector<vector<int>> cnt(m + 1, vector<int>(m + 1, 0));\n  // horizontal\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n - 1; ++j) {\n      int a = grid[i][j], b = grid[i][j + 1];\n      if (a != b && a > 0 && b > 0) {\n        int u = min(a, b), v = max(a, b);\n        cnt[u][v]++;\n      }\n    }\n  }\n  // vertical\n  for (int i = 0; i < n - 1; ++i) {\n    for (int j = 0; j < n; ++j) {\n      int a = grid[i][j], b = grid[i + 1][j];\n      if (a != b && a > 0 && b > 0) {\n        int u = min(a, b), v = max(a, b);\n        cnt[u][v]++;\n      }\n    }\n  }\n\n  vector<pair<int, int>> dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n  auto peel = [&](vector<vector<int>> g, const vector<int>& init_size) -> pair<vector<vector<int>>, int> {\n    vector<vector<int>> out = g;\n    vector<int> size_ = init_size;\n    auto cnte = cnt;\n    bool changed = true;\n    while (changed) {\n      changed = false;\n      for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n          if (out[i][j] == 0) continue;\n          int c = out[i][j];\n          if (anchor[c].first == i && anchor[c].second == j) continue;\n          if (size_[c] == 1) continue;\n          int same_n = 0;\n          bool can_zero = (i == 0 || i == n - 1 || j == 0 || j == n - 1);\n          int adj_cnt[101] = {};\n          bool would_hurt_i = false;\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) continue;\n            int nc = out[ni][nj];\n            if (nc == c) {\n              ++same_n;\n            } else if (nc == 0) {\n              can_zero = true;\n            } else {\n              ++adj_cnt[nc];\n              if (touches0[nc] == 0) would_hurt_i = true;\n            }\n          }\n          bool safe_adj = true;\n          for (int nc = 1; nc <= m; ++nc) {\n            if (adj_cnt[nc] > 0) {\n              int u = min(c, nc), v = max(c, nc);\n              if (cnte[u][v] == adj_cnt[nc]) {\n                safe_adj = false;\n                break;\n              }\n            }\n          }\n          if (same_n > 1 || !safe_adj || !can_zero || would_hurt_i) continue;\n          // remove\n          out[i][j] = 0;\n          size_[c]--;\n          // update cnt\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n              int nc = out[ni][nj];\n              if (nc > 0 && nc != c) {\n                int u = min(c, nc), v = max(c, nc);\n                cnte[u][v]--;\n              }\n            }\n          }\n          changed = true;\n        }\n      }\n    }\n    int zeros = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        if (out[i][j] == 0) ++zeros;\n      }\n    }\n    return {out, zeros};\n  };\n\n  auto [out1, z1] = peel(grid, cursize);\n\n  auto peel_rev = [&](vector<vector<int>> g, const vector<int>& init_size) -> pair<vector<vector<int>>, int> {\n    vector<vector<int>> out = g;\n    vector<int> size_ = init_size;\n    auto cnte = cnt;\n    bool changed = true;\n    while (changed) {\n      changed = false;\n      for (int i = n - 1; i >= 0; --i) {\n        for (int j = n - 1; j >= 0; --j) {\n          if (out[i][j] == 0) continue;\n          int c = out[i][j];\n          if (anchor[c].first == i && anchor[c].second == j) continue;\n          if (size_[c] == 1) continue;\n          int same_n = 0;\n          bool can_zero = (i == 0 || i == n - 1 || j == 0 || j == n - 1);\n          int adj_cnt[101] = {};\n          bool would_hurt_i = false;\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) continue;\n            int nc = out[ni][nj];\n            if (nc == c) {\n              ++same_n;\n            } else if (nc == 0) {\n              can_zero = true;\n            } else {\n              ++adj_cnt[nc];\n              if (touches0[nc] == 0) would_hurt_i = true;\n            }\n          }\n          bool safe_adj = true;\n          for (int nc = 1; nc <= m; ++nc) {\n            if (adj_cnt[nc] > 0) {\n              int u = min(c, nc), v = max(c, nc);\n              if (cnte[u][v] == adj_cnt[nc]) {\n                safe_adj = false;\n                break;\n              }\n            }\n          }\n          if (same_n > 1 || !safe_adj || !can_zero || would_hurt_i) continue;\n          // remove\n          out[i][j] = 0;\n          size_[c]--;\n          // update cnt\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n              int nc = out[ni][nj];\n              if (nc > 0 && nc != c) {\n                int u = min(c, nc), v = max(c, nc);\n                cnte[u][v]--;\n              }\n            }\n          }\n          changed = true;\n        }\n      }\n    }\n    int zeros = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        if (out[i][j] == 0) ++zeros;\n      }\n    }\n    return {out, zeros};\n  };\n\n  auto [out2, z2] = peel_rev(grid, cursize);\n\n  // pick the better one\n  vector<vector<int>> final_out = (z1 >= z2 ? out1 : out2);\n\n  // output\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      cout << final_out[i][j];\n      if (j < n - 1) cout << \" \";\n    }\n    cout << \"\\n\";\n  }\n  return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  unsigned seed = chrono::duration_cast<chrono::microseconds>(\n      chrono::steady_clock::now().time_since_epoch()).count();\n  mt19937 rng(seed);\n  int N, D, Q;\n  cin >> N >> D >> Q;\n  vector<vector<int8_t>> cmp(N, vector<int8_t>(N, -2));\n  vector<int> perm(N);\n  iota(perm.begin(), perm.end(), 0);\n  int q_used = 0;\n  // Main querying loop with shuffled pairings\n  while (q_used < Q) {\n    shuffle(perm.begin(), perm.end(), rng);\n    for (int i = 0; i + 1 < N; i += 2) {\n      if (q_used >= Q) break;\n      int a = perm[i], b = perm[i + 1];\n      if (cmp[a][b] != -2) continue;\n      // Query\n      cout << 1 << ' ' << 1 << ' ' << a << ' ' << b << '\\n';\n      cout.flush();\n      string res;\n      cin >> res;\n      int8_t val;\n      if (res == \"<\") val = -1;\n      else if (res == \">\") val = 1;\n      else val = 0;\n      cmp[a][b] = val;\n      cmp[b][a] = -val;\n      q_used++;\n    }\n  }\n  // Dummy queries to reach exactly Q if needed\n  int dummy_a = 0, dummy_b = 1;\n  while (q_used < Q) {\n    cout << 1 << ' ' << 1 << ' ' << dummy_a << ' ' << dummy_b << '\\n';\n    cout.flush();\n    string res;\n    cin >> res;\n    q_used++;\n  }\n  // Build beat graph: adj[i] = lighter items directly beaten by i (cmp[i][j] > 0)\n  vector<vector<int>> adj(N);\n  for (int i = 0; i < N; i++) {\n    for (int j = 0; j < N; j++) {\n      if (i != j && cmp[i][j] > 0) {\n        adj[i].push_back(j);\n      }\n    }\n  }\n  // Compute reachability sizes\n  vector<int> reach(N);\n  for (int s = 0; s < N; s++) {\n    vector<char> vis(N, 0);\n    queue<int> qq;\n    qq.push(s);\n    vis[s] = 1;\n    int cnt = 1;\n    while (!qq.empty()) {\n      int u = qq.front();\n      qq.pop();\n      for (int v : adj[u]) {\n        if (!vis[v]) {\n          vis[v] = 1;\n          cnt++;\n          qq.push(v);\n        }\n      }\n    }\n    reach[s] = cnt;\n  }\n  // Rank by descending reach size\n  vector<pair<int, int>> ranked;\n  for (int i = 0; i < N; i++) {\n    ranked.emplace_back(-reach[i], i);\n  }\n  sort(ranked.begin(), ranked.end());\n  // Assign groups round-robin from heaviest\n  vector<int> group(N);\n  int gid = 0;\n  for (auto& p : ranked) {\n    group[p.second] = gid;\n    gid = (gid + 1) % D;\n  }\n  // Output assignment\n  for (int i = 0; i < N; i++) {\n    cout << group[i];\n    if (i + 1 < N) cout << ' ';\n    else cout << '\\n';\n  }\n  return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n, m;\n  cin >> n >> m;\n  int h = n / m;\n  vector<vector<int>> stacks(m);\n  vector<int> location(n + 1, -1);\n  for (int i = 0; i < m; i++) {\n    stacks[i].resize(h);\n    for (int j = 0; j < h; j++) {\n      cin >> stacks[i][j];\n      location[stacks[i][j]] = i;\n    }\n  }\n  vector<pair<int, int>> ops;\n  int next_box = 1;\n  const int INF = 1000000000;\n  const int PENALTY = 300;\n  const int DEPTH = 5;\n  while (next_box <= n) {\n    int s = location[next_box];\n    if (s != -1 && !stacks[s].empty() && stacks[s].back() == next_box) {\n      ops.emplace_back(next_box, 0);\n      stacks[s].pop_back();\n      location[next_box] = -1;\n      next_box++;\n      continue;\n    }\n    // Pile\n    auto& stk = stacks[s];\n    auto it = find(stk.begin(), stk.end(), next_box);\n    int p = it - stk.begin();\n    int start_idx = p + 1;\n    vector<int> pile(stk.begin() + start_idx, stk.end());\n    int v_move = pile[0];\n    int pile_top = pile.back();\n    // Unified lookahead ALL dests\n    tuple<int, int, int> best_key = {INF, -INF, INF};\n    int best_d = -1;\n    for (int d = 0; d < m; d++) {\n      if (d == s) continue;\n      const auto& dstk = stacks[d];\n      int orig_tt = dstk.empty() ? INF : dstk.back();\n      int orig_sz = dstk.size();\n      bool acc = dstk.empty() || orig_tt > pile_top;\n      // Trial sim\n      auto trial_stacks = stacks;\n      auto trial_loc = location;\n      auto& t_stk = trial_stacks[s];\n      auto& t_dst = trial_stacks[d];\n      t_stk.resize(start_idx);\n      t_dst.insert(t_dst.end(), pile.begin(), pile.end());\n      for (int bb : pile) trial_loc[bb] = d;\n      // Carry current\n      t_stk.pop_back();\n      trial_loc[next_box] = -1;\n      // Future dig costs\n      int tcost = 0;\n      int tnext = next_box + 1;\n      for (int dep = 0; dep < DEPTH; ++dep) {\n        if (tnext > n) break;\n        int ts2 = trial_loc[tnext];\n        if (ts2 == -1) {\n          ++tnext;\n          continue;\n        }\n        const auto& tstkk = trial_stacks[ts2];\n        if (!tstkk.empty() && tstkk.back() == tnext) {\n          // free\n          ++tnext;\n          continue;\n        }\n        auto tiit = find(tstkk.begin(), tstkk.end(), tnext);\n        int tpos = tiit - tstkk.begin();\n        int tabove = tstkk.size() - tpos - 1;\n        tcost += tabove + 1;\n        ++tnext;\n      }\n      if (!acc) tcost += PENALTY;\n      auto tkey = make_tuple(tcost, -orig_tt, orig_sz);\n      if (tkey < best_key) {\n        best_key = tkey;\n        best_d = d;\n      }\n    }\n    assert(best_d != -1);\n    // Commit\n    auto& dstk = stacks[best_d];\n    stk.resize(start_idx);\n    dstk.insert(dstk.end(), pile.begin(), pile.end());\n    for (int b : pile) {\n      location[b] = best_d;\n    }\n    ops.emplace_back(v_move, best_d + 1);\n  }\n  for (auto [v, i] : ops) {\n    cout << v << ' ' << i << '\\n';\n  }\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N;\n  cin >> N;\n  vector<string> H(N - 1);\n  for (auto& s : H) cin >> s;\n  vector<string> V(N);\n  for (auto& s : V) cin >> s;\n  vector<vector<int>> D(N, vector<int>(N));\n  long long sumD = 0;\n  for (int i = 0; i < N; i++)\n    for (int j = 0; j < N; j++) {\n      cin >> D[i][j];\n      sumD += D[i][j];\n    }\n  int dr[] = {0, 1, 0, -1};\n  int dc[] = {1, 0, -1, 0};\n  char dirchar[] = {'R', 'D', 'L', 'U'};\n  auto no_wall = [&](int r, int c, int d) -> bool {\n    int nr = r + dr[d], nc = c + dc[d];\n    if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n    if (dr[d] == 0) {\n      int cmin = min(c, nc);\n      return V[r][cmin] == '0';\n    } else {\n      int rmin = min(r, nr);\n      return H[rmin][c] == '0';\n    }\n  };\n  // Precompute Dist and prev from (0,0)\n  vector<vector<int>> Dist(N, vector<int>(N, -1));\n  vector<vector<int>> prevr(N, vector<int>(N, -1)), prevc(N, vector<int>(N, -1));\n  {\n    queue<pair<int, int>> q;\n    q.emplace(0, 0);\n    Dist[0][0] = 0;\n    while (!q.empty()) {\n      auto [r, c] = q.front(); q.pop();\n      for (int d = 0; d < 4; d++) {\n        int nr = r + dr[d], nc = c + dc[d];\n        if (nr >= 0 && nr < N && nc >= 0 && nc < N && Dist[nr][nc] == -1 && no_wall(r, c, d)) {\n          Dist[nr][nc] = Dist[r][c] + 1;\n          prevr[nr][nc] = r;\n          prevc[nr][nc] = c;\n          q.emplace(nr, nc);\n        }\n      }\n    }\n  }\n  // SP reconstruct target from src (0,0)\n  auto sp_to = [&](int ti, int tj) -> string {\n    if (Dist[ti][tj] == -1) return \"\";\n    string sp;\n    int r = ti, c = tj;\n    while (r != 0 || c != 0) {\n      int pr = prevr[r][c], pc = prevc[r][c];\n      char ch;\n      if (r == pr + 1) ch = 'U';\n      else if (r == pr - 1) ch = 'D';\n      else if (c == pc + 1) ch = 'L';\n      else ch = 'R';\n      sp += ch;\n      r = pr; c = pc;\n    }\n    reverse(sp.begin(), sp.end());\n    return sp;\n  };\n  auto rt_to = [&](int ti, int tj) -> string {\n    string forth = sp_to(ti, tj);\n    string back;\n    for (char ch : forth) {\n      if (ch == 'R') back += 'L';\n      else if (ch == 'L') back += 'R';\n      else if (ch == 'U') back += 'D';\n      else back += 'U';\n    }\n    reverse(back.begin(), back.end());\n    return forth + back;\n  };\n  auto compute_score = [&](const string& p) -> double {\n    int L = p.size();\n    if (L == 0 || L % 2 != 0 || L > 99999) return 1e18;\n    vector<vector<int>> lastv(N, vector<int>(N, 0));\n    int r = 0, c = 0, t = 0;\n    array<int, 256> dir2d = {};\n    dir2d['R'] = 0; dir2d['D'] = 1; dir2d['L'] = 2; dir2d['U'] = 3;\n    // Simulate first cycle\n    for (char ch : p) {\n      int d = dir2d[ch];\n      if (!no_wall(r, c, d)) return 1e18;\n      int nr = r + dr[d], nc = c + dc[d];\n      t++;\n      lastv[nr][nc] = t;\n      r = nr; c = nc;\n    }\n    if (r != 0 || c != 0) return 1e18;\n    bool allv = true;\n    for (int i = 0; i < N && allv; i++)\n      for (int j = 0; j < N; j++)\n        if (lastv[i][j] == 0) allv = false;\n    if (!allv) return 1e18;\n    // Compute sum S_L .. S_{2L-1}\n    long long total = 0;\n    for (int i = 0; i < N; i++)\n      for (int j = 0; j < N; j++)\n        total += 1LL * D[i][j] * (t - lastv[i][j]);\n    long long sumS = total;\n    // Second cycle L-1 steps\n    for (int i = 0; i < L - 1; i++) {\n      char ch = p[i];\n      int d = dir2d[ch];\n      int nr = r + dr[d], nc = c + dc[d];\n      long long oldc = 1LL * D[nr][nc] * (t - lastv[nr][nc]);\n      long long delta = sumD - D[nr][nc] - oldc;\n      total += delta;\n      t++;\n      lastv[nr][nc] = t;\n      sumS += total;\n      r = nr; c = nc;\n    }\n    return static_cast<double>(sumS) / L;\n  };\n  // Multi-heuristic DFS gen\n  auto gen_tree = [&](auto&& prio) -> string {\n    vector<vector<bool>> vis(N, vector<bool>(N, false));\n    string path;\n    path.reserve(4 * N * N);\n    auto dfs = [&](auto&& self, int r, int c) -> void {\n      vis[r][c] = true;\n      vector<pair<double, int>> cands;\n      for (int d = 0; d < 4; d++) {\n        int nr = r + dr[d], nc = c + dc[d];\n        if (nr >= 0 && nr < N && nc >= 0 && nc < N && !vis[nr][nc] && no_wall(r, c, d)) {\n          cands.emplace_back(-prio(nr, nc), d);\n        }\n      }\n      sort(cands.begin(), cands.end());\n      for (auto [_, d] : cands) {\n        int nr = r + dr[d], nc = c + dc[d];\n        path += dirchar[d];\n        self(self, nr, nc);\n        path += dirchar[(d + 2) % 4];\n      }\n    };\n    dfs(dfs, 0, 0);\n    return path;\n  };\n  // Priors\n  vector<function<double(int, int)>> prios;\n  vector<double> as = {0.3, 0.4, 0.45, 0.5, 0.55, 0.6, 0.7};\n  for (double a : as)\n    prios.push_back([&](int i, int j) { return pow(D[i][j], a); });\n  prios.push_back([&](int i, int j) { return D[i][j]; });\n  prios.push_back([&](int i, int j) { return sqrt(D[i][j]); });\n  prios.push_back([&](int i, int j) { return sqrt(D[i][j]) / (1 + Dist[i][j]); });\n  prios.push_back([&](int i, int j) { return D[i][j] / (1 + Dist[i][j]); });\n  prios.push_back([&](int i, int j) { return 1. / (1 + Dist[i][j]); });\n  prios.push_back([&](int i, int j) { return -Dist[i][j]; });\n  prios.push_back([&](int i, int j) { return 1e5 / (1. + i * N + j); });  // row-major\n  prios.push_back([&](int i, int j) {\n    int col = (i % 2 ? N - 1 - j : j);\n    return 1e5 / (1. + i * N + col);\n  });  // snake\n  // Find best tree\n  string best = \"\";\n  double best_sc = 1e100;\n  for (auto& pr : prios) {\n    string cand = gen_tree(pr);\n    double sc = compute_score(cand);\n    if (sc < best_sc) {\n      best_sc = sc;\n      best = move(cand);\n    }\n  }\n  // Compute visits on best tree\n  auto visits = [&]() -> vector<vector<int>> {\n    vector<vector<int>> v(N, vector<int>(N, 0));\n    int r = 0, c = 0;\n    array<int, 256> dir2d{};\n    dir2d['R'] = 0; dir2d['D'] = 1; dir2d['L'] = 2; dir2d['U'] = 3;\n    for (char ch : best) {\n      int d = dir2d[ch];\n      r += dr[d]; c += dc[d];\n      v[r][c]++;\n    }\n    return v;\n  }();\n  // Boost candidates: high (D/vis) / dist\n  vector<tuple<double, int, int>> boosts;\n  for (int i = 0; i < N; i++)\n    for (int j = 0; j < N; j++)\n      if (Dist[i][j] > 0 && visits[i][j] > 0)\n        boosts.emplace_back(D[i][j] * 1. / visits[i][j] / Dist[i][j], i, j);\n  sort(boosts.rbegin(), boosts.rend());\n  boosts.resize(min(30, (int)boosts.size()));\n  // Greedy append RTs\n  string curr = best;\n  for (int bi = 0; bi < boosts.size(); bi++) {\n    auto [_, ti, tj] = boosts[bi];\n    string rt = rt_to(ti, tj);\n    if (rt.empty()) continue;\n    int rtlen = rt.size();\n    for (int reps = 1; reps <= 3; reps++) {\n      string trial = curr + string(reps, ' ') + rt;  // temp marker\n      int newL = curr.size() + reps * rtlen;\n      if (newL > 99999) break;\n      string newpath = curr;\n      for (int k = 0; k < reps; k++) newpath += rt;\n      double newsc = compute_score(newpath);\n      if (newsc < best_sc) {\n        best_sc = newsc;\n        curr = move(newpath);\n        // Update visits? But since append after, approx ok for next residuals\n      }\n    }\n  }\n  cout << curr << '\\n';\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing pii = pair<int, int>;\nint manh(pii a, pii b) { return abs(a.first - b.first) + abs(a.second - b.second); }\n\nconst int INF = 1000000010;\n\nstruct PartialEmb {\n  int movecost = INF;\n  vector<pii> seq;\n};\n\nstruct Emb {\n  array<pii, 5> seq;\n  int intd;\n};\n\nint compute_T(const vector<pii>& pa, pii inip) {\n  if (pa.empty()) return 0;\n  int res = 0;\n  pii pr = inip;\n  for (auto p : pa) {\n    res += manh(pr, p) + 1;\n    pr = p;\n  }\n  return res;\n}\n\nvector<int> do_2opt(vector<int> ord, pii initp, const vector<Emb>& embs, int M) {\n  int passes = 0;\n  bool improved;\n  do {\n    improved = false;\n    for (int a = 0; a < M; ++a) {\n      for (int b = a + 1; b < M; ++b) {\n        pii prev_end = (a == 0 ? initp : embs[ord[a - 1]].seq[4]);\n        pii sa = embs[ord[a]].seq[0];\n        int old1 = manh(prev_end, sa);\n        int old2 = (b == M - 1 ? 0 : manh(embs[ord[b]].seq[4], embs[ord[b + 1]].seq[0]));\n        pii sb = embs[ord[b]].seq[0];\n        int new1 = manh(prev_end, sb);\n        pii ea = embs[ord[a]].seq[4];\n        int new2 = (b == M - 1 ? 0 : manh(ea, embs[ord[b + 1]].seq[0]));\n        int delta = new1 + new2 - old1 - old2;\n        if (delta < 0) {\n          reverse(ord.begin() + a, ord.begin() + b + 1);\n          improved = true;\n        }\n      }\n    }\n  } while (improved && ++passes < 500);\n  return ord;\n}\n\nint compute_inter(const vector<int>& ord, pii initp, const vector<Emb>& embs) {\n  int M = ord.size();\n  if (M == 0) return 0;\n  int sumd = manh(initp, embs[ord[0]].seq[0]);\n  for (int i = 0; i < M - 1; ++i) {\n    sumd += manh(embs[ord[i]].seq[4], embs[ord[i + 1]].seq[0]);\n  }\n  return sumd;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M;\n  cin >> N >> M;\n  int si, sj;\n  cin >> si >> sj;\n  pii initp = {si, sj};\n  vector<string> grid(N);\n  for (auto& s : grid) cin >> s;\n  vector<vector<pii>> pos(26);\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      int c = grid[i][j] - 'A';\n      pos[c].emplace_back(i, j);\n    }\n  }\n  vector<string> ts(M);\n  for (auto& s : ts) cin >> s;\n\n  // Precompute best partials\n  vector<vector<vector<PartialEmb>>> best_partials(M, vector<vector<PartialEmb>>(5));\n  vector<vector<int>> cand_sz(M, vector<int>(5));\n  for (int k = 0; k < M; ++k) {\n    string t = ts[k];\n    auto& szz = cand_sz[k];\n    for (int l = 0; l < 5; ++l) {\n      int cc = t[l] - 'A';\n      szz[l] = pos[cc].size();\n      best_partials[k][l].assign(szz[l], PartialEmb());\n    }\n    vector<pii> candd[5];\n    for (int l = 0; l < 5; ++l) candd[l] = pos[t[l] - 'A'];\n    int sz[5];\n    for (int l = 0; l < 5; ++l) sz[l] = szz[l];\n    for (int a0 = 0; a0 < sz[0]; ++a0) {\n      pii p0 = candd[0][a0];\n      for (int a1 = 0; a1 < sz[1]; ++a1) {\n        pii p1 = candd[1][a1];\n        int d01 = manh(p0, p1);\n        for (int a2 = 0; a2 < sz[2]; ++a2) {\n          pii p2 = candd[2][a2];\n          int d12 = manh(p1, p2);\n          int cum2 = d01 + d12;\n          for (int a3 = 0; a3 < sz[3]; ++a3) {\n            pii p3 = candd[3][a3];\n            int d23 = manh(p2, p3);\n            int cum3 = cum2 + d23;\n            for (int a4 = 0; a4 < sz[4]; ++a4) {\n              pii p4 = candd[4][a4];\n              int d34 = manh(p3, p4);\n              int cum4 = cum3 + d34;\n              // sl=0\n              {\n                auto& pe = best_partials[k][0][a0];\n                if (cum4 < pe.movecost) {\n                  pe.movecost = cum4;\n                  pe.seq = {p0, p1, p2, p3, p4};\n                }\n              }\n              // sl=1\n              {\n                int mc = cum4 - d01;\n                auto& pe = best_partials[k][1][a1];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p1, p2, p3, p4};\n                }\n              }\n              // sl=2\n              {\n                int mc = cum4 - cum2;\n                auto& pe = best_partials[k][2][a2];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p2, p3, p4};\n                }\n              }\n              // sl=3\n              {\n                int mc = cum4 - cum3;\n                auto& pe = best_partials[k][3][a3];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p3, p4};\n                }\n              }\n              // sl=4\n              {\n                int mc = 0;\n                auto& pe = best_partials[k][4][a4];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p4};\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  // Extract fixed embs\n  vector<Emb> embs(M);\n  for (int k = 0; k < M; ++k) {\n    int min_intd = INF;\n    int best_a = -1;\n    for (int a = 0; a < cand_sz[k][0]; ++a) {\n      int mc = best_partials[k][0][a].movecost;\n      if (mc < min_intd) {\n        min_intd = mc;\n        best_a = a;\n      }\n    }\n    embs[k].intd = min_intd;\n    embs[k].seq = {best_partials[k][0][best_a].seq[0], best_partials[k][0][best_a].seq[1],\n                   best_partials[k][0][best_a].seq[2], best_partials[k][0][best_a].seq[3],\n                   best_partials[k][0][best_a].seq[4]};\n  }\n\n  // Compute dist_init\n  vector<int> dist_init(M);\n  for (int k = 0; k < M; ++k) {\n    dist_init[k] = manh(initp, embs[k].seq[0]);\n  }\n\n  // NN order\n  vector<int> order_nn(M);\n  vector<bool> usd(M, false);\n  pii curp = initp;\n  for (int st = 0; st < M; ++st) {\n    int bestk = -1;\n    int mindd = INF;\n    for (int k = 0; k < M; ++k) {\n      if (usd[k]) continue;\n      pii stp = embs[k].seq[0];\n      int dd = manh(curp, stp);\n      if (dd < mindd || (dd == mindd && k < bestk)) {\n        mindd = dd;\n        bestk = k;\n      }\n    }\n    order_nn[st] = bestk;\n    usd[bestk] = true;\n    curp = embs[bestk].seq[4];\n  }\n  auto order1 = do_2opt(order_nn, initp, embs, M);\n  vector<pii> path1;\n  for (int idx : order1) {\n    for (auto pp : embs[idx].seq) path1.push_back(pp);\n  }\n\n  // Spatial order\n  vector<int> order_spa(M);\n  iota(order_spa.begin(), order_spa.end(), 0);\n  sort(order_spa.begin(), order_spa.end(), [&](int aa, int bb) {\n    int cia = (embs[aa].seq[0].first + embs[aa].seq[4].first) / 2;\n    int cja = (embs[aa].seq[0].second + embs[aa].seq[4].second) / 2;\n    int cib = (embs[bb].seq[0].first + embs[bb].seq[4].first) / 2;\n    int cjb = (embs[bb].seq[0].second + embs[bb].seq[4].second) / 2;\n    return cia * N + cja < cib * N + cjb;\n  });\n  auto order3 = do_2opt(order_spa, initp, embs, M);\n  vector<pii> path3;\n  for (int idx : order3) {\n    for (auto pp : embs[idx].seq) path3.push_back(pp);\n  }\n\n  // Close to init\n  vector<int> order_close(M);\n  iota(order_close.begin(), order_close.end(), 0);\n  sort(order_close.begin(), order_close.end(), [&](int x, int y) { return dist_init[x] < dist_init[y]; });\n  auto order_close_opt = do_2opt(order_close, initp, embs, M);\n  vector<pii> path_close;\n  for (int idx : order_close_opt) {\n    for (auto pp : embs[idx].seq) path_close.push_back(pp);\n  }\n\n  // SA improved\n  mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n  vector<int> sa_ord = order_nn;  // start from NN\n  int cur_c = compute_inter(sa_ord, initp, embs);\n  int sa_bestc = cur_c;\n  vector<int> sa_bestord = sa_ord;\n  double sa_T = 8000.0;\n  double cooling = 0.9999;\n  int maxit_sa = 80000;\n  uniform_int_distribution<int> uid(0, M - 1);\n  uniform_real_distribution<double> urd(0.0, 1.0);\n  for (int it = 0; it < maxit_sa; ++it) {\n    int ra = uid(rng), rb = uid(rng);\n    if (ra > rb) swap(ra, rb);\n    if (ra == rb) {\n      --it;\n      continue;\n    }\n    vector<int> trial = sa_ord;\n    reverse(trial.begin() + ra, trial.begin() + rb + 1);\n    int trial_c = compute_inter(trial, initp, embs);\n    int delta = trial_c - cur_c;\n    double prob = (delta < 0) ? 1.0 : exp(-double(delta) / sa_T);\n    if (urd(rng) < prob) {\n      sa_ord = move(trial);\n      cur_c = trial_c;\n      if (trial_c < sa_bestc) {\n        sa_bestc = trial_c;\n        sa_bestord = sa_ord;\n      }\n    }\n    sa_T *= cooling;\n    if (sa_T < 5.0) break;\n  }\n  auto order_sa_opt = do_2opt(sa_bestord, initp, embs, M);\n  vector<pii> path_sa;\n  for (int idx : order_sa_opt) {\n    for (auto pp : embs[idx].seq) path_sa.push_back(pp);\n  }\n\n  // Dynamic greedy with overlaps\n  vector<pii> path_dyn;\n  pii curr_pos = initp;\n  string recent_str = \"\";\n  vector<bool> covered_dyn(M, false);\n  int remaining = M;\n  while (remaining > 0 && (int)path_dyn.size() <= 4990) {\n    int best_kk = -1;\n    int best_added_t = INF;\n    int best_oo = -1;\n    int best_aa = -1;\n    int best_overlap = -1;\n    for (int kk = 0; kk < M; ++kk) {\n      if (covered_dyn[kk]) continue;\n      string tk = ts[kk];\n      int temp_best = INF;\n      int temp_o = -1;\n      int temp_a = -1;\n      int temp_max_ol = -1;\n      size_t rlen = recent_str.size();\n      int maxoo = min(4, (int)rlen);\n      for (int oo = 0; oo <= maxoo; ++oo) {\n        bool match = true;\n        for (int j = 0; j < oo; ++j) {\n          if (recent_str[rlen - oo + j] != tk[j]) {\n            match = false;\n            break;\n          }\n        }\n        if (!match) continue;\n        int ll = oo;\n        int rrem = 5 - oo;\n        if (rrem <= 0) continue;\n        int min_conn = INF;\n        int ba_this = -1;\n        int ncand = cand_sz[kk][ll];\n        for (int aid = 0; aid < ncand; ++aid) {\n          const auto& pe = best_partials[kk][ll][aid];\n          if (pe.seq.empty() || pe.movecost >= INF / 2) continue;\n          int cd = manh(curr_pos, pe.seq[0]) + pe.movecost;\n          if (cd < min_conn) {\n            min_conn = cd;\n            ba_this = aid;\n          }\n        }\n        if (min_conn == INF) continue;\n        int addedd = min_conn + rrem;\n        if (addedd < temp_best || (addedd == temp_best && oo > temp_max_ol)) {\n          temp_best = addedd;\n          temp_o = oo;\n          temp_a = ba_this;\n          temp_max_ol = oo;\n        }\n      }\n      if (temp_best < INF / 2) {\n        if (temp_best < best_added_t || (temp_best == best_added_t && temp_o > best_overlap)) {\n          best_added_t = temp_best;\n          best_kk = kk;\n          best_oo = temp_o;\n          best_aa = temp_a;\n          best_overlap = temp_o;\n        }\n      }\n    }\n    if (best_kk == -1) break;\n    int ll = best_oo;\n    const auto& pe = best_partials[best_kk][ll][best_aa];\n    for (auto p : pe.seq) {\n      path_dyn.push_back(p);\n    }\n    string addl = \"\";\n    for (auto p : pe.seq) {\n      addl += grid[p.first][p.second];\n    }\n    recent_str += addl;\n    if (recent_str.size() > 4) {\n      recent_str = recent_str.substr(recent_str.size() - 4);\n    }\n    curr_pos = pe.seq.back();\n    covered_dyn[best_kk] = true;\n    --remaining;\n  }\n  // Append remaining if any\n  if (remaining > 0) {\n    pii cur_rem = curr_pos;\n    vector<bool> usd_rem(M, false);  // reuse covered_dyn false for uncovered\n    for (int st = 0; st < remaining; ++st) {\n      int bestk = -1;\n      int mindd = INF;\n      for (int k = 0; k < M; ++k) {\n        if (covered_dyn[k]) continue;\n        int dd = manh(cur_rem, embs[k].seq[0]);\n        if (dd < mindd || (dd == mindd && k < bestk)) {\n          mindd = dd;\n          bestk = k;\n        }\n      }\n      for (auto p : embs[bestk].seq) path_dyn.push_back(p);\n      covered_dyn[bestk] = true;\n      cur_rem = embs[bestk].seq[4];\n    }\n  }\n\n  // Pick best among all\n  vector<pair<int, const vector<pii>*>> candts = {\n      {compute_T(path1, initp), &path1},\n      {compute_T(path3, initp), &path3},\n      {compute_T(path_close, initp), &path_close},\n      {compute_T(path_sa, initp), &path_sa},\n      {compute_T(path_dyn, initp), &path_dyn}};\n  sort(candts.begin(), candts.end());\n  const vector<pii>& best_path = *candts[0].second;\n  for (auto p : best_path) {\n    cout << p.first << \" \" << p.second << '\\n';\n  }\n}","ahc030":"#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <random>\n#include <chrono>\nusing namespace std;\nusing namespace Eigen;\n\nconst int MAXNN = 400;\nconst int MAXM = 20;\nconst int MAXB = 512;\n\nstruct State {\n    double score;\n    int choice[MAXM];\n};\n\nstruct Placement {\n    int di, dj;\n    double score;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout << fixed << setprecision(10);\n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n    vector<vector<pair<int, int>>> shapes(M);\n    int total_mass = 0;\n    for (int m = 0; m < M; ++m) {\n        int d;\n        cin >> d;\n        shapes[m].resize(d);\n        for (int l = 0; l < d; ++l) {\n            cin >> shapes[m][l].first >> shapes[m][l].second;\n        }\n        total_mass += d;\n    }\n    int NN = N * N;\n    assert(NN <= MAXNN);\n    assert(M <= MAXM);\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    int QQ = 48;\n    int ksize = max(8, NN / 2);\n    double alpha = 1.0 - 2 * eps;\n    vector<double> ys(QQ);\n    vector<int> ks(QQ);\n    MatrixXd A(QQ, NN);\n    A.setZero();\n    vector<vector<int>> subsets(QQ);\n    for (int q = 0; q < QQ; ++q) {\n        vector<int> all_cells(NN);\n        iota(all_cells.begin(), all_cells.end(), 0);\n        shuffle(all_cells.begin(), all_cells.end(), rng);\n        int actual_k = min(ksize, NN);\n        subsets[q].reserve(actual_k);\n        for (int t = 0; t < actual_k; ++t) {\n            subsets[q].push_back(all_cells[t]);\n        }\n        printf(\"q %d\", (int)subsets[q].size());\n        for (int cc : subsets[q]) {\n            printf(\" %d %d\", cc / N, cc % N);\n        }\n        printf(\"\\n\");\n        fflush(stdout);\n        int y;\n        cin >> y;\n        ys[q] = y;\n        ks[q] = subsets[q].size();\n        for (int cc : subsets[q]) {\n            A(q, cc) = 1.0;\n        }\n    }\n    VectorXd sh(QQ);\n    for (int q = 0; q < QQ; ++q) {\n        double bq = eps * ks[q];\n        sh(q) = max(0.0, (ys[q] - bq) / alpha);\n    }\n    ColPivHouseholderQR<MatrixXd> decomp(A);\n    VectorXd vhat_raw = decomp.solve(sh);\n    vector<vector<double>> dens(N, vector<double>(N));\n    for (int c = 0; c < NN; ++c) {\n        int i = c / N, j = c % N;\n        dens[i][j] = max(0.0, vhat_raw(c));\n    }\n    // Smooth twice 5x5 tent\n    for (int pass = 0; pass < 2; ++pass) {\n        vector<vector<double>> newd(N, vector<double>(N));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                double sum = 0.0, wsum = 0.0;\n                for (int di = -2; di <= 2; ++di) {\n                    for (int dj = -2; dj <= 2; ++dj) {\n                        int ni = i + di, nj = j + dj;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                            double w = 1.0 / (1.0 + abs(di) + abs(dj));\n                            sum += w * dens[ni][nj];\n                            wsum += w;\n                        }\n                    }\n                }\n                newd[i][j] = sum / wsum;\n            }\n        }\n        dens = std::move(newd);\n    }\n    // Top placements\n    int LL = 40;\n    vector<vector<Placement>> top_placements(M);\n    for (int m = 0; m < M; ++m) {\n        const auto& shp = shapes[m];\n        int d = shp.size();\n        int hmax = 0, wmax = 0;\n        for (auto [ii, jj] : shp) {\n            hmax = max(hmax, ii + 1);\n            wmax = max(wmax, jj + 1);\n        }\n        int ndi = N - hmax + 1;\n        int ndj = N - wmax + 1;\n        vector<tuple<double, int, int>> cand;\n        cand.reserve((size_t)ndi * ndj);\n        for (int di = 0; di < ndi; ++di) {\n            for (int dj = 0; dj < ndj; ++dj) {\n                double sc = 0.0;\n                for (auto [ri, rj] : shp) {\n                    sc += dens[di + ri][dj + rj];\n                }\n                double avg_sc = sc / d;\n                cand.emplace_back(-avg_sc, di, dj);\n            }\n        }\n        sort(cand.begin(), cand.end());\n        int tk = min(LL, (int)cand.size());\n        top_placements[m].reserve(tk);\n        for (int l = 0; l < tk; ++l) {\n            auto [nsc, di, dj] = cand[l];\n            top_placements[m].push_back({di, dj, -nsc});\n        }\n    }\n    // Order by size desc\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return shapes[a].size() > shapes[b].size();\n    });\n    // Beam search\n    int BB = 256;\n    double lambda = 0.25;\n    int temp_cover[MAXNN];\n    vector<State> current_beam;\n    current_beam.reserve(BB);\n    State init_st;\n    memset(init_st.choice, -1, sizeof(init_st.choice));\n    init_st.score = 0.0;\n    current_beam.push_back(init_st);\n    for (int s = 0; s < M; ++s) {\n        int fld = order[s];\n        vector<State> next_beam;\n        next_beam.reserve(current_beam.size() * (size_t)LL);\n        for (const auto& st : current_beam) {\n            const auto& tpls = top_placements[fld];\n            for (size_t l = 0; l < tpls.size(); ++l) {\n                State nst = st;\n                nst.choice[fld] = (int)l;\n                memset(temp_cover, 0, (size_t)NN * sizeof(int));\n                for (int ff = 0; ff < M; ++ff) {\n                    int cl = nst.choice[ff];\n                    if (cl < 0) continue;\n                    const auto& pl = top_placements[ff][cl];\n                    const auto& shp = shapes[ff];\n                    for (auto p : shp) {\n                        int x = pl.di + p.first;\n                        int y = pl.dj + p.second;\n                        temp_cover[x * N + y]++;\n                    }\n                }\n                double sc = 0.0;\n                for (int x = 0; x < N; ++x) {\n                    for (int y = 0; y < N; ++y) {\n                        int c = x * N + y;\n                        int cv = temp_cover[c];\n                        double vh = dens[x][y];\n                        sc += vh * cv - lambda * cv * (double)cv;\n                    }\n                }\n                nst.score = sc;\n                next_beam.push_back(std::move(nst));\n            }\n        }\n        sort(next_beam.begin(), next_beam.end(), [](const State& aa, const State& bb) {\n            return aa.score > bb.score;\n        });\n        current_beam.clear();\n        current_beam.reserve(BB);\n        int nb = min(BB, (int)next_beam.size());\n        for (int bi = 0; bi < nb; ++bi) {\n            current_beam.push_back(std::move(next_beam[bi]));\n        }\n    }\n    // Best guess\n    const State& best = current_beam[0];\n    set<pair<int, int>> union_set;\n    for (int ff = 0; ff < M; ++ff) {\n        int cl = best.choice[ff];\n        if (cl < 0) continue;\n        const auto& pl = top_placements[ff][cl];\n        const auto& shp = shapes[ff];\n        for (auto p : shp) {\n            union_set.emplace(pl.di + p.first, pl.dj + p.second);\n        }\n    }\n    vector<pair<int, int>> ans(union_set.begin(), union_set.end());\n    printf(\"a %zu\", ans.size());\n    for (auto [i, j] : ans) {\n        printf(\" %d %d\", i, j);\n    }\n    printf(\"\\n\");\n    fflush(stdout);\n    int ver;\n    cin >> ver;\n    if (ver == 1) {\n        return 0;\n    }\n    // Fallback 1: drill candidate cells\n    double fb_thresh = 0.10;\n    double sumhat = 0.0;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) sumhat += dens[i][j];\n    double avg_dens = sumhat / NN;\n    fb_thresh = max(0.10, 0.35 * avg_dens);\n    vector<pair<int, int>> cand;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (dens[i][j] > fb_thresh) {\n                cand.emplace_back(i, j);\n            }\n        }\n    }\n    vector<vector<char>> drilled_grid(N, vector<char>(N, 0));\n    vector<pair<int, int>> true_oil;\n    for (auto [i, j] : cand) {\n        drilled_grid[i][j] = 1;\n        printf(\"q 1 %d %d\\n\", i, j);\n        fflush(stdout);\n        int vv;\n        cin >> vv;\n        if (vv > 0) {\n            true_oil.emplace_back(i, j);\n        }\n    }\n    printf(\"a %zu\", true_oil.size());\n    for (auto [i, j] : true_oil) {\n        printf(\" %d %d\", i, j);\n    }\n    printf(\"\\n\");\n    fflush(stdout);\n    int ver2;\n    cin >> ver2;\n    if (ver2 == 1) {\n        return 0;\n    }\n    // Super fallback: drill remaining\n    vector<pair<int, int>> all_oil = true_oil;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (drilled_grid[i][j]) continue;\n            drilled_grid[i][j] = 1;\n            printf(\"q 1 %d %d\\n\", i, j);\n            fflush(stdout);\n            int vv;\n            cin >> vv;\n            if (vv > 0) {\n                all_oil.emplace_back(i, j);\n            }\n        }\n    }\n    sort(all_oil.begin(), all_oil.end());\n    printf(\"a %zu\", all_oil.size());\n    for (auto [i, j] : all_oil) {\n        printf(\" %d %d\", i, j);\n    }\n    printf(\"\\n\");\n    fflush(stdout);\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  int W, D, N;\n  cin >> W >> D >> N;\n  vector<vector<int>> A(D, vector<int>(N));\n  for (int d = 0; d < D; ++d) {\n    for (int k = 0; k < N; ++k) {\n      cin >> A[d][k];\n    }\n  }\n  for (int d = 0; d < D; ++d) {\n    vector<int> w_opt(N, 1);\n    int totalw = N;\n    priority_queue<tuple<ll, int>> pq;\n    vector<ll> covered(N, 0);\n    for (int k = 0; k < N; ++k) {\n      ll ar = A[d][k];\n      ll gain = min((ll)W, ar);\n      covered[k] += gain;\n      ll remain_after1 = ar - covered[k];\n      ll nextg = min((ll)W, remain_after1);\n      if (nextg > 0) {\n        pq.emplace(nextg, k);\n      }\n    }\n    while (totalw < W && !pq.empty()) {\n      auto [gainv, k] = pq.top();\n      pq.pop();\n      w_opt[k]++;\n      totalw++;\n      covered[k] += gainv;\n      ll remain = (ll)A[d][k] - covered[k];\n      ll nextg = min((ll)W, remain);\n      if (nextg > 0) {\n        pq.emplace(nextg, k);\n      }\n    }\n    int remainw = W - totalw;\n    if (remainw > 0) {\n      int bestk = 0;\n      for (int k = 1; k < N; ++k) {\n        if (A[d][k] > A[d][bestk]) bestk = k;\n      }\n      w_opt[bestk] += remainw;\n    }\n    vector<int> pref(N + 1, 0);\n    for (int k = 0; k < N; ++k) {\n      pref[k + 1] = pref[k] + w_opt[k];\n    }\n    for (int k = 0; k < N; ++k) {\n      cout << 0 << ' ' << pref[k] << ' ' << W << ' ' << pref[k + 1] << '\\n';\n    }\n  }\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll MOD = 998244353LL;\nconst int TRIALS = 512;\nconst int TOPK = 48;\nconst int SZ = 9;\nconst int POS = 7;\nconst int STAMPSZ = 20;\nconst int OPSMAX = 81;\n\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, K;\n  cin >> N >> M >> K;\n  ll board[SZ][SZ];\n  for (int i = 0; i < SZ; i++)\n    for (int j = 0; j < SZ; j++)\n      cin >> board[i][j];\n  ll stamps[STAMPSZ][3][3];\n  for (int m = 0; m < STAMPSZ; m++)\n    for (int i = 0; i < 3; i++)\n      for (int j = 0; j < 3; j++)\n        cin >> stamps[m][i][j];\n  ll best_score = -1LL<<60;\n  vector<tuple<int,int,int>> best_ops;\n  for (int trial = 0; trial < TRIALS; trial++) {\n    ll cur[SZ][SZ];\n    memcpy(cur, board, sizeof(board));\n    vector<tuple<int,int,int>> ops;\n    for (int step = 0; step < OPSMAX; step++) {\n      vector<tuple<ll,int,int,int>> cands;\n      cands.reserve(1024);\n      for (int m = 0; m < STAMPSZ; m++) {\n        for (int p = 0; p < POS; p++) {\n          for (int q = 0; q < POS; q++) {\n            ll delta = 0;\n            for (int di = 0; di < 3; di++) {\n              for (int dj = 0; dj < 3; dj++) {\n                int x = p + di, y = q + dj;\n                ll s = stamps[m][di][dj];\n                ll r = cur[x][y];\n                ll nr = r + s;\n                if (nr >= MOD) nr -= MOD;\n                delta += nr - r;\n              }\n            }\n            cands.emplace_back(delta, m, p, q);\n          }\n        }\n      }\n      int tk = (trial % 16 == 0) ? 1 : min(TOPK, (int)cands.size());\n      nth_element(cands.begin(), cands.begin() + tk, cands.end(),\n                  greater<tuple<ll,int,int,int>>());\n      int pick = (trial % 16 == 0) ? 0 : (rng() % tk);\n      auto [delta, bm, bp, bq] = cands[pick];\n      for (int di = 0; di < 3; di++) {\n        for (int dj = 0; dj < 3; dj++) {\n          int x = bp + di, y = bq + dj;\n          ll s = stamps[bm][di][dj];\n          ll r = cur[x][y];\n          ll nr = r + s;\n          if (nr >= MOD) nr -= MOD;\n          cur[x][y] = nr;\n        }\n      }\n      ops.emplace_back(bm, bp, bq);\n    }\n    ll score = 0;\n    for (int i = 0; i < SZ; i++)\n      for (int j = 0; j < SZ; j++)\n        score += cur[i][j];\n    if (score > best_score) {\n      best_score = score;\n      best_ops = move(ops);\n    }\n  }\n  cout << best_ops.size() << '\\n';\n  for (auto [m, p, q] : best_ops) {\n    cout << m << ' ' << p << ' ' << q << '\\n';\n  }\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\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    vector<int> start_time(N);\n    int cur = 0;\n    for (int i = 0; i < N; i++) {\n        int sum_adr = 0;\n        for (int k = 0; k < N; k++) {\n            int t = A[i][k] / N;\n            sum_adr += abs(t - i);\n        }\n        int active_len = 10 * N + 2 * sum_adr;\n        start_time[i] = cur;\n        cur += active_len;\n    }\n    vector<string> actions(N);\n    for (int i = 0; i < N; i++) {\n        string s(start_time[i], '.');\n        for (int k = 0; k < N; k++) {\n            int c = A[i][k];\n            int t = c / N;\n            int dr = t - i;\n            int adr = abs(dr);\n            char hdir = (dr > 0 ? 'D' : (dr < 0 ? 'U' : '.'));\n            string hold_vert(adr, hdir);\n            string hold_path = string(N - 1, 'R') + hold_vert;\n            int drb = i - t;\n            char bdir = (drb > 0 ? 'D' : (drb < 0 ? 'U' : '.'));\n            string back_vert(adr, bdir);\n            string back_path = back_vert + string(N - 1, 'L');\n            s += 'P';\n            s += hold_path;\n            s += 'Q';\n            s += back_path;\n        }\n        actions[i] = s;\n    }\n    size_t maxl = 0;\n    for (auto& ss : actions) {\n        maxl = max(maxl, ss.size());\n    }\n    for (auto& ss : actions) {\n        cout << ss + string(maxl - ss.size(), '.') << '\\n';\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<string> get_moves(int r1, int c1, int r2, int c2) {\n    vector<string> res;\n    int dr = r2 - r1;\n    int dc = c2 - c1;\n    string vdir = \"\";\n    if (dr > 0) vdir = \"D\";\n    else if (dr < 0) vdir = \"U\";\n    string hdir = \"\";\n    if (dc > 0) hdir = \"R\";\n    else if (dc < 0) hdir = \"L\";\n    for (int i = 0; i < abs(dr); ++i) {\n        res.push_back(vdir);\n    }\n    for (int i = 0; i < abs(dc); ++i) {\n        res.push_back(hdir);\n    }\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    cin >> N;\n    vector<vector<int>> height(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> height[i][j];\n        }\n    }\n    vector<string> ops;\n    int cur_r = 0, cur_c = 0;\n    long long current_load = 0;\n    while (ops.size() < 95000) {\n        // check if done\n        bool is_done = (current_load == 0);\n        if (is_done) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (height[i][j] != 0) {\n                        is_done = false;\n                        goto next;\n                    }\n                }\n            }\n        }\n    next:;\n        if (is_done) break;\n\n        double best_score = 1e100;\n        int best_secondary = -1;\n        int best_r = -1, best_c = -1;\n        if (current_load > 0) {\n            // find best sink (closest, tie largest need)\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (height[i][j] < 0) {\n                        double dist = abs(i - cur_r) + abs(j - cur_c);\n                        int camt = -height[i][j];\n                        double cscore = dist;\n                        if (cscore < best_score || (cscore == best_score && camt > best_secondary)) {\n                            best_score = cscore;\n                            best_secondary = camt;\n                            best_r = i;\n                            best_c = j;\n                        }\n                    }\n                }\n            }\n        } else {\n            // find best source (min est_cost = D*100 + min_ds*(100 + amt), tie largest amt)\n            for (int sr = 0; sr < N; ++sr) {\n                for (int sc = 0; sc < N; ++sc) {\n                    if (height[sr][sc] > 0) {\n                        int camt = height[sr][sc];\n                        double D = abs(sr - cur_r) + abs(sc - cur_c);\n                        double min_ds = 1e9;\n                        int sink_sec = -1;\n                        for (int tr = 0; tr < N; ++tr) {\n                            for (int tc = 0; tc < N; ++tc) {\n                                if (height[tr][tc] < 0) {\n                                    double ds = abs(tr - sr) + abs(tc - sc);\n                                    int ssamt = -height[tr][tc];\n                                    if (ds < min_ds || (ds == min_ds && ssamt > sink_sec)) {\n                                        min_ds = ds;\n                                        sink_sec = ssamt;\n                                    }\n                                }\n                            }\n                        }\n                        double cscore = D * 100.0 + min_ds * (100.0 + (double)camt);\n                        if (cscore < best_score || (cscore == best_score && camt > best_secondary)) {\n                            best_score = cscore;\n                            best_secondary = camt;\n                            best_r = sr;\n                            best_c = sc;\n                        }\n                    }\n                }\n            }\n        }\n        if (best_r == -1) break;\n\n        // move\n        auto path = get_moves(cur_r, cur_c, best_r, best_c);\n        for (auto& p : path) {\n            ops.push_back(p);\n        }\n        cur_r = best_r;\n        cur_c = best_c;\n\n        // act\n        if (current_load > 0) {\n            // unload\n            long long need = -(long long)height[best_r][best_c];\n            long long d = min(current_load, need);\n            ops.push_back(\"-\" + to_string(d));\n            height[best_r][best_c] += (int)d;\n            current_load -= d;\n        } else {\n            // load\n            long long d = height[best_r][best_c];\n            ops.push_back(\"+\" + to_string(d));\n            height[best_r][best_c] -= (int)d;\n            current_load += d;\n        }\n    }\n    for (auto& s : ops) {\n        cout << s << '\\n';\n    }\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int N, M, T;\n    cin >> N >> M >> T;\n    const int P = N * N; // 36\n    const int S = 2 * N * (N - 1); // 60\n    vector<vector<int>> cur(S, vector<int>(M));\n    for (int k = 0; k < S; k++) {\n        for (int j = 0; j < M; j++) {\n            cin >> cur[k][j];\n        }\n    }\n\n    auto pid = [N](int i, int j) { return i * N + j; };\n\n    // adjacency list\n    vector<vector<int>> adj(P);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N - 1; j++) {\n            int u = pid(i, j), v = pid(i, j + 1);\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n    }\n    for (int i = 0; i < N - 1; i++) {\n        for (int j = 0; j < N; j++) {\n            int u = pid(i, j), v = pid(i + 1, j);\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n    }\n\n    // edges\n    vector<pair<int, int>> edges;\n    for (int u = 0; u < P; u++) {\n        for (int v : adj[u]) {\n            if (v > u) edges.emplace_back(u, v);\n        }\n    }\n\n    // degrees & pos_order (high deg first)\n    vector<int> degree(P);\n    for (int i = 0; i < P; i++) degree[i] = adj[i].size();\n    vector<int> pos_order(P);\n    iota(pos_order.begin(), pos_order.end(), 0);\n    sort(pos_order.begin(), pos_order.end(), [&](int pa, int pb) {\n        return degree[pa] > degree[pb] || (degree[pa] == degree[pb] && pa < pb);\n    });\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> uni_pos(0, P - 1);\n    uniform_real_distribution<double> uni_prob(0.0, 1.0);\n\n    for (int t = 0; t < T; t++) {\n        // values\n        vector<long long> val(S, 0);\n        for (int k = 0; k < S; k++) {\n            for (int j = 0; j < M; j++) val[k] += cur[k][j];\n        }\n\n        // global sort by val desc\n        vector<int> idx(S);\n        iota(idx.begin(), idx.end(), 0);\n        sort(idx.begin(), idx.end(), [&](int a, int b) {\n            return val[a] > val[b] || (val[a] == val[b] && a < b);\n        });\n\n        // elites: dim maxes\n        set<int> elites_set;\n        for (int l = 0; l < M; l++) {\n            int best = -1, mx = -1;\n            for (int k = 0; k < S; k++) {\n                if (cur[k][l] > mx) {\n                    mx = cur[k][l];\n                    best = k;\n                }\n            }\n            if (best != -1) elites_set.insert(best);\n        }\n        int num_elite = elites_set.size();\n        if (t >= 6) num_elite = min(8, num_elite); // late: fewer elites\n\n        // complementary score for non-elites\n        vector<double> comp_score(S, 0.0);\n        if (!elites_set.empty()) {\n            double inv_ne = 1.0 / num_elite;\n            for (int k = 0; k < S; k++) {\n                if (elites_set.count(k)) continue;\n                long long sum_sup = 0;\n                for (int e : elites_set) {\n                    for (int m = 0; m < M; m++) {\n                        sum_sup += max((long long)cur[k][m], (long long)cur[e][m]);\n                    }\n                }\n                comp_score[k] = sum_sup * inv_ne;\n            }\n        }\n\n        // candidates: top comp_score non-elites (or val if no elites)\n        vector<int> candidates;\n        vector<int> non_elite_idx;\n        for (int ii = 0; ii < S; ii++) {\n            int k = idx[ii];\n            if (elites_set.count(k) == 0) non_elite_idx.push_back(k);\n        }\n        sort(non_elite_idx.begin(), non_elite_idx.end(), [&](int a, int b) {\n            if (comp_score[a] != comp_score[b]) return comp_score[a] > comp_score[b];\n            return val[a] > val[b] || (val[a] == val[b] && a < b);\n        });\n        int need_more = P - num_elite;\n        for (int i = 0; i < need_more && i < (int)non_elite_idx.size(); i++) {\n            candidates.push_back(non_elite_idx[i]);\n        }\n\n        // top36\n        vector<int> top36(elites_set.begin(), elites_set.end());\n        top36.insert(top36.end(), candidates.begin(), candidates.end());\n\n        // locals\n        vector<vector<int>> loc(P, vector<int>(M));\n        vector<long long> local_val(P);\n        for (int li = 0; li < P; li++) {\n            int gi = top36[li];\n            local_val[li] = val[gi];\n            for (int m = 0; m < M; m++) loc[li][m] = cur[gi][m];\n        }\n\n        // sort locals by val desc\n        vector<int> local_order(P);\n        iota(local_order.begin(), local_order.end(), 0);\n        sort(local_order.begin(), local_order.end(), [&](int a, int b) {\n            return local_val[a] > local_val[b] || (local_val[a] == local_val[b] && a < b);\n        });\n\n        // supersum lambda\n        auto supersum = [&](int lid1, int lid2) -> long long {\n            long long s = 0;\n            for (int m = 0; m < M; m++) {\n                s += max((long long)loc[lid1][m], (long long)loc[lid2][m]);\n            }\n            return s;\n        };\n\n        // Multi-start SA\n        vector<int> best_assignment(P);\n        long long best_score = LLONG_MIN / 2;\n        const int NUM_STARTS = 2;\n        const int MAX_ITER = 400000;\n        const double TEMP_START = 15000.0;\n        const double COOL_RATE = 0.9997;\n\n        for (int st = 0; st < NUM_STARTS; st++) {\n            // init assignment: top locals to high-deg pos\n            vector<int> assignment(P);\n            for (int pp = 0; pp < P; pp++) {\n                assignment[pos_order[pp]] = local_order[pp];\n            }\n\n            // init score\n            long long score = 0;\n            for (auto [u, v] : edges) {\n                score += supersum(assignment[u], assignment[v]);\n            }\n\n            // SA\n            double cur_temp = TEMP_START;\n            for (int iter = 0; iter < MAX_ITER; iter++) {\n                int a = uni_pos(rng), b = uni_pos(rng);\n                if (a == b) continue;\n\n                int sidA = assignment[a], sidB = assignment[b];\n                long long delta = 0;\n\n                for (int n : adj[a]) {\n                    if (n == b) continue;\n                    delta += supersum(assignment[n], sidB) - supersum(assignment[n], sidA);\n                }\n                for (int n : adj[b]) {\n                    if (n == a) continue;\n                    delta += supersum(assignment[n], sidA) - supersum(assignment[n], sidB);\n                }\n\n                bool accept = delta >= 0;\n                if (!accept) {\n                    double p = exp((double)delta / cur_temp);\n                    accept = uni_prob(rng) < p;\n                }\n                if (accept) {\n                    swap(assignment[a], assignment[b]);\n                    score += delta;\n                }\n\n                cur_temp *= COOL_RATE;\n                if (cur_temp < 1.0) break;\n            }\n\n            if (score > best_score) {\n                best_score = score;\n                best_assignment = assignment;\n            }\n        }\n\n        // build grid\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                int pos = pid(i, j);\n                int lid = best_assignment[pos];\n                grid[i][j] = top36[lid];\n            }\n        }\n\n        // output\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << grid[i][j];\n                if (j + 1 < N) cout << ' ';\n                else cout << '\\n';\n            }\n        }\n        cout.flush();\n\n        // read new\n        for (int k = 0; k < S; k++) {\n            for (int m = 0; m < M; m++) {\n                cin >> cur[k][m];\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, V;\n  cin >> N >> M >> V;\n  vector<string> S(N), T(N);\n  for (auto& str : S) cin >> str;\n  for (auto& str : T) cin >> str;\n  vector<vector<int>> has(N, vector<int>(N, 0));\n  vector<vector<int>> targ(N, vector<int>(N, 0));\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      has[i][j] = S[i][j] - '0';\n      targ[i][j] = T[i][j] - '0';\n    }\n  }\n\n  // Compute center for initial position\n  int sumx = 0, sumy = 0, cnt = 0;\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      if (has[i][j]) {\n        sumx += i;\n        sumy += j;\n        ++cnt;\n      }\n    }\n  }\n  int rx = cnt ? sumx / cnt : N / 2;\n  int ry = cnt ? sumy / cnt : N / 2;\n  rx = max(0, min(N - 1, rx));\n  ry = max(0, min(N - 1, ry));\n\n  // Design simple tree: V' = 2, length N/2\n  int Vp = 2;\n  int L = max(1, N / 2);\n  cout << Vp << '\\n';\n  cout << 0 << \" \" << L << '\\n';\n  cout << rx << \" \" << ry << '\\n';\n\n  // Simulation state\n  vector<pair<int, int>> extras, holes;\n  bool dirty = true;\n  auto rebuild = [&]() {\n    extras.clear();\n    holes.clear();\n    for (int i = 0; i < N; ++i) {\n      for (int j = 0; j < N; ++j) {\n        if (has[i][j] && !targ[i][j]) extras.emplace_back(i, j);\n        if (!has[i][j] && targ[i][j]) holes.emplace_back(i, j);\n      }\n    }\n    dirty = false;\n  };\n\n  // Directions: 0=R,1=D,2=L,3=U\n  int dir_dx[4] = {0, 1, 0, -1};\n  int dir_dy[4] = {1, 0, -1, 0};\n\n  // Current state\n  int cur_rx = rx, cur_ry = ry;\n  int edir = 0;\n  bool holding = false;\n\n  vector<string> ops;\n  const int MAX_TURNS = 100000;\n  while (ops.size() < MAX_TURNS) {\n    if (dirty) rebuild();\n\n    // Current finger position\n    int fx = cur_rx + L * dir_dx[edir];\n    int fy = cur_ry + L * dir_dy[edir];\n\n    // Find best_target pos\n    pair<int, int> best_target{-1, -1};\n    int best_dist = INT_MAX;\n    int best_lex = INT_MAX;\n    bool target_empty = false;\n    if (holding) {\n      if (holes.empty()) {\n        target_empty = true;\n      } else {\n        for (auto p : holes) {\n          int i = p.first, j = p.second;\n          int d = abs(fx - i) + abs(fy - j);\n          int lex = i * N + j;\n          if (d < best_dist || (d == best_dist && lex < best_lex)) {\n            best_dist = d;\n            best_lex = lex;\n            best_target = p;\n          }\n        }\n      }\n    } else {\n      if (extras.empty()) {\n        target_empty = true;\n      } else {\n        for (auto p : extras) {\n          int i = p.first, j = p.second;\n          int d = abs(fx - i) + abs(fy - j);\n          int lex = i * N + j;\n          if (d < best_dist || (d == best_dist && lex < best_lex)) {\n            best_dist = d;\n            best_lex = lex;\n            best_target = p;\n          }\n        }\n      }\n    }\n    if (target_empty) {\n      best_target = {fx, fy};\n      best_dist = 0;\n    }\n\n    // Lambda for ndist after action\n    auto get_ndist = [&](int px, int py, bool hld) -> int {\n      if (!(0 <= px && px < N && 0 <= py && py < N)) return 999;\n      auto& lst = hld ? holes : extras;\n      if (lst.empty()) return 0;\n      int md = INT_MAX;\n      for (auto p : lst) {\n        md = min(md, abs(px - p.first) + abs(py - p.second));\n      }\n      return md;\n    };\n\n    // Try all actions\n    char best_mv = '.', best_rt = '.', best_pk = '.';\n    int best_score = INT_MIN;\n    string mv_opts = \".UDLR\";\n    string rt_opts = \".LR\";\n    string pk_opts = \".P\";\n    for (char mv : mv_opts) {\n      int nrx = cur_rx, nry = cur_ry;\n      int ddx = 0, ddy = 0;\n      if (mv == 'U') {\n        ddx = -1;\n      } else if (mv == 'D') {\n        ddx = 1;\n      } else if (mv == 'L') {\n        ddy = -1;\n      } else if (mv == 'R') {\n        ddy = 1;\n      }\n      nrx += ddx;\n      nry += ddy;\n      if (nrx < 0 || nrx >= N || nry < 0 || nry >= N) continue;\n\n      for (char rt : rt_opts) {\n        int rdelta = 0;\n        if (rt == 'R') rdelta = 1;\n        else if (rt == 'L') rdelta = 3;\n        int nedir = (edir + rdelta) % 4;\n\n        int nfx = nrx + L * dir_dx[nedir];\n        int nfy = nry + L * dir_dy[nedir];\n        bool inb = (0 <= nfx && nfx < N && 0 <= nfy && nfy < N);\n\n        for (char pk : pk_opts) {\n          // Compute new_holding\n          bool new_holding = holding;\n          bool act_success = false;\n          bool good_act = false;\n          if (pk == 'P' && inb) {\n            if (holding) {\n              // try place\n              if (has[nfx][nfy] == 0) {\n                act_success = true;\n                new_holding = false;\n                if (targ[nfx][nfy]) good_act = true;\n              }\n            } else {\n              // try grab\n              if (has[nfx][nfy] == 1) {\n                act_success = true;\n                new_holding = true;\n                if (!targ[nfx][nfy]) good_act = true;\n              }\n            }\n          }\n\n          // ndist\n          int ndist = get_ndist(nfx, nfy, new_holding);\n\n          // target dist\n          int tdist = (best_target.first < 0 ? 0 : abs(nfx - best_target.first) + abs(nfy - best_target.second));\n\n          int score = -ndist * 100 - tdist * 5;\n          if (act_success && good_act) score += 50000;\n          else if (act_success) score += 5000;\n          if (inb) score += 100;\n\n          // action cost\n          if (mv != '.') score -= 3;\n          if (rt != '.') score -= 3;\n          if (pk != '.') score -= 1;\n\n          if (score > best_score) {\n            best_score = score;\n            best_mv = mv;\n            best_rt = rt;\n            best_pk = pk;\n          }\n        }\n      }\n    }\n\n    // Output op\n    string op(4, '.');\n    op[0] = best_mv;\n    op[1] = best_rt;\n    op[3] = best_pk;\n    cout << op << '\\n';\n    ops.push_back(op);\n\n    // Apply\n    int ddx = 0, ddy = 0;\n    if (best_mv == 'U') ddx = -1;\n    else if (best_mv == 'D') ddx = 1;\n    else if (best_mv == 'L') ddy = -1;\n    else if (best_mv == 'R') ddy = 1;\n    cur_rx += ddx;\n    cur_ry += ddy;\n\n    int rdelta = 0;\n    if (best_rt == 'R') rdelta = 1;\n    else if (best_rt == 'L') rdelta = 3;\n    edir = (edir + rdelta) % 4;\n\n    int nfx = cur_rx + L * dir_dx[edir];\n    int nfy = cur_ry + L * dir_dy[edir];\n    bool inb = (0 <= nfx && nfx < N && 0 <= nfy && nfy < N);\n    if (best_pk == 'P' && inb) {\n      if (holding) {\n        if (has[nfx][nfy] == 0) {\n          has[nfx][nfy] = 1;\n          holding = false;\n          dirty = true;\n        }\n      } else {\n        if (has[nfx][nfy] == 1) {\n          has[nfx][nfy] = 0;\n          holding = true;\n          dirty = true;\n        }\n      }\n    }\n\n    // Check done\n    if (extras.empty() && !holding) break;\n  }\n\n  return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    bool operator<(const Point& p) const {\n        return x < p.x || (x == p.x && y < p.y);\n    }\n};\n\nauto comp_y = [](const Point& a, const Point& b) {\n    return a.y < b.y || (a.y == b.y && a.x < b.x);\n};\n\nvector<Point> make_small_rect(const Point& p) {\n    int lx = p.x, rx = p.x, ly = p.y, ry = p.y;\n    if (p.x < 100000) rx = p.x + 1;\n    else if (p.x > 0) lx = p.x - 1;\n    if (p.y < 100000) ry = p.y + 1;\n    else if (p.y > 0) ly = p.y - 1;\n    return {{lx, ly}, {rx, ly}, {rx, ry}, {lx, ry}};\n}\n\npair<int, pair<int, int>> get_max_sub(const vector<pair<int, int>>& events) {\n    if (events.empty()) return {INT_MIN / 2, {0, 0}};\n    int max_prof = INT_MIN / 2;\n    int best_s = -1, best_e = -1;\n    int curr = 0;\n    int st = 0;\n    for (int e = 0; e < (int)events.size(); ++e) {\n        curr += events[e].second;\n        if (curr > max_prof) {\n            max_prof = curr;\n            best_s = st;\n            best_e = e;\n        }\n        if (curr < 0) {\n            curr = 0;\n            st = e + 1;\n        }\n    }\n    if (max_prof <= 0 || best_s < 0) return {0, {0, 0}};\n    int cl = events[best_s].first;\n    int cr = events[best_e].first;\n    if (cl >= cr) return {0, {0, 0}};\n    return {max_prof, {cl, cr}};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int N;\n    cin >> N;\n    vector<Point> mack(N), sard(N);\n    for (auto& p : mack) cin >> p.x >> p.y;\n    for (auto& p : sard) cin >> p.x >> p.y;\n\n    // Initial small rect\n    int best_profit = 1;\n    int best_xl = INT_MAX, best_xr = INT_MIN, best_yl = INT_MAX, best_yr = INT_MIN;\n    {\n        auto rect = make_small_rect(mack[0]);\n        for (const auto& pt : rect) {\n            best_xl = min(best_xl, pt.x);\n            best_xr = max(best_xr, pt.x);\n            best_yl = min(best_yl, pt.y);\n            best_yr = max(best_yr, pt.y);\n        }\n    }\n\n    auto update = [&](int xl, int xr, int yl, int yr, int prof) {\n        if (prof > best_profit && xl < xr && yl < yr) {\n            best_profit = prof;\n            best_xl = xl;\n            best_xr = xr;\n            best_yl = yl;\n            best_yr = yr;\n        }\n    };\n\n    // Global BB\n    {\n        int gminx = INT_MAX, gmaxx = INT_MIN, gmin_y = INT_MAX, gmax_y = INT_MIN;\n        for (const auto& p : mack) {\n            gminx = min(gminx, p.x);\n            gmaxx = max(gmaxx, p.x);\n            gmin_y = min(gmin_y, p.y);\n            gmax_y = max(gmax_y, p.y);\n        }\n        int sb = 0;\n        for (const auto& s : sard) {\n            if (gminx <= s.x && s.x <= gmaxx && gmin_y <= s.y && s.y <= gmax_y) ++sb;\n        }\n        update(gminx, gmaxx, gmin_y, gmax_y, N - sb);\n    }\n\n    // Sorted lists\n    vector<Point> mxs = mack;\n    sort(mxs.begin(), mxs.end());\n    vector<Point> sxs = sard;\n    sort(sxs.begin(), sxs.end());\n    vector<Point> mys = mack;\n    sort(mys.begin(), mys.end(), comp_y);\n    vector<Point> sys = sard;\n    sort(sys.begin(), sys.end(), comp_y);\n\n    vector<int> ths = {0, 10, 20, 50, 100, 200, 400, 600, 800, 1200, 1600, 2500, 3500, 5000, 8000, 12000, 20000, 40000, 100000};\n\n    // X-strips with optimal Y-substrip\n    for (int th : ths) {\n        int i = 0;\n        while (i < N) {\n            int j = i;\n            while (j + 1 < N && mxs[j + 1].x - mxs[j].x <= th) ++j;\n            int xl = mxs[i].x;\n            int xr = mxs[j].x;\n            if (xl >= xr) {\n                i = j + 1;\n                continue;\n            }\n            vector<pair<int, int>> events;\n            events.reserve(j - i + 1 + N / 4);\n            for (int k = i; k <= j; ++k) {\n                events.emplace_back(mxs[k].y, 1);\n            }\n            auto lit = lower_bound(sxs.begin(), sxs.end(), Point{xl, INT_MIN});\n            auto rit = upper_bound(lit, sxs.end(), Point{xr, INT_MAX});\n            for (auto it = lit; it != rit; ++it) {\n                events.emplace_back(it->y, -1);\n            }\n            sort(events.begin(), events.end());\n            auto [prof, prng] = get_max_sub(events);\n            if (prof > 0) {\n                auto [yl, yr] = prng;\n                update(xl, xr, yl, yr, prof);\n            }\n            i = j + 1;\n        }\n    }\n\n    // Y-strips with optimal X-substrip\n    for (int th : ths) {\n        int i = 0;\n        while (i < N) {\n            int j = i;\n            while (j + 1 < N && mys[j + 1].y - mys[j].y <= th) ++j;\n            int yl = mys[i].y;\n            int yr = mys[j].y;\n            if (yl >= yr) {\n                i = j + 1;\n                continue;\n            }\n            vector<pair<int, int>> events;\n            events.reserve(j - i + 1 + N / 4);\n            for (int k = i; k <= j; ++k) {\n                events.emplace_back(mys[k].x, 1);\n            }\n            Point plow = {INT_MIN, yl};\n            auto lit = lower_bound(sys.begin(), sys.end(), plow, comp_y);\n            Point pup = {INT_MAX, yr};\n            auto rit = upper_bound(lit, sys.end(), pup, comp_y);\n            for (auto it = lit; it != rit; ++it) {\n                events.emplace_back(it->x, -1);\n            }\n            sort(events.begin(), events.end());\n            auto [prof, prng] = get_max_sub(events);\n            if (prof > 0) {\n                auto [xl, xr] = prng;\n                update(xl, xr, yl, yr, prof);\n            }\n            i = j + 1;\n        }\n    }\n\n    // Fallback for degenerate\n    if (best_xl >= best_xr || best_yl >= best_yr) {\n        auto rect = make_small_rect(mack[0]);\n        best_xl = INT_MAX;\n        best_xr = INT_MIN;\n        best_yl = INT_MAX;\n        best_yr = INT_MIN;\n        for (const auto& pt : rect) {\n            best_xl = min(best_xl, pt.x);\n            best_xr = max(best_xr, pt.x);\n            best_yl = min(best_yl, pt.y);\n            best_yr = max(best_yr, pt.y);\n        }\n    }\n\n    // Output\n    cout << 4 << '\\n';\n    cout << best_xl << ' ' << best_yl << '\\n';\n    cout << best_xr << ' ' << best_yl << '\\n';\n    cout << best_xr << ' ' << best_yr << '\\n';\n    cout << best_xl << ' ' << best_yr << '\\n';\n\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Rect {\n    ll xl, xr, yt, yb;\n};\n\nstruct Placement {\n    int p, r, d, b;\n};\n\nstruct State {\n    vector<Rect> pos;\n    vector<Placement> placed_seq;\n    vector<int> placed_list;\n    int next_id;\n    ll cur_maxw, cur_maxh, penalty;\n};\n\nll get_score(const State& s) {\n    return s.cur_maxw + s.cur_maxh + s.penalty;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int N, T;\n    ll sigma;\n    cin >> N >> T >> sigma;\n    vector<ll> est_w(N), est_h(N);\n    for (int i = 0; i < N; i++) {\n        cin >> est_w[i] >> est_h[i];\n    }\n\n    const int BEAM_SIZE = 256;\n    const int MAX_BASES = 20;\n    const int NUM_PROBE = 40;\n\n    vector<State> beam(1);\n    beam[0].pos.assign(N, Rect{-1LL, -1LL, -1LL, -1LL});\n    beam[0].placed_seq.clear();\n    beam[0].placed_list.clear();\n    beam[0].next_id = 0;\n    beam[0].cur_maxw = 0;\n    beam[0].cur_maxh = 0;\n    beam[0].penalty = 0;\n\n    for (int step = 0; step < N; step++) {\n        vector<State> next_beam;\n        next_beam.reserve(200000);\n        for (const auto& st : beam) {\n            int nid = st.next_id;\n            if (nid == N) continue;\n\n            // Skip option\n            {\n                State news = st;\n                news.penalty += est_w[nid] + est_h[nid];\n                news.next_id++;\n                next_beam.push_back(std::move(news));\n            }\n\n            // Possible bases: -1 + recent placed\n            vector<int> poss_b;\n            poss_b.reserve(MAX_BASES + 1);\n            poss_b.push_back(-1);\n            int num_recent = min(MAX_BASES, (int)st.placed_list.size());\n            for (int ii = 0; ii < num_recent; ii++) {\n                poss_b.push_back(st.placed_list[st.placed_list.size() - 1 - ii]);\n            }\n\n            // Place options\n            for (int rot = 0; rot < 2; rot++) {\n                ll ww = rot ? est_h[nid] : est_w[nid];\n                ll hh = rot ? est_w[nid] : est_h[nid];\n                for (int dd = 0; dd < 2; dd++) {\n                    for (int bb : poss_b) {\n                        ll xl_, xr_, yt_, yb_;\n                        if (dd == 0) {  // U\n                            xl_ = (bb == -1 ? 0LL : st.pos[bb].xr);\n                            xr_ = xl_ + ww;\n                            yt_ = 0;\n                            for (int j = 0; j < nid; j++) {\n                                if (st.pos[j].xl < 0) continue;\n                                ll lx = max(st.pos[j].xl, xl_);\n                                ll rx = min(st.pos[j].xr, xr_);\n                                if (lx < rx) {\n                                    yt_ = max(yt_, st.pos[j].yb);\n                                }\n                            }\n                            yb_ = yt_ + hh;\n                        } else {  // L\n                            yt_ = (bb == -1 ? 0LL : st.pos[bb].yb);\n                            yb_ = yt_ + hh;\n                            xl_ = 0;\n                            for (int j = 0; j < nid; j++) {\n                                if (st.pos[j].xl < 0) continue;\n                                ll ty = max(st.pos[j].yt, yt_);\n                                ll by_ = min(st.pos[j].yb, yb_);\n                                if (ty < by_) {\n                                    xl_ = max(xl_, st.pos[j].xr);\n                                }\n                            }\n                            xr_ = xl_ + ww;\n                        }\n                        State news = st;\n                        news.pos[nid] = {xl_, xr_, yt_, yb_};\n                        news.placed_seq.push_back({nid, rot, dd, bb});\n                        news.placed_list.push_back(nid);\n                        news.next_id++;\n                        news.cur_maxw = max(st.cur_maxw, xr_);\n                        news.cur_maxh = max(st.cur_maxh, yb_);\n                        next_beam.push_back(std::move(news));\n                    }\n                }\n            }\n        }\n        // Sort by score\n        sort(next_beam.begin(), next_beam.end(), [](const State& a, const State& b) {\n            return get_score(a) < get_score(b);\n        });\n        // Keep top\n        beam.clear();\n        beam.reserve(BEAM_SIZE);\n        int keep_cnt = min(BEAM_SIZE, (int)next_beam.size());\n        for (int k = 0; k < keep_cnt; k++) {\n            beam.push_back(std::move(next_beam[k]));\n        }\n    }\n\n    // Sort final beam\n    sort(beam.begin(), beam.end(), [](const State& a, const State& b) {\n        return get_score(a) < get_score(b);\n    });\n\n    // Probing phase\n    int num_probe = min({NUM_PROBE, (int)beam.size(), T});\n    ll min_proxy = LLONG_MAX;\n    int best_cid = 0;\n    for (int t = 0; t < T; t++) {\n        int cid = (t < num_probe ? t : best_cid);\n        const auto& conf = beam[cid].placed_seq;\n        cout << conf.size() << '\\n';\n        for (const auto& pl : conf) {\n            cout << pl.p << ' ' << pl.r << ' ' << (pl.d == 0 ? \"U\" : \"L\") << ' ' << pl.b << '\\n';\n        }\n        cout.flush();\n\n        ll Wp, Hp;\n        cin >> Wp >> Hp;\n\n        if (t < num_probe) {\n            ll proxy = Wp + Hp + beam[t].penalty;\n            if (proxy < min_proxy) {\n                min_proxy = proxy;\n                best_cid = t;\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  int N, M, H;\n  cin >> N >> M >> H;\n  vector<int> A(N);\n  for (int &a : A) cin >> a;\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  vector<int> X(N), Y(N);\n  for (int i = 0; i < N; i++) {\n    cin >> X[i] >> Y[i];\n  }\n  const int INF = 1000000000;\n  vector<vector<int>> dist(N, vector<int>(N, INF));\n  for (int s = 0; s < N; s++) {\n    vector<int> dep(N, INF);\n    vector<bool> vis(N, false);\n    queue<int> qq;\n    dep[s] = 0;\n    vis[s] = true;\n    qq.push(s);\n    while (!qq.empty()) {\n      int u = qq.front();\n      qq.pop();\n      for (int nei : adj[u]) {\n        if (!vis[nei]) {\n          vis[nei] = true;\n          dep[nei] = dep[u] + 1;\n          qq.push(nei);\n        }\n      }\n    }\n    dist[s] = dep;\n  }\n  vector<vector<int>> ball(N);\n  for (int r = 0; r < N; r++) {\n    for (int v = 0; v < N; v++) {\n      if (dist[r][v] <= H) {\n        ball[r].push_back(v);\n      }\n    }\n  }\n  auto get_greedy_roots = [&](int typ) -> vector<int> {\n    bitset<1000> uncovered;\n    uncovered.set();\n    vector<int> roots;\n    while (uncovered.any()) {\n      ll best_prof = -1;\n      int best_r = -1;\n      int best_ar = INT_MAX;\n      for (int r = 0; r < N; r++) {\n        ll prof = 0;\n        for (int v : ball[r]) {\n          if (uncovered.test(v)) {\n            if (typ == 0) {\n              prof += (ll)dist[r][v] * A[v];\n            } else if (typ == 1) {\n              prof += 1;\n            } else {\n              prof += A[v];\n            }\n          }\n        }\n        bool better = (prof > best_prof) ||\n                      (prof == best_prof && A[r] < best_ar);\n        if (better) {\n          best_prof = prof;\n          best_r = r;\n          best_ar = A[r];\n        }\n      }\n      assert(best_r != -1);\n      roots.push_back(best_r);\n      for (int v : ball[best_r]) {\n        if (uncovered.test(v)) {\n          uncovered.reset(v);\n        }\n      }\n    }\n    return roots;\n  };\n  auto get_farthest_roots = [&]() -> vector<int> {\n    vector<int> roots;\n    while (true) {\n      int best_u = -1;\n      int max_dd = -1;\n      int best_au = INT_MAX;\n      for (int u = 0; u < N; u++) {\n        int dd = INF;\n        for (int rr : roots) {\n          dd = min(dd, dist[rr][u]);\n        }\n        bool better = (dd > max_dd) || (dd == max_dd && A[u] < best_au);\n        if (better) {\n          max_dd = dd;\n          best_u = u;\n          best_au = A[u];\n        }\n      }\n      if (max_dd <= H) break;\n      roots.push_back(best_u);\n    }\n    return roots;\n  };\n  vector<vector<int>> candidates{\n      get_greedy_roots(0),  // depth profit\n      get_greedy_roots(1),  // size\n      get_greedy_roots(2),  // beauty\n      get_farthest_roots()  // farthest\n  };\n  ll best_sc = -1;\n  vector<int> best_S;\n  auto eval = [&](const vector<int>& S) -> pair<ll, bool> {\n    vector<int> md(N, INF);\n    ll sc = 0;\n    bool valid = true;\n    for (int v = 0; v < N; v++) {\n      int dmin = INF;\n      for (int r : S) {\n        dmin = min(dmin, dist[r][v]);\n      }\n      md[v] = dmin;\n      if (dmin > H) {\n        valid = false;\n        break;\n      }\n      sc += (ll)dmin * A[v];\n    }\n    return {sc, valid};\n  };\n  for (auto& S : candidates) {\n    auto [sc, valid] = eval(S);\n    if (valid && sc > best_sc) {\n      best_sc = sc;\n      best_S = S;\n    }\n  }\n  // Improve by removing redundant roots\n  bool improved = true;\n  while (improved) {\n    improved = false;\n    for (size_t i = 0; i < best_S.size(); ++i) {\n      vector<int> trial = best_S;\n      trial.erase(trial.begin() + i);\n      auto [sc_trial, valid] = eval(trial);\n      if (valid && sc_trial > best_sc) {\n        best_sc = sc_trial;\n        best_S = std::move(trial);\n        improved = true;\n        break;\n      }\n    }\n  }\n  // Now build the forest using multi-source BFS\n  vector<int> parent(N, -1);\n  vector<int> dep(N, INF);\n  queue<int> q;\n  for (int r : best_S) {\n    dep[r] = 0;\n    parent[r] = -1;\n    q.push(r);\n  }\n  while (!q.empty()) {\n    int u = q.front();\n    q.pop();\n    for (int v : adj[u]) {\n      if (dep[v] == INF) {\n        dep[v] = dep[u] + 1;\n        parent[v] = u;\n        q.push(v);\n      }\n    }\n  }\n  for (int i = 0; i < N; i++) {\n    cout << parent[i];\n    if (i + 1 < N) cout << \" \";\n    else cout << \"\\n\";\n  }\n}","ahc042":"#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<string> board(N);\n    vector<vector<int>> state(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                state[i][j] = 1;\n            }\n        }\n    }\n    \n    // kmax\n    vector<int> row_left_kmax(N), row_right_kmax(N);\n    for (int r = 0; r < N; ++r) {\n        int first_o = N;\n        for (int j = 0; j < N; ++j) if (board[r][j] == 'o') { first_o = j; break; }\n        row_left_kmax[r] = first_o;\n        int last_o = -1;\n        for (int j = N - 1; j >= 0; --j) if (board[r][j] == 'o') { last_o = j; break; }\n        row_right_kmax[r] = N - 1 - last_o;\n    }\n    vector<int> col_up_kmax(N), col_down_kmax(N);\n    for (int c = 0; c < N; ++c) {\n        int first_o = N;\n        for (int i = 0; i < N; ++i) if (board[i][c] == 'o') { first_o = i; break; }\n        col_up_kmax[c] = first_o;\n        int last_o = -1;\n        for (int i = N - 1; i >= 0; --i) if (board[i][c] == 'o') { last_o = i; break; }\n        col_down_kmax[c] = N - 1 - last_o;\n    }\n    \n    using Op = pair<char, int>;\n    vector<Op> best_sol;\n    size_t min_t = SIZE_MAX;\n    \n    // Heuristic 1-2: All-rows / all-cols optimal split cover\n    auto try_global = [&](const vector<vector<int>>& xs, const vector<int>& k_prefix, const vector<int>& k_suffix,\n                          char d_prefix, char d_suffix, char opp_prefix, char opp_suffix) -> vector<Op> {\n        vector<Op> ops;\n        bool feasible = true;\n        for (int ln = 0; ln < N; ++ln) {\n            vector<int> ps = xs[ln];\n            int m = ps.size();\n            if (m == 0) continue;\n            sort(ps.begin(), ps.end());\n            long long best_c = LLONG_MAX / 2;\n            int best_kpre = 0, best_ksuf = 0;\n            // all prefix\n            if (m > 0) {\n                int maxp = ps.back();\n                int kp = maxp + 1;\n                if (kp <= k_prefix[ln]) {\n                    long long c = 2LL * kp;\n                    if (c < best_c) {\n                        best_c = c;\n                        best_kpre = kp;\n                        best_ksuf = 0;\n                    }\n                }\n            }\n            // all suffix\n            if (m > 0) {\n                int minp = ps[0];\n                int ks = N - minp;\n                if (ks <= k_suffix[ln]) {\n                    long long c = 2LL * ks;\n                    if (c < best_c) {\n                        best_c = c;\n                        best_kpre = 0;\n                        best_ksuf = ks;\n                    }\n                }\n            }\n            // splits\n            for (int s = 0; s <= m; ++s) {\n                long long c = 0;\n                int kp = 0, ks = 0;\n                bool ok = true;\n                if (s > 0) {\n                    int maxpl = ps[s - 1];\n                    kp = maxpl + 1;\n                    if (kp > k_prefix[ln]) ok = false;\n                    else c += 2LL * kp;\n                }\n                if (s < m) {\n                    int minpr = ps[s];\n                    ks = N - minpr;\n                    if (ks > k_suffix[ln]) ok = false;\n                    else c += 2LL * ks;\n                }\n                if (ok && c < best_c) {\n                    best_c = c;\n                    best_kpre = kp;\n                    best_ksuf = ks;\n                }\n            }\n            if (best_c >= LLONG_MAX / 2) {\n                feasible = false;\n                break;\n            }\n            // add ops prefix first\n            for (int t = 0; t < best_kpre; ++t) ops.emplace_back(d_prefix, ln);\n            for (int t = 0; t < best_kpre; ++t) ops.emplace_back(opp_prefix, ln);\n            // suffix\n            for (int t = 0; t < best_ksuf; ++t) ops.emplace_back(d_suffix, ln);\n            for (int t = 0; t < best_ksuf; ++t) ops.emplace_back(opp_suffix, ln);\n        }\n        if (feasible) return ops;\n        return {};\n    };\n    \n    // row_xs\n    vector<vector<int>> row_xs(N);\n    for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) if (state[i][j]) row_xs[i].push_back(j);\n    auto row_ops = try_global(row_xs, row_left_kmax, row_right_kmax, 'L', 'R', 'R', 'L');\n    if (!row_ops.empty() && row_ops.size() < min_t) {\n        min_t = row_ops.size();\n        best_sol = row_ops;\n    }\n    \n    // col_xs\n    vector<vector<int>> col_xs(N);\n    for (int j = 0; j < N; ++j) for (int i = 0; i < N; ++i) if (state[i][j]) col_xs[j].push_back(i);\n    auto col_ops = try_global(col_xs, col_up_kmax, col_down_kmax, 'U', 'D', 'D', 'U');\n    if (!col_ops.empty() && col_ops.size() < min_t) {\n        min_t = col_ops.size();\n        best_sol = col_ops;\n    }\n    \n    // Greedy variants\n    for (int var_id = 0; var_id < 4; ++var_id) {\n        auto temp_state = state;\n        vector<Op> ops;\n        int rem_x = 0;\n        for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) rem_x += temp_state[i][j];\n        while (rem_x > 0) {\n            double best_score = -1.0;\n            int best_cnt = 0;\n            int best_kk = N + 1;\n            char best_d = ' ';\n            int best_p = -1;\n            // rows L\n            for (int r = 0; r < N; ++r) {\n                int kmaxx = row_left_kmax[r];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    for (int j = 0; j < kk; ++j) cntt += temp_state[r][j];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'L';\n                        best_p = r;\n                    }\n                }\n            }\n            // rows R\n            for (int r = 0; r < N; ++r) {\n                int kmaxx = row_right_kmax[r];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    int st = N - kk;\n                    for (int j = st; j < N; ++j) cntt += temp_state[r][j];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'R';\n                        best_p = r;\n                    }\n                }\n            }\n            // cols U\n            for (int c = 0; c < N; ++c) {\n                int kmaxx = col_up_kmax[c];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    for (int i = 0; i < kk; ++i) cntt += temp_state[i][c];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'U';\n                        best_p = c;\n                    }\n                }\n            }\n            // cols D\n            for (int c = 0; c < N; ++c) {\n                int kmaxx = col_down_kmax[c];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    int st = N - kk;\n                    for (int i = st; i < N; ++i) cntt += temp_state[i][c];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'D';\n                        best_p = c;\n                    }\n                }\n            }\n            if (best_cnt == 0) break;  // safeguard\n            // apply\n            char dir = best_d;\n            int p = best_p;\n            int kk = best_kk;\n            char opp;\n            if (dir == 'L') opp = 'R';\n            else if (dir == 'R') opp = 'L';\n            else if (dir == 'U') opp = 'D';\n            else opp = 'U';\n            for (int t = 0; t < kk; ++t) ops.emplace_back(dir, p);\n            for (int t = 0; t < kk; ++t) ops.emplace_back(opp, p);\n            // update temp_state\n            if (dir == 'L' || dir == 'R') {\n                int r = p;\n                int st = (dir == 'L' ? 0 : N - kk);\n                for (int pos = st; pos < st + kk; ++pos) {\n                    temp_state[r][pos] = 0;\n                }\n            } else {\n                int c = p;\n                int st = (dir == 'U' ? 0 : N - kk);\n                for (int pos = st; pos < st + kk; ++pos) {\n                    temp_state[pos][c] = 0;\n                }\n            }\n            rem_x -= best_cnt;\n        }\n        size_t this_t = ops.size();\n        if (this_t < min_t) {\n            min_t = this_t;\n            best_sol = move(ops);\n        }\n    }\n    \n    // Output best\n    for (const auto& op : best_sol) {\n        cout << op.first << ' ' << op.second << '\\n';\n    }\n    return 0;\n}","ahc044":"","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing pii = pair<int, int>;\nusing vpii = vector<pii>;\nusing u32 = uint32_t;\nusing tiii = tuple<int, int, int>;  // d, a, b with a < b\n\nu32 hilbert_order(int xx, int yy) {\n  const int n = 16384;\n  int x = max(0, min(n - 1, xx));\n  int y = max(0, min(n - 1, yy));\n  u32 d = 0;\n  u32 s;\n  for (s = n / 2; s > 0; s >>= 1) {\n    u32 rx = (x & s) > 0;\n    u32 ry = (y & s) > 0;\n    d += s * s * ((3 * rx) ^ ry);\n    if (ry == 0) {\n      if (rx == 1) {\n        x = n - 1 - x;\n        y = n - 1 - y;\n      }\n      swap(x, y);\n    }\n  }\n  return d;\n}\n\nvoid get_mst(const vector<int>& C, vpii& mst_edges) {\n  int l = C.size();\n  cout << \"? \" << l;\n  for (int u : C) cout << \" \" << u;\n  cout << endl << flush;\n  mst_edges.resize(l - 1);\n  for (int i = 0; i < l - 1; i++) {\n    int a, b;\n    cin >> a >> b;\n    if (a > b) swap(a, b);\n    mst_edges[i] = {a, b};\n  }\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, Q_max, L, W;\n  cin >> N >> M >> Q_max >> L >> W;\n  vi G(M);\n  for (auto& g : G) cin >> g;\n  vi lx(N), rx(N), ly(N), ry(N);\n  vi cx(N), cy(N);\n  for (int i = 0; i < N; i++) {\n    cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    cx[i] = (lx[i] + rx[i]) / 2;\n    cy[i] = (ly[i] + ry[i]) / 2;\n  }\n  vector<u32> hidx(N);\n  for (int i = 0; i < N; i++) {\n    hidx[i] = hilbert_order(cx[i], cy[i]);\n  }\n  vi order(N);\n  iota(order.begin(), order.end(), 0);\n  auto cmp = [&](int i, int j) { return hidx[i] < hidx[j]; };\n  sort(order.begin(), order.end(), cmp);\n  vi cum(M + 1, 0);\n  for (int i = 1; i <= M; i++) {\n    cum[i] = cum[i - 1] + G[i - 1];\n  }\n  vvi groups(M);\n  for (int m = 0; m < M; m++) {\n    groups[m].assign(order.begin() + cum[m], order.begin() + cum[m + 1]);\n  }\n  auto proxy_dist = [&](int a, int b) -> int {\n    ll dx = cx[a] - cx[b];\n    ll dy = cy[a] - cy[b];\n    ll dd = dx * dx + dy * dy;\n    int res = (int)sqrt((double)dd);\n    while (1LL * (res + 1) * (res + 1) <= dd) ++res;\n    while (1LL * res * res > dd) --res;\n    return res;\n  };\n  vector<vpii> all_trees(M);\n  int queries_used = 0;\n  int step_size = 3;\n  for (int m = 0; m < M; m++) {\n    int g = groups[m].size();\n    if (g < 2) {\n      all_trees[m] = {};\n      continue;\n    }\n    vi C = groups[m];\n    vpii candidates;\n    if (g <= L) {\n      vpii temp;\n      get_mst(C, temp);\n      queries_used++;\n      all_trees[m] = std::move(temp);\n      continue;\n    }\n    // large group\n    int wsz = L;\n    int pos = 0;\n    while (pos + wsz <= g) {\n      vi sub(C.begin() + pos, C.begin() + pos + wsz);\n      vpii temp;\n      get_mst(sub, temp);\n      queries_used++;\n      for (auto e : temp) candidates.push_back(e);\n      pos += step_size;\n    }\n    if (pos < g) {\n      int rem = g - pos;\n      if (rem >= 2) {\n        int lsz = min(wsz, rem);\n        vi sub(C.begin() + pos, C.begin() + pos + lsz);\n        vpii temp;\n        get_mst(sub, temp);\n        queries_used++;\n        for (auto e : temp) candidates.push_back(e);\n      }\n    }\n    // now Kruskal with proxy dist\n    vi local_id(N, -1);\n    for (int loc = 0; loc < g; loc++) {\n      local_id[C[loc]] = loc;\n    }\n    vector<tiii> cand_edges;\n    for (auto [a, b] : candidates) {\n      int dd = proxy_dist(a, b);\n      cand_edges.emplace_back(dd, a, b);\n    }\n    // add consecutive edges\n    for (int i = 0; i < g - 1; i++) {\n      int u = C[i], v = C[i + 1];\n      int uu = min(u, v), vv = max(u, v);\n      int dd = proxy_dist(u, v);\n      cand_edges.emplace_back(dd, uu, vv);\n    }\n    // sort by proxy dist\n    sort(cand_edges.begin(), cand_edges.end());\n    // union-find\n    vi par(g);\n    iota(par.begin(), par.end(), 0);\n    auto find = [&](auto&& self, int x) -> int {\n      return par[x] == x ? x : par[x] = self(self, par[x]);\n    };\n    vpii tree_edges;\n    for (auto [d, aa, bb] : cand_edges) {\n      int la = local_id[aa], lb = local_id[bb];\n      int pa = find(find, la), pb = find(find, lb);\n      if (pa != pb) {\n        par[pa] = pb;\n        tree_edges.emplace_back(aa, bb);\n        if ((int)tree_edges.size() == g - 1) break;\n      }\n    }\n    // fallback if not connected\n    if ((int)tree_edges.size() < g - 1) {\n      tree_edges.clear();\n      for (int i = 0; i < g - 1; i++) {\n        int u = C[i], v = C[i + 1];\n        if (u > v) swap(u, v);\n        tree_edges.emplace_back(u, v);\n      }\n    }\n    all_trees[m] = std::move(tree_edges);\n  }\n  cout << \"!\" << endl;\n  for (int m = 0; m < M; m++) {\n    for (size_t i = 0; i < groups[m].size(); ++i) {\n      if (i > 0) cout << \" \";\n      cout << groups[m][i];\n    }\n    cout << '\\n';\n    for (const auto& e : all_trees[m]) {\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\nconst int INF = 1e9 + 5;\nint dr[4] = {-1, 1, 0, 0};\nint dc[4] = {0, 0, -1, 1};\nchar dirch[4] = {'U', 'D', 'L', 'R'};\n\nvector<pair<char, char>> get_path(int sr, int sc, int tr, int tc, int N) {\n  int NN = N * N;\n  vector<int> dist(NN, INF);\n  vector<int> prevv(NN, -1);\n  vector<char> pactt(NN, 0);\n  vector<char> pdirr(NN, 0);\n  int sid = sr * N + sc;\n  int tid = tr * N + tc;\n  dist[sid] = 0;\n  queue<int> q;\n  q.push(sid);\n  while (!q.empty()) {\n    int id = q.front();\n    q.pop();\n    int cr = id / N;\n    int cc = id % N;\n    // moves\n    for (int d = 0; d < 4; d++) {\n      int nr = cr + dr[d];\n      int nc = cc + dc[d];\n      if (nr >= 0 && nr < N && nc >= 0 && nc < N) {\n        int nid = nr * N + nc;\n        if (dist[nid] == INF) {\n          dist[nid] = dist[id] + 1;\n          prevv[nid] = id;\n          pactt[nid] = 'M';\n          pdirr[nid] = dirch[d];\n          q.push(nid);\n        }\n      }\n    }\n    // slides\n    for (int d = 0; d < 4; d++) {\n      int er = cr;\n      int ec = cc;\n      int ddr = dr[d];\n      int ddc = dc[d];\n      while (true) {\n        int nr = er + ddr;\n        int nc = ec + ddc;\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N) break;\n        er = nr;\n        ec = nc;\n      }\n      int eid = er * N + ec;\n      if (dist[eid] == INF) {\n        dist[eid] = dist[id] + 1;\n        prevv[eid] = id;\n        pactt[eid] = 'S';\n        pdirr[eid] = dirch[d];\n        q.push(eid);\n      }\n    }\n  }\n  // reconstruct\n  vector<pair<char, char>> path;\n  if (dist[tid] == INF) return path;\n  int cur = tid;\n  while (cur != sid) {\n    char a = pactt[cur];\n    char dd = pdirr[cur];\n    path.emplace_back(a, dd);\n    cur = prevv[cur];\n  }\n  reverse(path.begin(), path.end());\n  return path;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M;\n  cin >> N >> M;\n  vector<pair<int, int>> pos(M);\n  for (int i = 0; i < M; i++) {\n    cin >> pos[i].first >> pos[i].second;\n  }\n  int cr = pos[0].first;\n  int cc = pos[0].second;\n  vector<pair<char, char>> total;\n  for (int k = 1; k < M; k++) {\n    auto pth = get_path(cr, cc, pos[k].first, pos[k].second, N);\n    for (auto pr : pth) {\n      total.push_back(pr);\n    }\n    cr = pos[k].first;\n    cc = pos[k].second;\n  }\n  for (auto [a, d] : total) {\n    cout << a << ' ' << d << '\\n';\n  }\n  return 0;\n}"},"16":{"ahc001":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing u32 = uint32_t;\nusing A4 = array<int, 4>;\n\ninline bool overlaps_rect(int ax, int ay, int cx, int dy, int bx, int by, int dx, int ey) {\n  return ax < dx && cx > bx && ay < ey && dy > by;\n}\n\nbool overlaps(const vector<A4>& v, int a, int b, int c, int d) {\n  for (const auto& p : v) {\n    if (overlaps_rect(a, b, c, d, p[0], p[1], p[2], p[3])) return true;\n  }\n  return false;\n}\n\nbool overlaps_with(const vector<A4>& occ, const vector<A4>& ext, int a, int b, int c, int d) {\n  return overlaps(occ, a, b, c, d) || overlaps(ext, a, b, c, d);\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n;\n  cin >> n;\n  vector<int> X(n), Y(n), R(n);\n  for (int i = 0; i < n; i++) {\n    cin >> X[i] >> Y[i] >> R[i];\n  }\n  vector<A4> points(n);\n  for (int i = 0; i < n; i++) {\n    points[i] = {X[i], Y[i], X[i] + 1, Y[i] + 1};\n  }\n  vector<int> order(n);\n  iota(order.begin(), order.end(), 0);\n  sort(order.begin(), order.end(), [&](int i, int j) {\n    if (R[i] != R[j]) return R[i] > R[j];\n    return X[i] < X[j];\n  });\n  vector<A4> occupied;\n  vector<A4> solution(n);\n  for (int kk = 0; kk < n; kk++) {\n    int i = order[kk];\n    int xi = X[i], yi = Y[i];\n    ll rri = R[i];\n    vector<A4> extras;\n    for (int jj = kk + 1; jj < n; jj++) {\n      extras.push_back(points[order[jj]]);\n    }\n    int aa = xi, bb = yi, cc = xi + 1, dd = yi + 1;\n    bool min_free = !overlaps_with(occupied, extras, aa, bb, cc, dd);\n    if (min_free) {\n      int cura = xi, curb = yi, curc = xi + 1, curd = yi + 1;\n      const int MAX_ITER = 300;\n      for (int iter = 0; iter < MAX_ITER; iter++) {\n        int d_left = 0;\n        {\n          int lo = 0, hi = cura;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int na = cura - mid;\n            if (na >= 0 && !overlaps_with(occupied, extras, na, curb, curc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_left = lo;\n        }\n        int d_right = 0;\n        {\n          int lo = 0, hi = 10000 - curc;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nc = curc + mid;\n            if (nc <= 10000 && !overlaps_with(occupied, extras, cura, curb, nc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_right = lo;\n        }\n        int d_bot = 0;\n        {\n          int lo = 0, hi = curb;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nb = curb - mid;\n            if (nb >= 0 && !overlaps_with(occupied, extras, cura, nb, curc, curd)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_bot = lo;\n        }\n        int d_top = 0;\n        {\n          int lo = 0, hi = 10000 - curd;\n          while (lo < hi) {\n            int mid = (lo + hi + 1) / 2;\n            int nt = curd + mid;\n            if (nt <= 10000 && !overlaps_with(occupied, extras, cura, curb, curc, nt)) {\n              lo = mid;\n            } else {\n              hi = mid - 1;\n            }\n          }\n          d_top = lo;\n        }\n        ll h = (ll)(curd - curb);\n        ll w = (ll)(curc - cura);\n        ll gain_l = (ll)d_left * h;\n        ll gain_r = (ll)d_right * h;\n        ll gain_b = (ll)d_bot * w;\n        ll gain_t = (ll)d_top * w;\n        ll maxg = max({gain_l, gain_r, gain_b, gain_t});\n        if (maxg == 0) break;\n        int chdir = -1;\n        if (gain_l == maxg) chdir = 0;\n        else if (gain_r == maxg) chdir = 1;\n        else if (gain_b == maxg) chdir = 2;\n        else chdir = 3;\n        if (chdir == 0) cura -= d_left;\n        else if (chdir == 1) curc += d_right;\n        else if (chdir == 2) curb -= d_bot;\n        else curd += d_top;\n      }\n      int Wma = curc - cura;\n      int Hma = curd - curb;\n      double bestp = -1.0;\n      int best_sq = INT_MAX;\n      int best_ms = INT_MAX;\n      int besw = 1, besh = 1;\n      for (int ww = 1; ww <= Wma; ww++) {\n        double hhd = (double)rri / ww;\n        int hh = (int)round(hhd);\n        for (int dk = -2; dk <= 2; dk++) {\n          int hht = hh + dk;\n          hht = max(1, min(Hma, hht));\n          ll ss = (ll)ww * hht;\n          double ra = min((double)rri, (double)ss) / max((double)rri, (double)ss);\n          double pp = 2 * ra - ra * ra;\n          int sq = abs(ww - hht);\n          int ms = max(ww, hht);\n          if (pp > bestp || (fabs(pp - bestp) < 1e-10 && (sq < best_sq || (sq == best_sq && ms < best_ms)))) {\n            bestp = pp;\n            best_sq = sq;\n            best_ms = ms;\n            besw = ww;\n            besh = hht;\n          }\n        }\n      }\n      double cx = xi + 0.5;\n      double cy = yi + 0.5;\n      double hw = besw / 2.0;\n      double hh_ = besh / 2.0;\n      int a_ideal = (int)round(cx - hw);\n      int a = max(cura, min(a_ideal, curc - besw));\n      int b_ideal = (int)round(cy - hh_);\n      int b = max(curb, min(b_ideal, curd - besh));\n      int c2 = a + besw;\n      int d2 = b + besh;\n      solution[i] = {a, b, c2, d2};\n      occupied.push_back(solution[i]);\n    } else {\n      bool found = false;\n      u32 state = static_cast<u32>(i) * 1103515245u + 12345u;\n      const int MAX_ATT = 30000;\n      for (int att = 0; att < MAX_ATT; att++) {\n        u32 st = state;\n        state = state * 1103515245u + 12345u;\n        int px = static_cast<int>((st >> 16) % 10000u);\n        int py = static_cast<int>(st % 10000u);\n        if (!overlaps(occupied, px, py, px + 1, py + 1)) {\n          solution[i] = {px, py, px + 1, py + 1};\n          occupied.push_back(solution[i]);\n          found = true;\n          break;\n        }\n      }\n      if (!found) {\n        found = false;\n        for (int px = 9999; px >= 0 && !found; px -= 5) {\n          for (int py = 9999; py >= 0 && !found; py -= 5) {\n            if (!overlaps(occupied, px, py, px + 1, py + 1)) {\n              solution[i] = {px, py, px + 1, py + 1};\n              occupied.push_back(solution[i]);\n              found = true;\n              break;\n            }\n          }\n        }\n      }\n      if (!found) {\n        solution[i] = {0, 0, 1, 1};\n        occupied.push_back(solution[i]);\n      }\n    }\n  }\n  for (int i = 0; i < n; i++) {\n    auto& re = solution[i];\n    cout << re[0] << \" \" << re[1] << \" \" << re[2] << \" \" << re[3] << \"\\n\";\n  }\n}","ahc002":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int si, sj;\n  cin >> si >> sj;\n  vector<vector<int>> T(50, vector<int>(50));\n  int maxt = -1;\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) {\n      cin >> T[i][j];\n      maxt = max(maxt, T[i][j]);\n    }\n  int M = maxt + 1;\n  vector<vector<int>> P(50, vector<int>(50));\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) cin >> P[i][j];\n\n  // Precompute tile_maxp\n  vector<int> tile_maxp(M, 0);\n  for (int i = 0; i < 50; i++)\n    for (int j = 0; j < 50; j++) {\n      tile_maxp[T[i][j]] = max(tile_maxp[T[i][j]], P[i][j]);\n    }\n\n  // Precompute tile_adj and static_deg\n  vector<unordered_set<int>> adj_set(M);\n  const int dr[] = {-1, 1, 0, 0};\n  const int dc[] = {0, 0, -1, 1};\n  for (int i = 0; i < 50; i++) {\n    for (int j = 0; j < 50; j++) {\n      int t1 = T[i][j];\n      for (int d = 0; d < 4; d++) {\n        int ni = i + dr[d];\n        int nj = j + dc[d];\n        if (ni >= 0 && ni < 50 && nj >= 0 && nj < 50) {\n          int t2 = T[ni][nj];\n          if (t1 != t2) {\n            adj_set[t1].insert(t2);\n          }\n        }\n      }\n    }\n  }\n  vector<vector<int>> tile_adj(M);\n  vector<int> static_deg(M);\n  for (int t = 0; t < M; t++) {\n    tile_adj[t].assign(adj_set[t].begin(), adj_set[t].end());\n    static_deg[t] = tile_adj[t].size();\n  }\n\n  const char dirchar[] = {'U', 'D', 'L', 'R'};\n\n  string best_str = \"\";\n  long long best_sc = -1LL;\n  int best_len = 0;\n  const int TRIALS = 262144;\n  const int MAX_TOP = 10;\n  const int PRUNE_STEP = 80;\n  const double PRUNE_FRAC = 0.75;\n\n  mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n  for (int trial = 0; trial < TRIALS; trial++) {\n    vector<int> vis(M, 0);\n    int st = T[si][sj];\n    vis[st] = 1;\n    long long score = P[si][sj];\n    int cr = si, cc = sj;\n    string moves = \"\";\n    int local_mode = trial % 7;\n    while (true) {\n      // Early pruning\n      int curlen = moves.size() + 1;\n      if (best_sc >= 0 && curlen > PRUNE_STEP && \n          score < best_sc * PRUNE_FRAC * curlen / best_len) {\n        break;\n      }\n\n      vector<int> cand_dirs;\n      for (int d = 0; d < 4; d++) {\n        int nr = cr + dr[d];\n        int nc = cc + dc[d];\n        if (nr < 0 || nr >= 50 || nc < 0 || nc >= 50) continue;\n        int nt = T[nr][nc];\n        if (vis[nt]) continue;\n        cand_dirs.push_back(d);\n      }\n      size_t ncand = cand_dirs.size();\n      if (ncand == 0) break;\n\n      int fdir;\n      if (local_mode == 6) {  // Fallback uniform if ncand small, but mode6 below\n        uniform_int_distribution<int> dist(0, ncand - 1);\n        fdir = cand_dirs[dist(rng)];\n      } else {\n        vector<tuple<int, int, int, int>> scored_cands;\n        for (size_t ci = 0; ci < ncand; ci++) {\n          int d = cand_dirs[ci];\n          int nr = cr + dr[d];\n          int nc = cc + dc[d];\n          int nt = T[nr][nc];\n\n          // Dynamic tile out-degree\n          int ddeg = 0;\n          for (int t2 : tile_adj[nt]) {\n            if (!vis[t2]) ddeg++;\n          }\n\n          int pp = P[nr][nc];\n          int bonus = (pp == tile_maxp[nt] ? 50 : 0);\n          int pps = pp + bonus;\n          int sdeg = static_deg[nt];\n\n          int k1, k2, k3;\n          if (local_mode == 0) { // low_sdeg low_ddeg high_pps\n            k1 = sdeg; k2 = ddeg; k3 = -pps;\n          } else if (local_mode == 1) { // low_sdeg high_ddeg high_pps\n            k1 = sdeg; k2 = -ddeg; k3 = -pps;\n          } else if (local_mode == 2) { // high_sdeg low_ddeg high_pps\n            k1 = -sdeg; k2 = ddeg; k3 = -pps;\n          } else if (local_mode == 3) { // low_ddeg low_sdeg high_pps\n            k1 = ddeg; k2 = sdeg; k3 = -pps;\n          } else if (local_mode == 4) { // pure high_pps\n            k1 = 0; k2 = 0; k3 = -pps;\n          } else if (local_mode == 5) { // uniform random\n            uniform_int_distribution<int> dist(0, ncand - 1);\n            fdir = cand_dirs[dist(rng)];\n            goto picked;\n          } else { // local_mode==6: pure low_ddeg low_sdeg high_pps (Warnsdorff)\n            k1 = ddeg; k2 = sdeg; k3 = -pps;\n          }\n          scored_cands.emplace_back(k1, k2, k3, (int)ci);\n        }\n        sort(scored_cands.begin(), scored_cands.end());\n        int nsel = min((int)ncand, MAX_TOP);\n        uniform_int_distribution<int> dist(0, nsel - 1);\n        int pick_ci = dist(rng);\n        auto [_, __, ___, fci] = scored_cands[pick_ci];\n        fdir = cand_dirs[fci];\n      }\n    picked:\n      int nr = cr + dr[fdir];\n      int nc = cc + dc[fdir];\n      moves += dirchar[fdir];\n      int nt = T[nr][nc];\n      vis[nt] = 1;\n      score += P[nr][nc];\n      cr = nr;\n      cc = nc;\n    }\n    int this_len = moves.size() + 1;\n    if (score > best_sc) {\n      best_sc = score;\n      best_len = this_len;\n      best_str = moves;\n    }\n  }\n  cout << best_str << '\\n';\n}","ahc003":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  const int N = 30;\n  auto nodef = [&](int i, int j) -> int { return i * N + j; };\n  auto geti = [&](int u) -> int { return u / N; };\n  auto getj = [&](int u) -> int { return u % N; };\n  vector<vector<double>> h(N, vector<double>(N - 1, 4100.0));\n  vector<vector<double>> vv(N - 1, vector<double>(N, 4100.0));\n  for (int q = 0; q < 1000; ++q) {\n    int si, sj, ti, tj;\n    cin >> si >> sj >> ti >> tj;\n    int ss = nodef(si, sj);\n    int tt = nodef(ti, tj);\n    if (ss == tt) {\n      cout << '\\n';\n      cout.flush();\n      int obs; cin >> obs;\n      continue;\n    }\n    vector<double> dist(N * N, 1e18);\n    vector<int> prevv(N * N, -1);\n    dist[ss] = 0.0;\n    priority_queue<pair<double, int>, vector<pair<double, int>>, greater<pair<double, int>>> pq;\n    pq.push({0.0, ss});\n    while (!pq.empty()) {\n      auto [cost, u] = pq.top(); pq.pop();\n      if (cost > dist[u]) continue;\n      int i = geti(u), j = getj(u);\n      // R\n      if (j < N - 1) {\n        int v = nodef(i, j + 1);\n        double nc = dist[u] + h[i][j];\n        if (nc < dist[v]) {\n          dist[v] = nc; prevv[v] = u; pq.push({nc, v});\n        }\n      }\n      // L\n      if (j > 0) {\n        int v = nodef(i, j - 1);\n        double nc = dist[u] + h[i][j - 1];\n        if (nc < dist[v]) {\n          dist[v] = nc; prevv[v] = u; pq.push({nc, v});\n        }\n      }\n      // D\n      if (i < N - 1) {\n        int v = nodef(i + 1, j);\n        double nc = dist[u] + vv[i][j];\n        if (nc < dist[v]) {\n          dist[v] = nc; prevv[v] = u; pq.push({nc, v});\n        }\n      }\n      // U\n      if (i > 0) {\n        int v = nodef(i - 1, j);\n        double nc = dist[u] + vv[i - 1][j];\n        if (nc < dist[v]) {\n          dist[v] = nc; prevv[v] = u; pq.push({nc, v});\n        }\n      }\n    }\n    double predicted = dist[tt];\n    // recon path\n    vector<int> path_nodes;\n    for (int cur = tt; ; cur = prevv[cur]) {\n      path_nodes.push_back(cur);\n      if (cur == ss) break;\n    }\n    reverse(path_nodes.begin(), path_nodes.end());\n    // path str\n    string path_str;\n    int num_e = path_nodes.size() - 1;\n    for (int k = 0; k < num_e; ++k) {\n      int u = path_nodes[k], v = path_nodes[k + 1];\n      int ui = geti(u), uj = getj(u);\n      int vi = geti(v), vj = getj(v);\n      int di = vi - ui, dj = vj - uj;\n      char ch = (di == -1 ? 'U' : (di == 1 ? 'D' : (dj == -1 ? 'L' : 'R')));\n      path_str += ch;\n    }\n    cout << path_str << '\\n';\n    cout.flush();\n    int obs;\n    cin >> obs;\n    if (num_e == 0 || predicted <= 0) continue;\n    double factor_raw = (double)obs / predicted;\n    factor_raw = max(0.85, min(1.15, factor_raw));\n    double prog = min(1.0, (double)q / 400.0);\n    double alpha = 1.0 - 0.15 * prog;\n    double factor = pow(factor_raw, alpha);\n    for (int k = 0; k < num_e; ++k) {\n      int u = path_nodes[k], v = path_nodes[k + 1];\n      int ui = geti(u), uj = getj(u);\n      int vi = geti(v), vj = getj(v);\n      if (ui == vi) {  // horiz\n        int lj = min(uj, vj);\n        h[ui][lj] *= factor;\n        h[ui][lj] = max(80.0, min(23000.0, h[ui][lj]));\n      } else {  // vert\n        int ti_ = min(ui, vi);\n        vv[ti_][uj] *= factor;\n        vv[ti_][uj] = max(80.0, min(23000.0, vv[ti_][uj]));\n      }\n    }\n  }\n  return 0;\n}","ahc004":"#include <bits/stdc++.h>\nusing namespace std;\n\nint N, M;\nstring SS[805];\nint Lens[805];\nchar grid[20][20];\nchar best_grid[20][20];\nchar temp_grid[20][20];\nchar chars[8] = {'A','B','C','D','E','F','G','H'};\nchar dblr[20][41];\nchar dblc[20][41];\n\nvoid compute_dbl() {\n  for (int r = 0; r < N; ++r) {\n    memcpy(dblr[r], grid[r], N);\n    memcpy(dblr[r] + N, grid[r], N);\n  }\n  for (int c = 0; c < N; ++c) {\n    for (int r = 0; r < N; ++r) dblc[c][r] = grid[r][c];\n    memcpy(dblc[c] + N, dblc[c], N);\n  }\n}\n\nint get_covered() {\n  compute_dbl();\n  int cnt = 0;\n  for (int si = 0; si < M; ++si) {\n    int k = Lens[si];\n    const char* pat = SS[si].c_str();\n    bool ok = false;\n    for (int r = 0; r < N && !ok; ++r) {\n      const char* dbl = dblr[r];\n      for (int st = 0; st < N; ++st) {\n        if (memcmp(dbl + st, pat, k) == 0) { ok = true; break; }\n      }\n    }\n    if (!ok) {\n      for (int c = 0; c < N && !ok; ++c) {\n        const char* dbl = dblc[c];\n        for (int st = 0; st < N; ++st) {\n          if (memcmp(dbl + st, pat, k) == 0) { ok = true; break; }\n        }\n      }\n    }\n    if (ok) ++cnt;\n  }\n  return cnt;\n}\n\nbool get_covered_vec(bool cov[805]) {\n  memset(cov, 0, M);\n  compute_dbl();\n  int cnt = 0;\n  for (int si = 0; si < M; ++si) {\n    int k = Lens[si];\n    const char* pat = SS[si].c_str();\n    bool ok = false;\n    for (int r = 0; r < N && !ok; ++r) {\n      const char* dbl = dblr[r];\n      for (int st = 0; st < N; ++st) {\n        if (memcmp(dbl + st, pat, k) == 0) { ok = true; break; }\n      }\n    }\n    if (!ok) {\n      for (int c = 0; c < N && !ok; ++c) {\n        const char* dbl = dblc[c];\n        for (int st = 0; st < N; ++st) {\n          if (memcmp(dbl + st, pat, k) == 0) { ok = true; break; }\n        }\n      }\n    }\n    cov[si] = ok;\n    if (ok) ++cnt;\n  }\n  return cnt == M;\n}\n\nvoid do_blanking() {\n  vector<pair<int, int>> non_dots;\n  for (int i = 0; i < N; ++i)\n    for (int j = 0; j < N; ++j)\n      if (grid[i][j] != '.') non_dots.emplace_back(i, j);\n  const int num_sweeps = 3;\n  const int max_tries_per_sweep = 200;\n  for (int sw = 0; sw < num_sweeps; ++sw) {\n    random_shuffle(non_dots.begin(), non_dots.end());\n    int tries = 0;\n    for (auto [ri, ci] : non_dots) {\n      if (tries++ >= max_tries_per_sweep) break;\n      char old = grid[ri][ci];\n      grid[ri][ci] = '.';\n      if (get_covered() != M) {\n        grid[ri][ci] = old;\n      }\n    }\n  }\n}\n\nint main() {\n  srand(42);\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cin >> N >> M;\n  for (int i = 0; i < M; ++i) {\n    cin >> SS[i];\n    Lens[i] = SS[i].size();\n  }\n  memset(grid, '.', sizeof(grid));\n  // Greedy: sampled positions\n  int passes = 0;\n  bool changed;\n  do {\n    changed = false;\n    bool cov[805];\n    if (get_covered_vec(cov) && passes > 0) break;\n    vector<int> unc;\n    for (int si = 0; si < M; ++si) if (!cov[si]) unc.push_back(si);\n    if (unc.empty()) break;\n    // top 60 longest\n    sort(unc.begin(), unc.end(), [](int a, int b){ return Lens[a] > Lens[b]; });\n    unc.resize(min(60, (int)unc.size()));\n    // sample 1000 pos per str\n    uint64_t prng = 42 + passes;\n    auto rnd = [&](int mod) {\n      prng = prng * 1103515245ULL + 12345;\n      return (int)(prng % mod);\n    };\n    for (int si : unc) {\n      const string& s = SS[si];\n      int k = s.size();\n      int best_cost = 99;\n      int best_ndot = -1;\n      int best_dir = -1, best_fix = -1, best_st = -1;\n      for (int tr = 0; tr < 1000; ++tr) {\n        int dir = rnd(2);\n        int fix = rnd(N);\n        int st = rnd(N);\n        int cost = 0;\n        int ndot = 0;\n        for (int p = 0; p < k; ++p) {\n          int rr = dir ? (st + p) % N : fix;\n          int cc = dir ? fix : (st + p) % N;\n          char cur = grid[rr][cc];\n          if (cur != '.' && cur != s[p]) ++cost;\n          if (cur == '.') ++ndot;\n        }\n        if (cost > best_cost) continue;\n        if (cost < best_cost || ndot > best_ndot) {\n          best_cost = cost;\n          best_ndot = ndot;\n          best_dir = dir;\n          best_fix = fix;\n          best_st = st;\n        }\n      }\n      if (best_cost == 0) {\n        // place\n        int dir = best_dir, fix = best_fix, st = best_st;\n        for (int p = 0; p < k; ++p) {\n          int rr = dir ? (st + p) % N : fix;\n          int cc = dir ? fix : (st + p) % N;\n          grid[rr][cc] = s[p];\n        }\n        changed = true;\n      }\n    }\n    passes++;\n  } while (changed && passes < 8);\n  memcpy(best_grid, grid, sizeof(grid));\n  int best_c = get_covered();\n  // Try uniform fills\n  for (int ci = 0; ci < 8; ++ci) {\n    char fill_ch = chars[ci];\n    memcpy(temp_grid, best_grid, sizeof(grid));\n    for (int i = 0; i < N; ++i)\n      for (int j = 0; j < N; ++j)\n        if (temp_grid[i][j] == '.') temp_grid[i][j] = fill_ch;\n    memcpy(grid, temp_grid, sizeof(grid));\n    int tc = get_covered();\n    if (tc > best_c) {\n      best_c = tc;\n      memcpy(best_grid, grid, sizeof(grid));\n    }\n  }\n  memcpy(grid, best_grid, sizeof(grid));\n  // If full coverage, blanking\n  if (get_covered() == M) {\n    do_blanking();\n  }\n  // Output\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) cout << grid[i][j];\n    cout << '\\n';\n  }\n  return 0;\n}","ahc005":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nchar get_move(int fi, int fj, int ti, int tj) {\n    int di = ti - fi, dj = tj - fj;\n    if (di == -1 && dj == 0) return 'U';\n    if (di == 1 && dj == 0) return 'D';\n    if (di == 0 && dj == 1) return 'R';\n    if (di == 0 && dj == -1) return 'L';\n    return '?';\n}\n\nll tour_cost(const vector<int>& ord, const vector<vector<ll>>& dists, int nt) {\n    ll c = 0;\n    for (int i = 0; i < nt; ++i) c += dists[ord[i]][ord[(i + 1) % nt]];\n    return c;\n}\n\nstring build_tsp_path(const vector<int>& ord, const vector<vector<string>>& pathstr, int nt) {\n    string path;\n    path.reserve(4000000);\n    for (int i = 0; i < nt; ++i) {\n        path += pathstr[ord[i]][ord[(i + 1) % nt]];\n    }\n    return path;\n}\n\nstring build_mst_path(int start_tid, const vector<vector<string>>& pathstr, const vector<vector<int>>& tadj) {\n    string path;\n    path.reserve(4000000);\n    function<void(int, int)> dfs = [&](int u, int p) {\n        for (int v : tadj[u]) if (v != p) {\n            path += pathstr[u][v];\n            dfs(v, u);\n            path += pathstr[v][u];\n        }\n    };\n    dfs(start_tid, -1);\n    return path;\n}\n\npair<ll, string> compute_best(const vector<pair<int, int>>& base_terms, int si, int sj, int numcells,\n                              const vector<pair<int, int>>& cells, const vector<vector<pair<int, int>>>& graph,\n                              const vector<vector<int>>& cellid, int N) {\n    vector<pair<int, int>> terms = base_terms;\n    set<pair<int, int>> uniq;\n    for (auto p : terms) uniq.insert(p);\n    if (!uniq.count({si, sj})) terms.emplace_back(si, sj);\n    int nt = terms.size();\n    if (nt == 0) return {0, \"\"};\n    vector<int> termids(nt);\n    for (int k = 0; k < nt; ++k) termids[k] = cellid[terms[k].first][terms[k].second];\n    // Find start_tid correctly\n    int start_tid = -1;\n    for (int k = 0; k < nt; ++k) {\n        if (terms[k].first == si && terms[k].second == sj) {\n            start_tid = k;\n            break;\n        }\n    }\n    if (start_tid == -1) return {LLONG_MAX / 2, \"\"};  // impossible\n    const ll INF = 1LL << 60;\n    vector<vector<ll>> dists(nt, vector<ll>(nt, INF));\n    vector<vector<string>> pathstr(nt, vector<string>(nt));\n    int dx[4] = {-1, 0, 1, 0};\n    int dy[4] = {0, 1, 0, -1};\n    for (int s = 0; s < nt; ++s) {\n        int sid = termids[s];\n        vector<ll> d(numcells, INF);\n        vector<int> pred(numcells, -1);\n        d[sid] = 0;\n        priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;\n        pq.emplace(0, sid);\n        while (!pq.empty()) {\n            auto [dc, u] = pq.top(); pq.pop();\n            if (dc > d[u]) continue;\n            for (auto [v, wc] : graph[u]) {\n                ll nc = d[u] + wc;\n                if (nc < d[v]) {\n                    d[v] = nc;\n                    pred[v] = u;\n                    pq.emplace(nc, v);\n                }\n            }\n        }\n        for (int t = 0; t < nt; ++t) {\n            int tid = termids[t];\n            if (d[tid] >= INF / 2) continue;\n            dists[s][t] = d[tid];\n            string& pth = pathstr[s][t];\n            int cur = tid;\n            while (cur != sid) {\n                int prv = pred[cur];\n                if (prv == -1) break;\n                auto [pi, pj] = cells[prv];\n                auto [ci, cj] = cells[cur];\n                pth += get_move(pi, pj, ci, cj);\n                cur = prv;\n            }\n            reverse(pth.begin(), pth.end());\n        }\n    }\n    // MST\n    vector<tuple<ll, int, int>> edges;\n    for (int a = 0; a < nt; ++a)\n        for (int b = a + 1; b < nt; ++b) {\n            ll dab = dists[a][b], dba = dists[b][a];\n            if (dab < INF / 2 && dba < INF / 2) edges.emplace_back(dab + dba, a, b);\n        }\n    sort(edges.begin(), edges.end());\n    vector<int> par(nt);\n    iota(par.begin(), par.end(), 0);\n    auto find = [&](auto self, int x) -> int { return par[x] == x ? x : par[x] = self(self, par[x]); };\n    vector<vector<int>> tadj(nt);\n    ll mst_cost = 0;\n    int nedges = 0;\n    for (auto [w, a, b] : edges) {\n        int pa = find(find, a), pb = find(find, b);\n        if (pa != pb) {\n            par[pa] = pb;\n            tadj[a].push_back(b);\n            tadj[b].push_back(a);\n            mst_cost += w;\n            ++nedges;\n            if (nedges == nt - 1) break;\n        }\n    }\n    string mst_path = build_mst_path(start_tid, pathstr, tadj);\n    // TSP: NN + 2opt fwd/rev\n    ll best_tsp_c = LLONG_MAX / 2;\n    string best_tsp_p;\n    {\n        vector<int> ord(nt);\n        vector<bool> vis(nt);\n        ord[0] = start_tid;\n        vis[start_tid] = true;\n        int cur = start_tid;\n        for (int st = 1; st < nt; ++st) {\n            ll mn = INF;\n            int nxt = -1;\n            for (int c = 0; c < nt; ++c)\n                if (!vis[c] && dists[cur][c] < mn) {\n                    mn = dists[cur][c];\n                    nxt = c;\n                }\n            ord[st] = nxt;\n            vis[nxt] = true;\n            cur = nxt;\n        }\n        auto improve = [&](vector<int> o) -> pair<ll, string> {\n            int passes = 0, maxp = nt * 3;\n            bool ch = true;\n            while (ch && passes++ < maxp) {\n                ch = false;\n                for (int i = 0; i < nt - 2; ++i)\n                    for (int k = i + 2; k < nt - 1; ++k) {\n                        ll d1 = dists[o[i]][o[i + 1]], d2 = dists[o[k]][o[k + 1]];\n                        ll nd1 = dists[o[i]][o[k]], nd2 = dists[o[i + 1]][o[k + 1]];\n                        if (nd1 + nd2 < d1 + d2) {\n                            reverse(o.begin() + i + 1, o.begin() + k + 1);\n                            ch = true;\n                        }\n                    }\n            }\n            ll cc = tour_cost(o, dists, nt);\n            return {cc, build_tsp_path(o, pathstr, nt)};\n        };\n        auto [c1, p1] = improve(ord);\n        vector<int> rev_ord = ord;\n        reverse(rev_ord.begin() + 1, rev_ord.end());\n        auto [c2, p2] = improve(rev_ord);\n        if (c1 < best_tsp_c) {\n            best_tsp_c = c1;\n            best_tsp_p = p1;\n        }\n        if (c2 < best_tsp_c) {\n            best_tsp_c = c2;\n            best_tsp_p = p2;\n        }\n    }\n    if (nt == 1) return {0, \"\"};\n    if (best_tsp_c <= mst_cost) return {best_tsp_c, best_tsp_p};\n    return {mst_cost, mst_path};\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\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    vector<vector<bool>> road(N, vector<bool>(N));\n    vector<vector<int>> enter(N, vector<int>(N));\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (grid[i][j] != '#') {\n                road[i][j] = true;\n                enter[i][j] = grid[i][j] - '0';\n            }\n    // H_reps\n    vector<pair<int, int>> h_reps;\n    for (int i = 0; i < N; ++i) {\n        int j = 0;\n        while (j < N) {\n            if (!road[i][j]) {\n                ++j;\n                continue;\n            }\n            int sjj = j;\n            while (j < N && road[i][j]) ++j;\n            h_reps.emplace_back(i, (sjj + j - 1) / 2);\n        }\n    }\n    // V_reps\n    vector<pair<int, int>> v_reps;\n    for (int j = 0; j < N; ++j) {\n        int i = 0;\n        while (i < N) {\n            if (!road[i][j]) {\n                ++i;\n                continue;\n            }\n            int sii = i;\n            while (i < N && road[i][j]) ++i;\n            v_reps.emplace_back((sii + i - 1) / 2, j);\n        }\n    }\n    // Cells, graph shared\n    vector<pair<int, int>> cells;\n    vector<vector<int>> cellid(N, vector<int>(N, -1));\n    int numcells = 0;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n            if (road[i][j]) {\n                cellid[i][j] = numcells++;\n                cells.push_back({i, j});\n            }\n    vector<vector<pair<int, int>>> graph(numcells);\n    int dx[4] = {-1, 0, 1, 0};\n    int dy[4] = {0, 1, 0, -1};\n    for (int u = 0; u < numcells; ++u) {\n        auto [x, y] = cells[u];\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 && road[nx][ny]) {\n                graph[u].emplace_back(cellid[nx][ny], enter[nx][ny]);\n            }\n        }\n    }\n    auto [ch, ph] = compute_best(h_reps, si, sj, numcells, cells, graph, cellid, N);\n    auto [cv, pv] = compute_best(v_reps, si, sj, numcells, cells, graph, cellid, N);\n    if (ch <= cv) {\n        cout << ph << '\\n';\n    } else {\n        cout << pv << '\\n';\n    }\n    return 0;\n}","future-contest-2022-qual":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout << fixed << setprecision(10);\n  int N, M, K, R;\n  cin >> N >> M >> K >> R;\n  vector<vector<int>> D(N + 1, vector<int>(K));\n  vector<double> avg_d(K, 0.0);\n  for (int i = 1; i <= N; ++i) {\n    for (int k = 0; k < K; ++k) {\n      cin >> D[i][k];\n      avg_d[k] += D[i][k];\n    }\n  }\n  for (int k = 0; k < K; ++k) {\n    avg_d[k] /= N;\n  }\n  vector<vector<int>> adj(N + 1);\n  vector<int> pending(N + 1, 0);\n  for (int r = 0; r < R; ++r) {\n    int u, v;\n    cin >> u >> v;\n    adj[u].push_back(v);\n    ++pending[v];\n  }\n  vector<int> crit(N + 1, 0);\n  auto get_crit = [&](auto&& self, int i) -> int {\n    if (crit[i] != 0) return crit[i];\n    int mx = 0;\n    for (int suc : adj[i]) {\n      mx = max(mx, self(self, suc));\n    }\n    crit[i] = 1 + mx;\n    return crit[i];\n  };\n  for (int i = 1; i <= N; ++i) {\n    get_crit(get_crit, i);\n  }\n  vector<vector<double>> est_s(M + 1, vector<double>(K, 0.0));\n  vector<int> obs_count(M + 1, 0);\n  for (int j = 1; j <= M; ++j) {\n    for (int k = 0; k < K; ++k) {\n      est_s[j][k] = avg_d[k] * 1.6;\n    }\n  }\n  vector<int> task_worker(N + 1, 0);\n  vector<int> task_start(N + 1, 0);\n  vector<bool> task_completed(N + 1, false);\n  vector<int> worker_task(M + 1, 0);\n  set<int> ready_set;\n  for (int i = 1; i <= N; ++i) {\n    if (pending[i] == 0) {\n      ready_set.insert(i);\n    }\n  }\n  int day = 0;\n  while (true) {\n    ++day;\n    vector<int> idles;\n    for (int j = 1; j <= M; ++j) {\n      if (worker_task[j] == 0) {\n        idles.push_back(j);\n      }\n    }\n    vector<int> readies_vec(ready_set.begin(), ready_set.end());\n    if (idles.empty() || readies_vec.empty()) {\n      cout << 0 << '\\n';\n      cout.flush();\n    } else {\n      vector<pair<int, double>> ready_list;\n      for (int ti : readies_vec) {\n        double min_pt = 1e100;\n        for (int j : idles) {\n          double w = 0.0;\n          for (int k = 0; k < K; ++k) {\n            w += max(0.0, (double)D[ti][k] - est_s[j][k]);\n          }\n          double pt = (w <= 0 ? 1.0 : max(1.0, w));\n          if (pt < min_pt) min_pt = pt;\n        }\n        ready_list.emplace_back(ti, min_pt);\n      }\n      sort(ready_list.begin(), ready_list.end(), [&](const pair<int, double>& a, const pair<int, double>& b) {\n        if (crit[a.first] != crit[b.first]) return crit[a.first] > crit[b.first];\n        if (fabs(a.second - b.second) > 1e-9) return a.second < b.second;\n        return a.first < b.first;\n      });\n      set<int> avail(idles.begin(), idles.end());\n      vector<pair<int, int>> assignment;\n      for (auto [ti, mpt] : ready_list) {\n        if (avail.empty()) break;\n        double best_pt = 1e100;\n        int best_j = -1;\n        for (int j : avail) {\n          double w = 0.0;\n          for (int k = 0; k < K; ++k) {\n            w += max(0.0, (double)D[ti][k] - est_s[j][k]);\n          }\n          double pt = (w <= 0 ? 1.0 : max(1.0, w));\n          if (pt < best_pt || (fabs(pt - best_pt) < 1e-9 && j < best_j)) {\n            best_pt = pt;\n            best_j = j;\n          }\n        }\n        if (best_j != -1) {\n          assignment.emplace_back(best_j, ti);\n          avail.erase(best_j);\n        }\n      }\n      cout << assignment.size();\n      for (auto p : assignment) {\n        cout << \" \" << p.first << \" \" << p.second;\n      }\n      cout << '\\n';\n      cout.flush();\n      for (auto [wj, ti] : assignment) {\n        task_worker[ti] = wj;\n        task_start[ti] = day;\n        worker_task[wj] = ti;\n        ready_set.erase(ti);\n      }\n    }\n    int n;\n    cin >> n;\n    if (n == -1) {\n      return 0;\n    }\n    vector<int> finished_workers(n);\n    for (int i = 0; i < n; ++i) {\n      cin >> finished_workers[i];\n    }\n    for (int jj : finished_workers) {\n      int tsk = worker_task[jj];\n      if (tsk == 0) continue;\n      int t_obs = day - task_start[tsk] + 1;\n      double w_est = max(0.0, (double)t_obs - 1.0);\n      ++obs_count[jj];\n      double alpha = 1.0 / obs_count[jj];\n      double current_w = 0.0;\n      vector<double> contrib(K, 0.0);\n      for (int k = 0; k < K; ++k) {\n        double defk = max(0.0, (double)D[tsk][k] - est_s[jj][k]);\n        contrib[k] = defk;\n        current_w += defk;\n      }\n      double error = current_w - w_est;\n      if (current_w > 1e-6) {\n        for (int k = 0; k < K; ++k) {\n          if (contrib[k] > 1e-6) {\n            double frac = contrib[k] / current_w;\n            double delta = alpha * error * frac;\n            est_s[jj][k] += delta;\n            if (est_s[jj][k] < 0.0) est_s[jj][k] = 0.0;\n          }\n        }\n      } else if (w_est > 1.0) {\n        double total_d = 0.0;\n        for (int k = 0; k < K; ++k) total_d += D[tsk][k];\n        if (total_d > 0) {\n          double delta = -alpha * (w_est / (double)K);\n          for (int k = 0; k < K; ++k) {\n            est_s[jj][k] += delta;\n            if (est_s[jj][k] < 0.0) est_s[jj][k] = 0.0;\n          }\n        }\n      }\n      task_completed[tsk] = true;\n      task_worker[tsk] = 0;\n      worker_task[jj] = 0;\n      for (int suc : adj[tsk]) {\n        --pending[suc];\n        if (pending[suc] == 0 && task_worker[suc] == 0 && !task_completed[suc]) {\n          ready_set.insert(suc);\n        }\n      }\n    }\n  }\n  return 0;\n}","ahc006":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    Point(int xx = 0, int yy = 0) : x(xx), y(yy) {}\n};\n\nint dist(Point a, Point b) {\n    return abs(a.x - b.x) + abs(a.y - b.y);\n}\n\ndouble get_angle(const Point& pp) {\n    return atan2(pp.y - 400, pp.x - 400);\n}\n\nstruct Order {\n    Point p, d;\n    int id;\n    int len() const { return dist(p, d); }\n};\n\nconst int N = 50;\nconst Point O(400, 400);\n\nint get_var_cost(const vector<int>& perm, const vector<Point>& Ps, const vector<Point>& Ds) {\n    if (perm.empty()) return 0;\n    int res = dist(O, Ps[perm[0]]);\n    for (size_t i = 0; i + 1 < perm.size(); ++i) {\n        res += dist(Ds[perm[i]], Ps[perm[i + 1]]);\n    }\n    res += dist(Ds[perm.back()], O);\n    return res;\n}\n\nbool improve2opt(vector<int>& perm, const vector<Point>& Ps, const vector<Point>& Ds) {\n    int cur_cost = get_var_cost(perm, Ps, Ds);\n    bool any_improved;\n    int passes = 0;\n    const int MAX_PASSES = 500;\n    do {\n        any_improved = false;\n        for (int i = 0; i < N; ++i) {\n            bool local_improved = false;\n            for (int j = i + 1; j < N; ++j) {\n                vector<int> candidate = perm;\n                reverse(candidate.begin() + i, candidate.begin() + j + 1);\n                int cand_cost = get_var_cost(candidate, Ps, Ds);\n                if (cand_cost < cur_cost) {\n                    perm = move(candidate);\n                    cur_cost = cand_cost;\n                    any_improved = true;\n                    local_improved = true;\n                    break;\n                }\n            }\n            if (local_improved) {\n                break;  // restart i from 0\n            }\n        }\n        ++passes;\n    } while (any_improved && passes < MAX_PASSES);\n    return any_improved;\n}\n\npair<int, vector<Point>> get_best_pallpd(const vector<Point>& Ps, const vector<Point>& Ds) {\n    int best_tt = INT_MAX;\n    vector<Point> best_route;\n    for (int pcw = 0; pcw < 2; ++pcw) {\n        vector<pair<double, int>> pang(N);\n        for (int k = 0; k < N; ++k) {\n            double a = get_angle(Ps[k]);\n            if (pcw) a = -a;\n            pang[k] = {a, k};\n        }\n        sort(pang.begin(), pang.end());\n        vector<Point> pseq(N);\n        for (int k = 0; k < N; ++k) pseq[k] = Ps[pang[k].second];\n        for (int dcw = 0; dcw < 2; ++dcw) {\n            vector<pair<double, int>> dang(N);\n            for (int k = 0; k < N; ++k) {\n                double a = get_angle(Ds[k]);\n                if (dcw) a = -a;\n                dang[k] = {a, k};\n            }\n            sort(dang.begin(), dang.end());\n            vector<Point> dseq(N);\n            for (int k = 0; k < N; ++k) dseq[k] = Ds[dang[k].second];\n            vector<Point> route{O};\n            route.insert(route.end(), pseq.begin(), pseq.end());\n            route.insert(route.end(), dseq.begin(), dseq.end());\n            route.push_back(O);\n            int tt = 0;\n            for (size_t k = 0; k + 1 < route.size(); ++k) {\n                tt += dist(route[k], route[k + 1]);\n            }\n            if (tt < best_tt) {\n                best_tt = tt;\n                best_route = route;\n            }\n        }\n    }\n    return {best_tt, best_route};\n}\n\npair<int, vector<int>> optimize_rigid(const vector<Point>& Ps, const vector<Point>& Ds) {\n    vector<vector<int>> inits;\n    // CCW P\n    {\n        vector<pair<double, int>> ang(N);\n        for (int ii = 0; ii < N; ++ii) ang[ii] = {get_angle(Ps[ii]), ii};\n        sort(ang.begin(), ang.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = ang[ii].second;\n        inits.push_back(ini);\n    }\n    // CW P\n    {\n        vector<pair<double, int>> ang(N);\n        for (int ii = 0; ii < N; ++ii) ang[ii] = {-get_angle(Ps[ii]), ii};\n        sort(ang.begin(), ang.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = ang[ii].second;\n        inits.push_back(ini);\n    }\n    // Manh P\n    {\n        vector<pair<pair<int, int>, int>> mng(N);\n        for (int ii = 0; ii < N; ++ii) {\n            int u = Ps[ii].x + Ps[ii].y;\n            int v = Ps[ii].x - Ps[ii].y;\n            mng[ii] = {{u, v}, ii};\n        }\n        sort(mng.begin(), mng.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = mng[ii].second;\n        inits.push_back(ini);\n    }\n    // Dist O P\n    {\n        vector<pair<int, int>> dsp(N);\n        for (int ii = 0; ii < N; ++ii) dsp[ii] = {dist(O, Ps[ii]), ii};\n        sort(dsp.begin(), dsp.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = dsp[ii].second;\n        inits.push_back(ini);\n    }\n    // CCW D\n    {\n        vector<pair<double, int>> ang(N);\n        for (int ii = 0; ii < N; ++ii) ang[ii] = {get_angle(Ds[ii]), ii};\n        sort(ang.begin(), ang.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = ang[ii].second;\n        inits.push_back(ini);\n    }\n    // CW D\n    {\n        vector<pair<double, int>> ang(N);\n        for (int ii = 0; ii < N; ++ii) ang[ii] = {-get_angle(Ds[ii]), ii};\n        sort(ang.begin(), ang.end());\n        vector<int> ini(N);\n        for (int ii = 0; ii < N; ++ii) ini[ii] = ang[ii].second;\n        inits.push_back(ini);\n    }\n    int best_var = INT_MAX;\n    vector<int> best_perm(N);\n    mt19937 gen(random_device{}());\n    uniform_real_distribution<double> rdis(0.0, 1.0);\n    uniform_int_distribution<int> randpos(0, N - 1);\n    for (auto ini : inits) {\n        vector<int> curp = ini;\n        improve2opt(curp, Ps, Ds);\n        int cc = get_var_cost(curp, Ps, Ds);\n        if (cc < best_var) {\n            best_var = cc;\n            best_perm = curp;\n        }\n        reverse(curp.begin(), curp.end());\n        improve2opt(curp, Ps, Ds);\n        cc = get_var_cost(curp, Ps, Ds);\n        if (cc < best_var) {\n            best_var = cc;\n            best_perm = curp;\n        }\n    }\n    // SA rev-moves\n    vector<int> path = best_perm;\n    int current_cost = best_var;\n    double temp = 10000.0;\n    double alpha = 0.99994;\n    const int MAX_ATT = 10000000;\n    for (int att = 0; att < MAX_ATT; ++att) {\n        int i = randpos(gen), j = randpos(gen);\n        if (i > j) swap(i, j);\n        if (i == j) continue;\n        vector<int> newp = path;\n        reverse(newp.begin() + i, newp.begin() + j + 1);\n        int nc = get_var_cost(newp, Ps, Ds);\n        int delta = nc - current_cost;\n        if (delta < 0 || rdis(gen) < exp(-double(delta) / temp)) {\n            path = move(newp);\n            current_cost = nc;\n            if (nc < best_var) {\n                best_var = nc;\n                best_perm = path;\n            }\n        }\n        temp *= alpha;\n        if (temp < 0.1) break;\n    }\n    improve2opt(best_perm, Ps, Ds);\n    best_var = get_var_cost(best_perm, Ps, Ds);\n    // Final rev check\n    {\n        vector<int> revp = best_perm;\n        reverse(revp.begin(), revp.end());\n        int rvar = get_var_cost(revp, Ps, Ds);\n        if (rvar < best_var) {\n            best_var = rvar;\n            best_perm = revp;\n        }\n    }\n    return {best_var, best_perm};\n}\n\nstruct Sel {\n    vector<int> ids;\n    vector<Point> Ps, Ds;\n    int sum_len = 0;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    vector<Order> orders(1000);\n    for (int i = 0; i < 1000; ++i) {\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        orders[i].p = {a, b};\n        orders[i].d = {c, d};\n        orders[i].id = i + 1;\n    }\n    vector<Sel> sels;\n    // Forward greedy\n    {\n        bool used[1000] = {};\n        vector<int> fsel;\n        Point curr = O;\n        for (int k = 0; k < N; ++k) {\n            int best = -1;\n            int md = INT_MAX;\n            for (int u = 0; u < 1000; ++u) {\n                if (used[u]) continue;\n                int dd = dist(curr, orders[u].p);\n                int tiel = orders[u].len();\n                int bestl = best == -1 ? INT_MAX : orders[best].len();\n                if (dd < md || (dd == md && tiel < bestl)) {\n                    md = dd;\n                    best = u;\n                }\n            }\n            assert(best != -1);\n            fsel.push_back(best);\n            used[best] = true;\n            curr = orders[best].d;\n        }\n        Sel sel;\n        sel.Ps.resize(N);\n        sel.Ds.resize(N);\n        sel.ids.resize(N);\n        for (int k = 0; k < N; ++k) {\n            int oi = fsel[k];\n            sel.Ps[k] = orders[oi].p;\n            sel.Ds[k] = orders[oi].d;\n            sel.ids[k] = orders[oi].id;\n            sel.sum_len += orders[oi].len();\n        }\n        sort(sel.ids.begin(), sel.ids.end());\n        sels.push_back(move(sel));\n    }\n    // Reverse greedy\n    {\n        bool used[1000] = {};\n        vector<int> rsel;\n        Point curr = O;\n        for (int k = 0; k < N; ++k) {\n            int best = -1;\n            int md = INT_MAX;\n            for (int u = 0; u < 1000; ++u) {\n                if (used[u]) continue;\n                int dd = dist(orders[u].d, curr);\n                int tiep = dist(O, orders[u].p);\n                int bestp = best == -1 ? INT_MAX : dist(O, orders[best].p);\n                if (dd < md || (dd == md && tiep < bestp)) {\n                    md = dd;\n                    best = u;\n                }\n            }\n            assert(best != -1);\n            rsel.push_back(best);\n            used[best] = true;\n            curr = orders[best].p;\n        }\n        reverse(rsel.begin(), rsel.end());\n        Sel sel;\n        sel.Ps.resize(N);\n        sel.Ds.resize(N);\n        sel.ids.resize(N);\n        for (int k = 0; k < N; ++k) {\n            int oi = rsel[k];\n            sel.Ps[k] = orders[oi].p;\n            sel.Ds[k] = orders[oi].d;\n            sel.ids[k] = orders[oi].id;\n            sel.sum_len += orders[oi].len();\n        }\n        sort(sel.ids.begin(), sel.ids.end());\n        sels.push_back(move(sel));\n    }\n    // Shortest len\n    {\n        vector<pair<int, int>> sh(1000);\n        for (int i = 0; i < 1000; ++i) sh[i] = {orders[i].len(), i};\n        sort(sh.begin(), sh.end());\n        Sel sel;\n        sel.Ps.resize(N);\n        sel.Ds.resize(N);\n        sel.ids.resize(N);\n        for (int k = 0; k < N; ++k) {\n            int oi = sh[k].second;\n            sel.Ps[k] = orders[oi].p;\n            sel.Ds[k] = orders[oi].d;\n            sel.ids[k] = orders[oi].id;\n            sel.sum_len += orders[oi].len();\n        }\n        sort(sel.ids.begin(), sel.ids.end());\n        sels.push_back(move(sel));\n    }\n    // Solo cheap: O-P + len + D-O\n    {\n        vector<pair<int, int>> sol(1000);\n        for (int i = 0; i < 1000; ++i) {\n            sol[i] = {dist(O, orders[i].p) + orders[i].len() + dist(orders[i].d, O), i};\n        }\n        sort(sol.begin(), sol.end());\n        Sel sel;\n        sel.Ps.resize(N);\n        sel.Ds.resize(N);\n        sel.ids.resize(N);\n        for (int k = 0; k < N; ++k) {\n            int oi = sol[k].second;\n            sel.Ps[k] = orders[oi].p;\n            sel.Ds[k] = orders[oi].d;\n            sel.ids[k] = orders[oi].id;\n            sel.sum_len += orders[oi].len();\n        }\n        sort(sel.ids.begin(), sel.ids.end());\n        sels.push_back(move(sel));\n    }\n    // Close: O-P + O-D\n    {\n        vector<pair<int, int>> cl(1000);\n        for (int i = 0; i < 1000; ++i) {\n            cl[i] = {dist(O, orders[i].p) + dist(O, orders[i].d), i};\n        }\n        sort(cl.begin(), cl.end());\n        Sel sel;\n        sel.Ps.resize(N);\n        sel.Ds.resize(N);\n        sel.ids.resize(N);\n        for (int k = 0; k < N; ++k) {\n            int oi = cl[k].second;\n            sel.Ps[k] = orders[oi].p;\n            sel.Ds[k] = orders[oi].d;\n            sel.ids[k] = orders[oi].id;\n            sel.sum_len += orders[oi].len();\n        }\n        sort(sel.ids.begin(), sel.ids.end());\n        sels.push_back(move(sel));\n    }\n    // Best overall\n    int best_t = INT_MAX;\n    vector<int> best_ids;\n    vector<Point> best_route;\n    for (const auto& sel : sels) {\n        auto [varc, permm] = optimize_rigid(sel.Ps, sel.Ds);\n        int rigid_t = sel.sum_len + varc;\n        vector<Point> rigid_route{O};\n        for (int pi : permm) {\n            rigid_route.push_back(sel.Ps[pi]);\n            rigid_route.push_back(sel.Ds[pi]);\n        }\n        rigid_route.push_back(O);\n        auto [pall_t, pall_route] = get_best_pallpd(sel.Ps, sel.Ds);\n        vector<Point> this_route;\n        int this_t;\n        if (pall_t < rigid_t) {\n            this_route = pall_route;\n            this_t = pall_t;\n        } else {\n            this_route = rigid_route;\n            this_t = rigid_t;\n        }\n        if (this_t < best_t) {\n            best_t = this_t;\n            best_ids = sel.ids;\n            best_route = this_route;\n        }\n    }\n    // Output\n    cout << N;\n    for (int r : best_ids) cout << ' ' << r;\n    cout << '\\n';\n    cout << best_route.size();\n    for (const auto& pt : best_route) {\n        cout << ' ' << pt.x << ' ' << pt.y;\n    }\n    cout << '\\n';\n    return 0;\n}","ahc007":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    const int N = 400;\n    const int M = 1995;\n\n    vector<int> X(N), Y(N);\n    for (int i = 0; i < N; ++i) {\n        cin >> X[i] >> Y[i];\n    }\n\n    vector<pair<int, int>> Edge(M);\n    vector<int> D(M);\n    for (int i = 0; i < M; ++i) {\n        int u, v;\n        cin >> u >> v;\n        Edge[i] = {u, v};\n        double dx = X[u] - X[v];\n        double dy = Y[u] - Y[v];\n        D[i] = (int)round(hypot(dx, dy));\n    }\n\n    vector<int> par(N), sz(N, 1);\n    vector<double> cminx(N), cmaxx(N), cminy(N), cmaxy(N);\n    for (int i = 0; i < N; ++i) {\n        par[i] = i;\n        cminx[i] = cmaxx[i] = X[i];\n        cminy[i] = cmaxy[i] = Y[i];\n    }\n\n    auto find = [&](auto&& self, int x) -> int {\n        return par[x] == x ? x : par[x] = self(self, par[x]);\n    };\n\n    auto rect_dist = [&](int c1, int c2) -> double {\n        double dx = max({0.0, cminx[c1] - cmaxx[c2], cminx[c2] - cmaxx[c1]});\n        double dy = max({0.0, cminy[c1] - cmaxy[c2], cminy[c2] - cmaxy[c1]});\n        return hypot(dx, dy);\n    };\n\n    auto unite = [&](int a, int b) {\n        a = find(find, a);\n        b = find(find, b);\n        if (a == b) return;\n        if (sz[a] < sz[b]) swap(a, b);\n        par[b] = a;\n        sz[a] += sz[b];\n        cminx[a] = min(cminx[a], cminx[b]);\n        cmaxx[a] = max(cmaxx[a], cmaxx[b]);\n        cminy[a] = min(cminy[a], cminy[b]);\n        cmaxy[a] = max(cmaxy[a], cmaxy[b]);\n    };\n\n    int cur_comp = N;\n    for (int i = 0; i < M; ++i) {\n        int l;\n        cin >> l;\n\n        int u = Edge[i].first, v = Edge[i].second;\n        int pu = find(find, u), pv = find(find, v);\n        if (pu == pv) {\n            cout << 0 << '\\n' << flush;\n            continue;\n        }\n\n        int s1 = sz[pu], s2 = sz[pv];\n        int smin = min(s1, s2);\n        double sepd = rect_dist(pu, pv);\n        bool separated = (sepd > 1e-6);\n        double ratio = (double)l / D[i];\n\n        // Scan for future only when necessary\n        double min_fut_d = 1e9;\n        bool need_scan = (smin >= 12) && separated && (cur_comp > 20) && (i < M - 20);\n        if (need_scan) {\n            for (int j = i + 1; j < M; ++j) {\n                int qu = find(find, Edge[j].first);\n                int qv = find(find, Edge[j].second);\n                if ((qu == pu && qv == pv) || (qu == pv && qv == pu)) {\n                    min_fut_d = min(min_fut_d, (double)D[j]);\n                }\n            }\n        }\n        double est_sep = (min_fut_d < 5e8) ? min_fut_d : sepd;\n\n        bool too_bad = (ratio > 2.7);\n        bool is_small = (smin <= 32);\n        bool good_dist = !separated || (l <= 1.85 * est_sep + 2.5);\n\n        bool take = !too_bad && (is_small || good_dist);\n\n        // Urgency\n        int remaining = M - i - 1;\n        int needed = cur_comp - 1;\n        double urgency_ratio = (double)needed / max(1, remaining);\n        bool large_comps = (s1 >= 50 && s2 >= 50);\n        bool urgent = (remaining <= needed * 1.8) || (needed <= 15) || (urgency_ratio > 0.20) ||\n                      (large_comps && urgency_ratio > 0.15);\n        if (urgent) {\n            take = !too_bad;\n        }\n\n        if (take) {\n            unite(u, v);\n            --cur_comp;\n            cout << 1 << '\\n' << flush;\n        } else {\n            cout << 0 << '\\n' << flush;\n        }\n    }\n\n    return 0;\n}","ahc008":"#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef pair<int, int> pii;\n\nconst int SZ = 30;\nbool passable[31][31];\nint DX[4] = {-1, 1, 0, 0};\nint DY[4] = {0, 0, -1, 1};\nchar WALLC[4] = {'u', 'd', 'l', 'r'};\nchar MOVEC[4] = {'U', 'D', 'L', 'R'};\nconst int GCX = 15, GCY = 15;\n\nbool in_bound(int x, int y) { return x >= 1 && x <= SZ && y >= 1 && y <= SZ; }\n\nbool can_wall(const vector<pii>& hpos, const vector<pii>& ppos, int hi, int d, int NN, int MM) {\n  int hx = hpos[hi].first, hy = hpos[hi].second;\n  int tx = hx + DX[d], ty = hy + DY[d];\n  if (!in_bound(tx, ty)) return false;\n  for (int k = 0; k < MM; k++) if (hpos[k].first == tx && hpos[k].second == ty) return false;\n  for (int k = 0; k < NN; k++) if (ppos[k].first == tx && ppos[k].second == ty) return false;\n  for (int dd = 0; dd < 4; dd++) {\n    int ax = tx + DX[dd], ay = ty + DY[dd];\n    if (!in_bound(ax, ay)) continue;\n    for (int k = 0; k < NN; k++) if (ppos[k].first == ax && ppos[k].second == ay) return false;\n  }\n  return true;\n}\n\nstruct CCInfo {\n  int id, size, min_pd, npet;\n  double score;\n  int bary_x, bary_y;\n};\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n\n  int N; cin >> N;\n  vector<pii> ppos(N);\n  vector<int> ptype(N);\n  for (int i = 0; i < N; i++) { int x, y, t; cin >> x >> y >> t; ppos[i]={x,y}; ptype[i]=t; }\n  int M; cin >> M;\n  vector<pii> hpos(M);\n  for (int i = 0; i < M; i++) { int x, y; cin >> x >> y; hpos[i]={x,y}; }\n\n  memset(passable, 0, sizeof(passable));\n  for (int i=1; i<=SZ; i++) for (int j=1; j<=SZ; j++) passable[i][j] = true;\n\n  vector<double> pet_threat(N);\n  double threat_base[6] = {0,1.0,4.0,12.0,65.0,25.0};\n  for (int i=0; i<N; i++) pet_threat[i] = threat_base[ptype[i]];\n\n  int pet_dist[31][31];\n  int comp_id[31][31];\n\n  for (int turn=0; turn<300; turn++) {\n    int sumx=0, sumy=0;\n    for (auto& hp : hpos) { sumx += hp.first; sumy += hp.second; }\n    int cur_cx = sumx / M, cur_cy = sumy / M;\n    int spread = 0;\n    for (auto& hp : hpos) spread = max(spread, abs(hp.first - cur_cx) + abs(hp.second - cur_cy));\n\n    // pet_dist BFS\n    memset(pet_dist, -1, sizeof(pet_dist));\n    queue<pii> q;\n    for (int i=0; i<N; i++) {\n      int px=ppos[i].first, py=ppos[i].second;\n      if (passable[px][py] && pet_dist[px][py]==-1) { pet_dist[px][py]=0; q.push({px,py}); }\n    }\n    while (!q.empty()) {\n      auto [x,y] = q.front(); q.pop();\n      for (int d=0; d<4; d++) {\n        int nx = x + DX[d], ny = y + DY[d];\n        if (in_bound(nx,ny) && passable[nx][ny] && pet_dist[nx][ny]==-1) {\n          pet_dist[nx][ny] = pet_dist[x][y] + 1;\n          q.push({nx,ny});\n        }\n      }\n    }\n\n    int min_human_pd = 999;\n    for (int hi=0; hi<M; hi++) {\n      int hx=hpos[hi].first, hy=hpos[hi].second;\n      int pd = pet_dist[hx][hy]; if (pd==-1) pd=999;\n      min_human_pd = min(min_human_pd, pd);\n    }\n\n    // CC analysis\n    memset(comp_id, -1, sizeof(comp_id));\n    int cid = 0;\n    vector<CCInfo> ccs;\n    vector<int> h_cc(M, -1);\n    double best_cc_score = 0;\n    int best_cid = -1;\n    for (int i=1; i<=SZ; i++) for (int j=1; j<=SZ; j++) {\n      if (passable[i][j] && comp_id[i][j]==-1) {\n        int csize=0, cmin_pd=999, sumx_cc=0, sumy_cc=0, cnp=0;\n        queue<pii> qq;\n        qq.push({i,j}); comp_id[i][j]=cid;\n        while (!qq.empty()) {\n          auto [x,y]=qq.front(); qq.pop();\n          csize++;\n          sumx_cc += x; sumy_cc += y;\n          cmin_pd = min(cmin_pd, pet_dist[x][y]==-1 ? 999 : pet_dist[x][y]);\n          for (int d=0; d<4; d++) {\n            int nx=x+DX[d], ny=y+DY[d];\n            if (in_bound(nx,ny) && passable[nx][ny] && comp_id[nx][ny]==-1) {\n              comp_id[nx][ny]=cid;\n              qq.push({nx,ny});\n            }\n          }\n        }\n        // npet\n        for (int pi=0; pi<N; pi++) {\n          int px=ppos[pi].first, py=ppos[pi].second;\n          if (in_bound(px,py) && comp_id[px][py]==cid) cnp++;\n        }\n        double ccscore = csize * (cmin_pd / 20.0) * pow(0.6, cnp);\n        ccs.push_back({cid, csize, cmin_pd, cnp, ccscore, sumx_cc/csize, sumy_cc/csize});\n        if (ccscore > best_cc_score) { best_cc_score = ccscore; best_cid = cid; }\n        cid++;\n      }\n    }\n\n    // human CC\n    double human_cc_score = 0;\n    if (M>0) {\n      int hx0 = hpos[0].first, hy0 = hpos[0].second;\n      int hcid = comp_id[hx0][hy0];\n      h_cc[0] = hcid;\n      bool all_same = true;\n      for (int hi=1; hi<M; hi++) {\n        int hx=hpos[hi].first, hy=hpos[hi].second;\n        int cc = comp_id[hx][hy];\n        h_cc[hi] = cc;\n        if (cc != hcid) all_same = false;\n      }\n      if (all_same && hcid >=0 && hcid < ccs.size()) human_cc_score = ccs[hcid].score;\n    }\n\n    bool wall_mode = (spread <= 5) || (turn > 140 && spread <= 9) || (min_human_pd <= 3) ||\n                     (human_cc_score > best_cc_score * 0.8);\n\n    pii target = {cur_cx, cur_cy};\n    if (best_cid != -1) {\n      auto& bestcc = ccs[best_cid];\n      target = {bestcc.bary_x, bestcc.bary_y};\n    } else if (turn > 220 && min_human_pd >=4 && spread <=5) {\n      target = {cur_cx, cur_cy};\n    }\n\n    int tx = target.first, ty = target.second;\n    int target_cid = comp_id[tx][ty];\n\n    string action(M, '.');\n    if (wall_mode) {\n      for (int hi=0; hi<M; hi++) {\n        double bsc = -1e100; int bestd=-1;\n        auto [hx, hy] = hpos[hi];\n        for (int d=0; d<4; d++) {\n          if (!can_wall(hpos, ppos, hi, d, N, M)) continue;\n          int wtx = hx + DX[d], wty = hy + DY[d];\n          double sc = 0.0;\n          double dist_c = abs(wtx - cur_cx) + abs(wty - cur_cy) + 2.0;\n          int w_pd = pet_dist[wtx][wty]; if (w_pd==-1) w_pd=999;\n          int w_ccid = comp_id[wtx][wty];\n          double cc_bonus = (w_ccid == target_cid ? w_pd * 0.2 : 0);\n          for (int pi=0; pi<N; pi++) {\n            int pdist = abs(wtx - ppos[pi].first) + abs(wty - ppos[pi].second);\n            sc += pet_threat[pi] / (pdist + 1);\n          }\n          sc /= dist_c;\n          sc += 0.08 * (abs(wtx - cur_cx) + abs(wty - cur_cy)) + cc_bonus;\n          if (sc > bsc) { bsc=sc; bestd=d; }\n        }\n        if (bestd != -1) action[hi] = WALLC[bestd];\n      }\n    } else {\n      for (int hi=0; hi<M; hi++) {\n        auto [hx, hy] = hpos[hi];\n        int mdist = abs(hx-tx) + abs(hy-ty);\n        if (mdist==0) continue;\n        int best_red=-1, best_pd=-1; int bestd=-1;\n        for (int d=0; d<4; d++) {\n          int nx=hx+DX[d], ny=hy+DY[d];\n          if (!in_bound(nx,ny) || !passable[nx][ny]) continue;\n          int nmdist = abs(nx-tx) + abs(ny-ty);\n          int red = mdist - nmdist;\n          int npd = pet_dist[nx][ny]; if (npd==-1) npd=999;\n          if (red > best_red || (red==best_red && npd > best_pd)) {\n            best_red = red; best_pd = npd; bestd = d;\n          }\n        }\n        if (bestd !=-1 && best_red>0) action[hi] = MOVEC[bestd];\n      }\n    }\n\n    cout << \"#\" << turn << \" s:\" << spread << \" pd:\" << min_human_pd << \" wm:\" << wall_mode\n         << \" best_cc:\" << best_cc_score << \" h_cc:\" << human_cc_score << \" t(\" << tx << \",\" << ty << \")\" << endl;\n    cout << action << endl << flush;\n\n    // pets\n    for (int i=0; i<N; i++) {\n      string s; cin >> s;\n      int x=ppos[i].first, y=ppos[i].second;\n      for (char c:s) {\n        if (c=='U') x--; else if (c=='D') x++; else if (c=='L') y--; else if (c=='R') y++;\n      }\n      ppos[i]={x,y};\n    }\n\n    // humans/walls\n    for (int hi=0; hi<M; hi++) {\n      char c=action[hi];\n      if (c=='.') continue;\n      bool ism = isupper((unsigned char)c);\n      int dd=-1;\n      if (ism) {\n        if (c=='U') dd=0; else if (c=='D') dd=1; else if (c=='L') dd=2; else dd=3;\n        hpos[hi].first += DX[dd]; hpos[hi].second += DY[dd];\n      } else {\n        if (c=='u') dd=0; else if (c=='d') dd=1; else if (c=='l') dd=2; else dd=3;\n        int wx = hpos[hi].first + DX[dd], wy = hpos[hi].second + DY[dd];\n        if (in_bound(wx,wy)) passable[wx][wy]=false;\n      }\n    }\n  }\n  return 0;\n}","ahc009":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int ROWS = 20, COLS = 20, N = ROWS * COLS;\n\nint get_row(int pos) { return pos / COLS; }\nint get_col(int pos) { return pos % COLS; }\n\nint attempt_move(int cur_pos, char direction, const vector<string>& h_walls, const vector<string>& v_walls) {\n  int r = get_row(cur_pos), c = get_col(cur_pos);\n  int dr = 0, dc = 0;\n  switch (direction) {\n    case 'U': dr = -1; break;\n    case 'D': dr = 1; break;\n    case 'L': dc = -1; break;\n    case 'R': dc = 1; break;\n    default: return cur_pos;\n  }\n  int nr = r + dr, nc = c + dc;\n  if (nr < 0 || nr >= ROWS || nc < 0 || nc >= COLS) return cur_pos;\n  if (dr != 0) {\n    if (dr > 0 && v_walls[r][c] == '1') return cur_pos;\n    if (dr < 0 && v_walls[nr][c] == '1') return cur_pos;\n  } else {\n    if (dc > 0 && h_walls[r][c] == '1') return cur_pos;\n    if (dc < 0 && h_walls[r][nc] == '1') return cur_pos;\n  }\n  return nr * COLS + nc;\n}\n\nstring shortest_path(int start_pos, int target_pos, const vector<string>& h_walls, const vector<string>& v_walls, const string& dir_order) {\n  vector<int> dist(N, -1), parent(N, -1);\n  dist[start_pos] = 0;\n  queue<int> q; q.push(start_pos);\n  while (!q.empty()) {\n    int u = q.front(); q.pop();\n    if (u == target_pos) break;\n    for (char dch : dir_order) {\n      int v = attempt_move(u, dch, h_walls, v_walls);\n      if (dist[v] == -1) {\n        dist[v] = dist[u] + 1;\n        parent[v] = u;\n        q.push(v);\n      }\n    }\n  }\n  if (dist[target_pos] == -1) return \"\";\n  string path_str;\n  int cur = target_pos;\n  while (cur != start_pos) {\n    int prev = parent[cur];\n    int pr = get_row(prev), pc = get_col(prev);\n    int cr = get_row(cur), cc = get_col(cur);\n    char dch = (cr == pr + 1 ? 'D' : (cr == pr - 1 ? 'U' : (cc == pc + 1 ? 'R' : 'L')));\n    path_str += dch;\n    cur = prev;\n  }\n  reverse(path_str.begin(), path_str.end());\n  return path_str;\n}\n\ndouble evaluate(const string& path_str, double forget_p, int start_pos, int target_pos,\n                const vector<string>& h_walls, const vector<string>& v_walls) {\n  if (start_pos == target_pos) return 401.0;\n  int L = path_str.size();\n  vector<double> curr_prob(N, 0.0);\n  curr_prob[start_pos] = 1.0;\n  double total_es = 0.0;\n  for (int t = 0; t < L; ++t) {\n    char ch = path_str[t];\n    vector<double> next_prob(N, 0.0);\n    double arr_this = 0.0;\n    for (int ps = 0; ps < N; ++ps) {\n      double pr = curr_prob[ps];\n      if (pr < 1e-12) continue;\n      // forget: stay\n      int stay_pos = ps;\n      if (stay_pos == target_pos) {\n        arr_this += pr * forget_p;\n      } else {\n        next_prob[stay_pos] += pr * forget_p;\n      }\n      // move\n      int move_pos = attempt_move(ps, ch, h_walls, v_walls);\n      if (move_pos == target_pos) {\n        arr_this += pr * (1.0 - forget_p);\n      } else {\n        next_prob[move_pos] += pr * (1.0 - forget_p);\n      }\n    }\n    total_es += arr_this * (401.0 - (t + 1));\n    curr_prob = std::move(next_prob);\n  }\n  return total_es;\n}\n\nstruct Cand {\n  string path;\n  double es;\n  bool operator>(const Cand& o) const { return es > o.es; }\n};\n\nint main() {\n  int si, sj, ti, tj;\n  double forget_p;\n  cin >> si >> sj >> ti >> tj >> forget_p;\n  vector<string> h_walls(20);\n  for (auto& s : h_walls) cin >> s;\n  vector<string> v_walls(19);\n  for (auto& s : v_walls) cin >> s;\n  int start_pos = si * COLS + sj;\n  int target_pos = ti * COLS + tj;\n  if (start_pos == target_pos) {\n    cout << \"\" << endl;\n    return 0;\n  }\n\n  // More biased shortest paths\n  vector<string> dir_orders = {\n    \"DRUL\", \"RDUL\", \"DDRR\", \"RRDD\", \"DRDR\", \"UDLR\"\n  };\n  vector<string> base_paths;\n  string sp_all = shortest_path(start_pos, target_pos, h_walls, v_walls, \"UDLR\");\n  base_paths.push_back(sp_all);\n  for (const string& order : dir_orders) {\n    string sp = shortest_path(start_pos, target_pos, h_walls, v_walls, order);\n    if (!sp.empty() && find(base_paths.begin(), base_paths.end(), sp) == base_paths.end()) {\n      base_paths.push_back(sp);\n    }\n  }\n\n  // Adaptive repeats/cycles\n  int max_rpm = max(5, (int)(4.0 / (1.0 - forget_p) + 1));\n  set<string> seen_paths;  // Dedup\n  vector<Cand> candidates;\n  for (const string& bsp : base_paths) {\n    size_t blen = bsp.size();\n    if (blen == 0 || blen > 50) continue;  // Skip invalid/long\n    // Singles\n    double es_single = evaluate(bsp, forget_p, start_pos, target_pos, h_walls, v_walls);\n    candidates.push_back({bsp, es_single});\n    seen_paths.insert(bsp);\n    // Per-move repeats\n    for (int rpm = 2; rpm <= max_rpm; ++rpm) {\n      string cand;\n      cand.reserve(blen * rpm);\n      bool too_long = false;\n      for (char ch : bsp) {\n        if (cand.size() + size_t(rpm) > 200u) {\n          too_long = true;\n          break;\n        }\n        cand.append(size_t(rpm), ch);\n      }\n      if (too_long || cand.empty()) continue;\n      if (seen_paths.count(cand)) continue;\n      double esc = evaluate(cand, forget_p, start_pos, target_pos, h_walls, v_walls);\n      candidates.push_back({cand, esc});\n      seen_paths.insert(cand);\n    }\n    // Path cycles\n    for (int cycles = 2; cycles <= 6; ++cycles) {\n      size_t tlen = blen * cycles;\n      if (tlen > 200) break;\n      string cand;\n      cand.reserve(tlen);\n      for (int i = 0; i < cycles; ++i) {\n        cand += bsp;\n      }\n      if (seen_paths.count(cand)) continue;\n      double esc = evaluate(cand, forget_p, start_pos, target_pos, h_walls, v_walls);\n      candidates.push_back({cand, esc});\n      seen_paths.insert(cand);\n    }\n  }\n\n  // Top candidate\n  sort(candidates.begin(), candidates.end(), greater<Cand>());\n  string best = candidates[0].path;\n  cout << best << endl;\n  return 0;\n}","ahc010":"#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nconst int N = 30;\nconst int NN = N * N;\nconst int SZ = NN * 4;\nint di[4] = {0, -1, 0, 1};\nint dj[4] = {-1, 0, 1, 0};\nint TO[8][4] = {\n    {1, 0, -1, -1},\n    {3, -1, -1, 0},\n    {-1, -1, 3, 2},\n    {-1, 2, 1, -1},\n    {1, 0, 3, 2},\n    {3, 2, 1, 0},\n    {2, -1, 0, -1},\n    {-1, 3, -1, 1}\n};\nint next_tile[8] = {1, 2, 3, 0, 5, 4, 7, 6};\nbool conn[8][4];\n\nint P_IDX[SZ];\nint P_TIME[SZ];\n\nvoid precompute_conn() {\n    memset(conn, 0, sizeof(conn));\n    for (int t = 0; t < 8; t++) {\n        for (int din = 0; din < 4; din++) {\n            int d2 = TO[t][din];\n            if (d2 != -1) conn[t][d2] = true;\n        }\n    }\n}\n\nvector<int> get_cycles(const vector<int>& succ) {\n    vector<int> res;\n    vector<bool> visited(SZ, false);\n    int ts = 0;\n    for (int start = 0; start < SZ; start++) {\n        if (visited[start] || succ[start] == -1) continue;\n        ts++;\n        int cur = start;\n        int pathlen = 0;\n        while (true) {\n            visited[cur] = true;\n            P_IDX[cur] = pathlen++;\n            P_TIME[cur] = ts;\n            int nxt = succ[cur];\n            if (nxt == -1) break;\n            if (P_TIME[nxt] == ts) {\n                int clen = pathlen - P_IDX[nxt];\n                if (clen >= 4) res.push_back(clen);\n                break;\n            }\n            cur = nxt;\n            if (pathlen > SZ) break;\n        }\n    }\n    return res;\n}\n\nll compute_score(const vector<vector<int>>& rot, const vector<vector<int>>& orig, const vector<vector<int>>& eff) {\n    vector<vector<int>> tiles(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = eff[orig[i][j]][rot[i][j]];\n        }\n    }\n    vector<int> succ(SZ, -1);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            for (int d = 0; d < 4; d++) {\n                int tid = (i * N + j) * 4 + d;\n                int d2 = TO[tiles[i][j]][d];\n                if (d2 == -1) continue;\n                int ni = i + di[d2];\n                int nj = j + dj[d2];\n                if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                int nd = (d2 + 2) % 4;\n                int nid = (ni * N + nj) * 4 + nd;\n                succ[tid] = nid;\n            }\n        }\n    }\n    vector<int> cycles = get_cycles(succ);\n    if (cycles.size() < 2) return 0;\n    sort(cycles.rbegin(), cycles.rend());\n    return (ll)cycles[0] * cycles[1];\n}\n\nvector<vector<int>> do_local_opt(vector<vector<int>> rot, const vector<vector<int>>& orig, const vector<vector<int>>& eff,\n                                 const vector<vector<bool>>& active, mt19937& rng) {\n    vector<vector<int>> tiles(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            tiles[i][j] = eff[orig[i][j]][rot[i][j]];\n        }\n    }\n    vector<pair<int, int>> actives;\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            if (active[i][j]) actives.emplace_back(i, j);\n        }\n    }\n    bool improved = true;\n    int iters = 0;\n    while (improved && iters++ < 200) {\n        shuffle(actives.begin(), actives.end(), rng);\n        improved = false;\n        for (auto [i, j] : actives) {\n            int ot = orig[i][j];\n            int curr = rot[i][j];\n            int best_sc = -1;\n            int best_r = curr;\n            for (int tr = 0; tr < 4; tr++) {\n                int tt = eff[ot][tr];\n                int lsc = 0;\n                for (int dd = 0; dd < 4; dd++) {\n                    int ni = i + di[dd];\n                    int nj = j + dj[dd];\n                    if (ni < 0 || ni >= N || nj < 0 || nj >= N) continue;\n                    int opp = (dd + 2) % 4;\n                    int nt = tiles[ni][nj];\n                    if (conn[tt][dd] && conn[nt][opp]) lsc++;\n                }\n                if (lsc > best_sc || (lsc == best_sc && tr < best_r)) {\n                    best_sc = lsc;\n                    best_r = tr;\n                }\n            }\n            if (best_r != curr) {\n                rot[i][j] = best_r;\n                tiles[i][j] = eff[ot][best_r];\n                improved = true;\n            }\n        }\n    }\n    return rot;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    precompute_conn();\n    vector<vector<int>> eff(8, vector<int>(4));\n    for (int t = 0; t < 8; t++) {\n        for (int r = 0; r < 4; r++) {\n            int tt = t;\n            for (int k = 0; k < r; k++) tt = next_tile[tt];\n            eff[t][r] = tt;\n        }\n    }\n    vector<vector<int>> orig(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < N; j++) {\n            orig[i][j] = s[j] - '0';\n        }\n    }\n    vector<vector<int>> best_rot(N, vector<int>(N, 0));\n    ll best_score = -1LL;\n    auto try_config = [&](const vector<vector<int>>& rot) {\n        ll sc = compute_score(rot, orig, eff);\n        if (sc > best_score) {\n            best_score = sc;\n            best_rot = rot;\n        }\n    };\n    vector<vector<bool>> active(N, vector<bool>(N, true));\n    const int NUM_TRIALS = 2048;\n    for (int tr = 0; tr < NUM_TRIALS; tr++) {\n        vector<vector<int>> rot_rand(N, vector<int>(N));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                rot_rand[i][j] = uniform_int_distribution<int>(0, 3)(rng);\n            }\n        }\n        auto rot_opt = do_local_opt(rot_rand, orig, eff, active, rng);\n        try_config(rot_opt);\n    }\n    // All uniform rots\n    for (int k = 0; k < 4; k++) {\n        vector<vector<int>> rot_uni(N, vector<int>(N, k));\n        auto rot_opt = do_local_opt(rot_uni, orig, eff, active, rng);\n        try_config(rot_opt);\n    }\n    // Vertical splits\n    vector<int> vsplits = {10, 12, 15, 18, 20};\n    for (int sp : vsplits) {\n        vector<vector<bool>> act_left(N, vector<bool>(N, false));\n        for (int i = 0; i < N; i++) for (int j = 0; j < sp; j++) act_left[i][j] = true;\n        vector<vector<int>> rot_left(N, vector<int>(N, 0));\n        for (int i = 0; i < N; i++) for (int j = 0; j < sp; j++) rot_left[i][j] = uniform_int_distribution<int>(0, 3)(rng);\n        rot_left = do_local_opt(rot_left, orig, eff, act_left, rng);\n        vector<vector<bool>> act_right(N, vector<bool>(N, false));\n        for (int i = 0; i < N; i++) for (int j = sp; j < N; j++) act_right[i][j] = true;\n        vector<vector<int>> rot_right(N, vector<int>(N, 0));\n        for (int i = 0; i < N; i++) for (int j = sp; j < N; j++) rot_right[i][j] = uniform_int_distribution<int>(0, 3)(rng);\n        rot_right = do_local_opt(rot_right, orig, eff, act_right, rng);\n        vector<vector<int>> rotc(N, vector<int>(N));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                rotc[i][j] = (j < sp ? rot_left[i][j] : rot_right[i][j]);\n            }\n        }\n        // Boundary opt\n        vector<vector<bool>> actb(N, vector<bool>(N, false));\n        if (sp > 0) for (int i = 0; i < N; i++) actb[i][sp - 1] = true;\n        for (int i = 0; i < N; i++) actb[i][sp] = true;\n        rotc = do_local_opt(rotc, orig, eff, actb, rng);\n        try_config(rotc);\n    }\n    // Horizontal splits (symmetric)\n    for (int sp : vsplits) {\n        vector<vector<bool>> act_top(N, vector<bool>(N, false));\n        for (int i = 0; i < sp; i++) for (int j = 0; j < N; j++) act_top[i][j] = true;\n        vector<vector<int>> rot_top(N, vector<int>(N, 0));\n        for (int i = 0; i < sp; i++) for (int j = 0; j < N; j++) rot_top[i][j] = uniform_int_distribution<int>(0, 3)(rng);\n        rot_top = do_local_opt(rot_top, orig, eff, act_top, rng);\n        vector<vector<bool>> act_bot(N, vector<bool>(N, false));\n        for (int i = sp; i < N; i++) for (int j = 0; j < N; j++) act_bot[i][j] = true;\n        vector<vector<int>> rot_bot(N, vector<int>(N, 0));\n        for (int i = sp; i < N; i++) for (int j = 0; j < N; j++) rot_bot[i][j] = uniform_int_distribution<int>(0, 3)(rng);\n        rot_bot = do_local_opt(rot_bot, orig, eff, act_bot, rng);\n        vector<vector<int>> rotc(N, vector<int>(N));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                rotc[i][j] = (i < sp ? rot_top[i][j] : rot_bot[i][j]);\n            }\n        }\n        // Boundary opt\n        vector<vector<bool>> actb(N, vector<bool>(N, false));\n        if (sp > 0) for (int j = 0; j < N; j++) actb[sp - 1][j] = true;\n        for (int j = 0; j < N; j++) actb[sp][j] = true;\n        rotc = do_local_opt(rotc, orig, eff, actb, rng);\n        try_config(rotc);\n    }\n    // Quadrants\n    int qsp = 15;\n    array<vector<vector<bool>>, 4> acts;\n    acts[0] = vector<vector<bool>>(N, vector<bool>(N, false)); // TL\n    acts[1] = vector<vector<bool>>(N, vector<bool>(N, false)); // TR\n    acts[2] = vector<vector<bool>>(N, vector<bool>(N, false)); // BL\n    acts[3] = vector<vector<bool>>(N, vector<bool>(N, false)); // BR\n    for (int qi = 0; qi < 4; qi++) {\n        int si = (qi / 2) * qsp;\n        int sj = (qi % 2) * qsp;\n        for (int i = si; i < si + qsp; i++) {\n            for (int j = sj; j < sj + qsp; j++) {\n                acts[qi][i][j] = true;\n            }\n        }\n    }\n    array<vector<vector<int>>, 4> rots_q;\n    for (int qi = 0; qi < 4; qi++) {\n        rots_q[qi] = vector<vector<int>>(N, vector<int>(N, 0));\n        int si = (qi / 2) * qsp;\n        int sj = (qi % 2) * qsp;\n        for (int i = si; i < si + qsp && i < N; i++) {\n            for (int j = sj; j < sj + qsp && j < N; j++) {\n                rots_q[qi][i][j] = uniform_int_distribution<int>(0, 3)(rng);\n            }\n        }\n        rots_q[qi] = do_local_opt(rots_q[qi], orig, eff, acts[qi], rng);\n    }\n    vector<vector<int>> rotq(N, vector<int>(N));\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            int qi = (i >= qsp ? 2 : 0) + (j >= qsp ? 1 : 0);\n            rotq[i][j] = rots_q[qi][i][j];\n        }\n    }\n    // Quadrant boundaries\n    vector<vector<bool>> actqb(N, vector<bool>(N, false));\n    for (int j = 0; j < N; j++) {\n        actqb[qsp - 1][j] = true;\n        actqb[qsp][j] = true;\n    }\n    for (int i = 0; i < N; i++) {\n        actqb[i][qsp - 1] = true;\n        actqb[i][qsp] = true;\n    }\n    rotq = do_local_opt(rotq, orig, eff, actqb, rng);\n    try_config(rotq);\n    // Final polish on best\n    best_rot = do_local_opt(best_rot, orig, eff, active, rng);\n    try_config(best_rot);\n    // Output\n    string ans = \"\";\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N; j++) {\n            ans += '0' + best_rot[i][j];\n        }\n    }\n    cout << ans << '\\n';\n    return 0;\n}","ahc011":"#include <bits/stdc++.h>\nusing namespace std;\n\nint dx[4] = {-1, 1, 0, 0};\nint dy[4] = {0, 0, -1, 1};\nchar dc[4] = {'U', 'D', 'L', 'R'};\n\nint get_max_tree(const vector<vector<int>>& brd, int ex, int ey, int N) {\n  int emp_id = ex * N + ey;\n  int NN = N * N;\n  vector<vector<int>> adj(NN);\n  // vertical edges\n  for (int i = 0; i < N - 1; ++i) {\n    for (int j = 0; j < N; ++j) {\n      int id1 = i * N + j;\n      int id2 = (i + 1) * N + j;\n      if (id1 == emp_id || id2 == emp_id) continue;\n      int m1 = brd[i][j];\n      int m2 = brd[i + 1][j];\n      if ((m1 & 8) && (m2 & 2)) {\n        adj[id1].push_back(id2);\n        adj[id2].push_back(id1);\n      }\n    }\n  }\n  // horizontal edges\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N - 1; ++j) {\n      int id1 = i * N + j;\n      int id2 = i * N + j + 1;\n      if (id1 == emp_id || id2 == emp_id) continue;\n      int m1 = brd[i][j];\n      int m2 = brd[i][j + 1];\n      if ((m1 & 4) && (m2 & 1)) {\n        adj[id1].push_back(id2);\n        adj[id2].push_back(id1);\n      }\n    }\n  }\n  vector<char> vis(NN, 0);\n  vis[emp_id] = 1;\n  int maxt = 1;\n  for (int sid = 0; sid < NN; ++sid) {\n    if (vis[sid]) continue;\n    stack<int> st;\n    st.push(sid);\n    vis[sid] = 1;\n    int vv = 0;\n    int degsum = 0;\n    while (!st.empty()) {\n      int u = st.top();\n      st.pop();\n      ++vv;\n      degsum += adj[u].size();\n      for (int v : adj[u]) {\n        if (!vis[v]) {\n          vis[v] = 1;\n          st.push(v);\n        }\n      }\n    }\n    int ee = degsum / 2;\n    if (ee == vv - 1) {\n      maxt = max(maxt, vv);\n    }\n  }\n  return maxt;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  srand(time(nullptr));\n  int N;\n  long long T;\n  cin >> N >> T;\n  vector<vector<int>> orig_board(N, vector<int>(N));\n  int ox = -1, oy = -1;\n  for (int i = 0; i < N; ++i) {\n    string s;\n    cin >> s;\n    for (int j = 0; j < N; ++j) {\n      char ch = s[j];\n      int val = isdigit(ch) ? ch - '0' : 10 + (ch - 'a');\n      orig_board[i][j] = val;\n      if (val == 0) {\n        ox = i;\n        oy = j;\n      }\n    }\n  }\n  vector<vector<int>> board = orig_board;\n  int ex = ox, ey = oy;\n  int targetV = N * N - 1;\n  int cur_S = get_max_tree(board, ex, ey, N);\n  if (cur_S == targetV) {\n    cout << \"\" << endl;\n    return 0;\n  }\n  string ans;\n  double temp = 20.0;\n  double cool_rate = 0.999;\n  int max_total_steps = min(100000LL, 10LL * T);\n  int step = 0;\n  while (ans.size() < (size_t)T && step < max_total_steps) {\n    ++step;\n    vector<int> newS(4, -1);\n    vector<bool> can(4, false);\n    int ncan = 0;\n    for (int d = 0; d < 4; ++d) {\n      int nx = ex + dx[d];\n      int ny = ey + dy[d];\n      if (nx >= 0 && nx < N && ny >= 0 && ny < N) {\n        can[d] = true;\n        ++ncan;\n        int tile = board[nx][ny];\n        board[nx][ny] = 0;\n        board[ex][ey] = tile;\n        newS[d] = get_max_tree(board, nx, ny, N);\n        board[nx][ny] = tile;\n        board[ex][ey] = 0;\n      }\n    }\n    if (ncan == 0) break;\n    vector<double> probs(4, 0.0);\n    double sum_p = 0.0;\n    for (int d = 0; d < 4; ++d) {\n      if (can[d]) {\n        double delta = newS[d] - cur_S;\n        probs[d] = exp(delta / temp);\n        sum_p += probs[d];\n      }\n    }\n    double r = (double)rand() / RAND_MAX * sum_p;\n    double cum = 0.0;\n    int chd = -1;\n    for (int d = 0; d < 4; ++d) {\n      if (can[d]) {\n        cum += probs[d];\n        if (cum > r) {\n          chd = d;\n          break;\n        }\n      }\n    }\n    if (chd == -1) {\n      // fallback to best\n      int bestd = 0;\n      int bs = -1e9;\n      for (int d = 0; d < 4; ++d) {\n        if (can[d] && newS[d] > bs) {\n          bs = newS[d];\n          bestd = d;\n        }\n      }\n      chd = bestd;\n    }\n    // perform move\n    int nx = ex + dx[chd];\n    int ny = ey + dy[chd];\n    int tile = board[nx][ny];\n    board[nx][ny] = 0;\n    board[ex][ey] = tile;\n    ex = nx;\n    ey = ny;\n    ans += dc[chd];\n    cur_S = newS[chd];\n    if (cur_S == targetV) {\n      break;\n    }\n    temp *= cool_rate;\n    if (temp < 0.1) temp = 0.1;\n  }\n  cout << ans << endl;\n}","ahc012":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Line {\n  ll px, py, qx, qy;\n};\n\nint side(const Line& l, ll x, ll y) {\n  ll dx1 = l.qx - l.px;\n  ll dy1 = l.qy - l.py;\n  ll dx2 = x - l.px;\n  ll dy2 = y - l.py;\n  __int128 cross = (__int128)dx1 * dy2 - (__int128)dy1 * dx2;\n  if (cross == 0) return 0;\n  return cross > 0 ? 1 : -1;\n}\n\ntuple<ll, ll, ll> exgcd(ll a, ll b) {\n  if (b == 0) return {a, 1, 0};\n  auto [g, x, y] = exgcd(b, a % b);\n  return {g, y, x - (a / b) * y};\n}\n\nint compute_current_score(const vector<vector<int>>& groups, const vector<int>& a) {\n  vector<int> b(11, 0);\n  for (const auto& g : groups) {\n    int sz = g.size();\n    if (sz >= 1 && sz <= 10) ++b[sz];\n  }\n  int sc = 0;\n  for (int d = 1; d <= 10; ++d) sc += min(a[d], b[d]);\n  return sc;\n}\n\nint eval_add(const Line& cand, const vector<vector<int>>& groups, const vector<pair<ll, ll>>& points, const vector<int>& a) {\n  vector<int> tent_b(11, 0);\n  for (const auto& grp : groups) {\n    int L = 0, R = 0;\n    for (int id : grp) {\n      int s = side(cand, points[id].first, points[id].second);\n      if (s == 1) ++L;\n      else if (s == -1) ++R;\n    }\n    if (L >= 1 && L <= 10) ++tent_b[L];\n    if (R >= 1 && R <= 10) ++tent_b[R];\n  }\n  int sc = 0;\n  for (int d = 1; d <= 10; ++d) sc += min(a[d], tent_b[d]);\n  return sc;\n}\n\nvoid add_line(vector<Line>& lines, vector<vector<int>>& groups, const vector<pair<ll, ll>>& points, const Line& newline) {\n  vector<vector<int>> newgroups;\n  newgroups.reserve(groups.size() * 2);\n  for (const auto& grp : groups) {\n    vector<int> left, right;\n    left.reserve(grp.size() / 2);\n    right.reserve(grp.size() / 2);\n    for (int id : grp) {\n      int s = side(newline, points[id].first, points[id].second);\n      if (s == 1) left.push_back(id);\n      else if (s == -1) right.push_back(id);\n    }\n    if (!left.empty()) newgroups.push_back(move(left));\n    if (!right.empty()) newgroups.push_back(move(right));\n  }\n  groups = move(newgroups);\n  lines.push_back(newline);\n}\n\nvector<Line> generate_cands(const vector<vector<int>>& groups, const vector<pair<ll, ll>>& points, uint64_t gseed) {\n  vector<pair<int, int>> large_groups;\n  large_groups.reserve(30);\n  for (int gi = 0; gi < (int)groups.size(); ++gi) {\n    int sz = groups[gi].size();\n    if (sz >= 2) large_groups.emplace_back(-sz, gi);\n  }\n  sort(large_groups.begin(), large_groups.end());\n  large_groups.resize(min(20, (int)large_groups.size()));\n\n  const int MAX_CANDS = 128;\n  vector<Line> cands;\n  cands.reserve(MAX_CANDS);\n  mt19937_64 global_rng(gseed);\n  for (auto [_, gi] : large_groups) {\n    if ((int)cands.size() >= MAX_CANDS) break;\n    const auto& grp = groups[gi];\n    int gsz = grp.size();\n    mt19937_64 rng(gi * 10007LL ^ global_rng());\n    int ngen = 35;\n    int range = 150;\n    for (int tr = 0; tr < ngen && (int)cands.size() < MAX_CANDS; ++tr) {\n      ll aa = (rng() % (2LL * range + 1)) - range;\n      ll bb = (rng() % (2LL * range + 1)) - range;\n      if (aa == 0 && bb == 0) continue;\n      ll gg = __gcd(abs(aa), abs(bb));\n      aa /= gg;\n      bb /= gg;\n      vector<pair<ll, int>> projs(gsz);\n      for (int j = 0; j < gsz; ++j) {\n        int id = grp[j];\n        ll x = points[id].first;\n        ll y = points[id].second;\n        projs[j].first = aa * x + bb * y;\n        projs[j].second = id;\n      }\n      sort(projs.begin(), projs.end());\n      int gm = min(10, gsz - 1);\n      for (int m = 1; m <= gm; ++m) {\n        if ((int)cands.size() >= MAX_CANDS) break;\n        ll ml = projs[m - 1].first;\n        ll mr = projs[m].first;\n        if (ml + 1 >= mr) continue;\n        ll kk = ml + 1;\n        auto [g, x0, y0] = exgcd(aa, bb);\n        if (g == 0 || kk % g != 0) continue;\n        if (g < 0) {\n          g = -g;\n          x0 = -x0;\n          y0 = -y0;\n        }\n        ll mul = kk / g;\n        ll xx = x0 * mul;\n        ll yy = y0 * mul;\n        ll ppx = xx;\n        ll ppy = yy;\n        ll qqx = ppx + bb;\n        ll qqy = ppy - aa;\n        if (abs(ppx) > 1000000000LL || abs(ppy) > 1000000000LL ||\n            abs(qqx) > 1000000000LL || abs(qqy) > 1000000000LL) continue;\n        if (ppx == qqx && ppy == qqy) continue;\n        cands.push_back({ppx, ppy, qqx, qqy});\n      }\n    }\n  }\n  return cands;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, K;\n  cin >> N >> K;\n  vector<int> a(11, 0);\n  int max_score = 0;\n  for (int d = 1; d <= 10; ++d) {\n    cin >> a[d];\n    max_score += a[d];\n  }\n  vector<pair<ll, ll>> points(N);\n  for (auto& p : points) {\n    cin >> p.first >> p.second;\n  }\n  const int num_restarts = 6;\n  vector<Line> best_sol;\n  int best_s = -1;\n  for (int rst = 0; rst < num_restarts; ++rst) {\n    vector<vector<int>> groups;\n    groups.reserve(4096);\n    groups.emplace_back(N);\n    iota(groups.back().begin(), groups.back().end(), 0);\n    vector<Line> curr_lines;\n    curr_lines.reserve(100);\n    uint64_t gseed = (uint64_t)rst * 1000000007ULL + 123456789ULL;\n    while (curr_lines.size() < (size_t)K) {\n      int current_sc = compute_current_score(groups, a);\n      if (current_sc == max_score || (int)groups.size() > 4000) break;\n      auto cands = generate_cands(groups, points, gseed ^ (uint64_t)curr_lines.size());\n      if (cands.empty()) break;\n      int best_new_sc = current_sc;\n      Line best_cand;\n      for (const auto& cand : cands) {\n        int nsc = eval_add(cand, groups, points, a);\n        if (nsc > best_new_sc) {\n          best_new_sc = nsc;\n          best_cand = cand;\n        }\n      }\n      if (best_new_sc <= current_sc) break;\n      add_line(curr_lines, groups, points, best_cand);\n    }\n    int this_s = compute_current_score(groups, a);\n    if (this_s > best_s) {\n      best_s = this_s;\n      best_sol = move(curr_lines);\n    }\n  }\n  cout << best_sol.size() << '\\n';\n  for (const auto& l : best_sol) {\n    cout << l.px << ' ' << l.py << ' ' << l.qx << ' ' << l.qy << '\\n';\n  }\n}","ahc014":"#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 64;\nconst int MAX_SIDE = 30;\nbool occupied[MAXN][MAXN];\nbool used_h[MAXN][MAXN];\nbool used_v[MAXN][MAXN];\nbool used_ne[MAXN][MAXN];\nbool used_nw[MAXN][MAXN];\nint N, c, M, num_occupied;\n\nstruct Move {\n    int x1,y1,x2,y2,x3,y3,x4,y4,rsize,area;\n    long long prio;\n};\n\nvector<Move> cands, ans_moves;\n\nlong long distsq(int x,int y){ long long dx=x-c,dy=y-c; return dx*dx+dy*dy+1; }\n\npair<int,int> getxy(int u,int v){ return {(u+v)/2,(u-v)/2}; }\n\nbool in_grid(int x,int y){ return x>=0&&x<N&&y>=0&&y<N; }\n\nbool check_clean(int x0,int y0,int x1,int y1){\n    int dx=x1-x0,dy=y1-y0,adx=abs(dx),ady=abs(dy);\n    if(adx==0&&ady==0)return false;\n    if(adx&&ady&&adx!=ady)return false;\n    int k=max(adx,ady),sx=dx>0?1:dx<0?-1:0,sy=dy>0?1:dy<0?-1:0;\n    for(int i=1;i<k;++i){\n        int xx=x0+i*sx,yy=y0+i*sy;\n        if(!in_grid(xx,yy)||occupied[xx][yy])return false;\n    }\n    for(int i=0;i<k;++i){\n        int x=x0+i*sx,y=y0+i*sy,nx=x+sx,ny=y+sy;\n        if(!in_grid(x,y)||!in_grid(nx,ny))return false;\n        int lx=min(x,nx),ly=x==lx?y:ny,ry=x==lx?ny:y;\n        if(sx==0){//vert\n            int by=min(y,ny);\n            if(by<0||by>=N-1||used_v[x][by])return false;\n        }else if(sy==0){//horiz\n            if(lx<0||lx>=N-1||used_h[y][lx])return false;\n        }else{//diag\n            if(ry==ly+1){//NE\n                if(lx<0||lx>=N-1||ly<0||ly>=N-1||used_ne[lx][ly])return false;\n            }else if(ry==ly-1){// NW\n                if(lx<0||lx>=N-1||ly<1||ly>=N||used_nw[lx][ly])return false;\n            }else return false;\n        }\n    }\n    return true;\n}\n\nvoid mark_side(int x0,int y0,int x1,int y1){\n    int dx=x1-x0,dy=y1-y0,adx=abs(dx),ady=abs(dy);\n    if(adx==0&&ady==0)return;\n    int k=max(adx,ady),sx=dx>0?1:dx<0?-1:0,sy=dy>0?1:dy<0?-1:0;\n    for(int i=0;i<k;++i){\n        int x=x0+i*sx,y=y0+i*sy,nx=x+sx,ny=y+sy;\n        int lx=min(x,nx),ly=x==lx?y:ny,ry=x==lx?ny:y;\n        if(sx==0){\n            int by=min(y,ny);\n            used_v[x][by]=true;\n        }else if(sy==0){\n            used_h[y][lx]=true;\n        }else{\n            if(ry==ly+1)used_ne[lx][ly]=true;\n            else if(ry==ly-1)used_nw[lx][ly]=true;\n        }\n    }\n}\n\nvoid scan_axis(){\n    cands.clear();\n    for(int w=1;w<=MAX_SIDE;++w)for(int xl=0;xl+w<N;++xl){\n        int xr=xl+w;\n        for(int h=1;h<=MAX_SIDE;++h)for(int yb=0;yb+h<N;++yb){\n            int yt=yb+h;\n            array<pair<int,int>,4> corns{{{xl,yb},{xr,yb},{xr,yt},{xl,yt}}};\n            int cnt=0;\n            for(auto [xx,yy]:corns)if(occupied[xx][yy])++cnt;\n            if(cnt!=3)continue;\n            int miss=-1;\n            for(int i=0;i<4;++i)if(!occupied[corns[i].first][corns[i].second]){miss=i;break;}\n            if(miss==-1|| !check_clean(corns[0].first,corns[0].second,corns[1].first,corns[1].second)||\n                       !check_clean(corns[1].first,corns[1].second,corns[2].first,corns[2].second)||\n                       !check_clean(corns[2].first,corns[2].second,corns[3].first,corns[3].second)||\n                       !check_clean(corns[3].first,corns[3].second,corns[0].first,corns[0].second))continue;\n            int i2=(miss+1)%4,i3=(miss+2)%4,i4=(miss+3)%4;\n            Move m;\n            m.x1=corns[miss].first;m.y1=corns[miss].second;\n            m.x2=corns[i2].first;m.y2=corns[i2].second;\n            m.x3=corns[i3].first;m.y3=corns[i3].second;\n            m.x4=corns[i4].first;m.y4=corns[i4].second;\n            m.rsize=w+h;m.area=w*h;m.prio=0;\n            cands.push_back(m);\n        }\n    }\n}\n\nvoid scan_45(int parity){\n    vector<int> us,vs;\n    for(int u=parity;u<=2*(N-1);u+=2)us.push_back(u);\n    int vmin=-(N-1),voff=parity?1:0;\n    for(int v=vmin+voff;v<=N-1;v+=2)vs.push_back(v);\n    for(size_t i=0;i<us.size();++i)for(size_t j=i+1;j<us.size();++j){\n        int u1=us[i],u2=us[j];\n        for(size_t k=0;k<vs.size();++k)for(size_t l=k+1;l<vs.size();++l){\n            int v1=vs[k],v2=vs[l];\n            auto [x0,y0]=getxy(u1,v1);if(!in_grid(x0,y0))continue;\n            auto [x1,y1]=getxy(u1,v2);if(!in_grid(x1,y1))continue;\n            auto [x2,y2]=getxy(u2,v2);if(!in_grid(x2,y2))continue;\n            auto [x3,y3]=getxy(u2,v1);if(!in_grid(x3,y3))continue;\n            array<pair<int,int>,4> corns{{{x0,y0},{x1,y1},{x2,y2},{x3,y3}}};\n            int cnt=0;\n            for(auto [xx,yy]:corns)if(occupied[xx][yy])++cnt;\n            if(cnt!=3)continue;\n            int miss=-1;\n            for(int p=0;p<4;++p)if(!occupied[corns[p].first][corns[p].second]){miss=p;break;}\n            if(miss==-1)continue;\n            if(!check_clean(x0,y0,x1,y1)||!check_clean(x1,y1,x2,y2)||\n               !check_clean(x2,y2,x3,y3)||!check_clean(x3,y3,x0,y0))continue;\n            int i2=(miss+1)%4,i3=(miss+2)%4,i4=(miss+3)%4;\n            int du=(u2-u1)/2,dv=abs(v2-v1)/2;\n            Move m;\n            m.x1=corns[miss].first;m.y1=corns[miss].second;\n            m.x2=corns[i2].first;m.y2=corns[i2].second;\n            m.x3=corns[i3].first;m.y3=corns[i3].second;\n            m.x4=corns[i4].first;m.y4=corns[i4].second;\n            m.rsize=du+dv;m.area=du*dv;m.prio=0;\n            cands.push_back(m);\n        }\n    }\n}\n\nint main(){\n    ios::sync_with_stdio(false);cin.tie(0);\n    clock_t clk=clock();\n    cin>>N>>M;c=(N-1)/2;num_occupied=M;\n    memset(occupied,0,sizeof(occupied));\n    memset(used_h,0,sizeof(used_h));memset(used_v,0,sizeof(used_v));\n    memset(used_ne,0,sizeof(used_ne));memset(used_nw,0,sizeof(used_nw));\n    for(int i=0;i<M;++i){int x,y;cin>>x>>y;occupied[x][y]=true;}\n    int phase=0,stalls=0,max_stalls=8;\n    while(true){\n        double t=(clock()-clk)/(double)CLOCKS_PER_SEC;\n        if(t>4.85||num_occupied>N*N*0.93||stalls>=max_stalls)break;\n        scan_axis();\n        scan_45(0);scan_45(1);\n        if(cands.empty()){++stalls;continue;}\n        auto cmp = [&](const Move& a,const Move& b){\n            long long da=distsq(a.x1,a.y1),db=distsq(b.x1,b.y1);\n            long long sa=a.rsize,sb=b.rsize;\n            long long pra=sa*sa + 1000000000LL/(sa+1);\n            long long prb=sb*sb + 1000000000LL/(sb+1);\n            bool outer=phase%2==0,large=(phase/2)%2==0;\n            long long pa=(outer?da:-da)*100LL + (large?pra:-pra)*10LL + a.area;\n            long long pb=(outer?db:-db)*100LL + (large?prb:-prb)*10LL + b.area;\n            return pa > pb;\n        };\n        sort(cands.begin(),cands.end(),cmp);\n        int added=0,topk=min(8192,(int)cands.size());\n        for(int i=0;i<topk;++i){\n            const auto& m=cands[i];\n            double t2=(clock()-clk)/(double)CLOCKS_PER_SEC;if(t2>4.9)break;\n            if(occupied[m.x1][m.y1])continue;\n            if(check_clean(m.x1,m.y1,m.x2,m.y2)&&check_clean(m.x2,m.y2,m.x3,m.y3)&&\n               check_clean(m.x3,m.y3,m.x4,m.y4)&&check_clean(m.x4,m.y4,m.x1,m.y1)){\n                ans_moves.push_back(m);\n                occupied[m.x1][m.y1]=true;\n                mark_side(m.x1,m.y1,m.x2,m.y2);\n                mark_side(m.x2,m.y2,m.x3,m.y3);\n                mark_side(m.x3,m.y3,m.x4,m.y4);\n                mark_side(m.x4,m.y4,m.x1,m.y1);\n                ++num_occupied;++added;\n            }\n        }\n        if(added==0){++stalls;phase=(phase+1)%4;}\n        else stalls=0;\n    }\n    cout<<ans_moves.size()<<'\\n';\n    for(auto& m:ans_moves){\n        cout<<m.x1<<' '<<m.y1<<' '<<m.x2<<' '<<m.y2<<' '<<m.x3<<' '<<m.y3<<' '<<m.x4<<' '<<m.y4<<'\\n';\n    }\n}","ahc015":"#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int, int>;\nusing vv = vector<vector<int>>;\n\npair<int, int> get_new_pos(const vv& g, int pr, int pc, char dir) {\n    int nr = pr, nc = pc;\n    if (dir == 'L') {\n        int rank_left = 0;\n        for (int c = 0; c < pc; ++c) if (g[pr][c] != 0) ++rank_left;\n        nc = rank_left;\n    } else if (dir == 'R') {\n        int total = 0;\n        for (int c = 0; c < 10; ++c) if (g[pr][c] != 0) ++total;\n        int rank_left = 0;\n        for (int c = 0; c < pc; ++c) if (g[pr][c] != 0) ++rank_left;\n        nc = (10 - total) + rank_left;\n    } else if (dir == 'F') {\n        int rank_top = 0;\n        for (int r = 0; r < pr; ++r) if (g[r][pc] != 0) ++rank_top;\n        nr = rank_top;\n    } else if (dir == 'B') {\n        int total = 0;\n        for (int r = 0; r < 10; ++r) if (g[r][pc] != 0) ++total;\n        int rank_top = 0;\n        for (int r = 0; r < pr; ++r) if (g[r][pc] != 0) ++rank_top;\n        nr = (10 - total) + rank_top;\n    }\n    return {nr, nc};\n}\n\nvoid simulate(vv& g, char dir) {\n    if (dir == 'F') {\n        for (int c = 0; c < 10; ++c) {\n            vector<int> lis;\n            for (int r = 0; r < 10; ++r) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            for (int r = 0; r < sz; ++r) g[r][c] = lis[r];\n            for (int r = sz; r < 10; ++r) g[r][c] = 0;\n        }\n    } else if (dir == 'B') {\n        for (int c = 0; c < 10; ++c) {\n            vector<int> lis;\n            for (int r = 0; r < 10; ++r) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            int off = 10 - sz;\n            for (int r = 0; r < off; ++r) g[r][c] = 0;\n            for (int r = 0; r < sz; ++r) g[off + r][c] = lis[r];\n        }\n    } else if (dir == 'L') {\n        for (int r = 0; r < 10; ++r) {\n            vector<int> lis;\n            for (int c = 0; c < 10; ++c) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            for (int c = 0; c < sz; ++c) g[r][c] = lis[c];\n            for (int c = sz; c < 10; ++c) g[r][c] = 0;\n        }\n    } else if (dir == 'R') {\n        for (int r = 0; r < 10; ++r) {\n            vector<int> lis;\n            for (int c = 0; c < 10; ++c) {\n                if (g[r][c] != 0) lis.push_back(g[r][c]);\n            }\n            int sz = lis.size();\n            int off = 10 - sz;\n            for (int c = 0; c < off; ++c) g[r][c] = 0;\n            for (int c = 0; c < sz; ++c) g[r][off + c] = lis[c];\n        }\n    }\n}\n\nlong long compute(const vv& g) {\n    bool vis[10][10] = {};\n    int dr[] = {-1, 0, 1, 0};\n    int dc[] = {0, 1, 0, -1};\n    long long sumsq = 0;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            if (g[r][c] != 0 && !vis[r][c]) {\n                int flav = g[r][c];\n                queue<pii> q;\n                q.emplace(r, c);\n                vis[r][c] = true;\n                int sz = 1;\n                while (!q.empty()) {\n                    auto [x, y] = q.front();\n                    q.pop();\n                    for (int d = 0; d < 4; ++d) {\n                        int nr = x + dr[d];\n                        int nc = y + dc[d];\n                        if (nr >= 0 && nr < 10 && nc >= 0 && nc < 10 &&\n                            !vis[nr][nc] && g[nr][nc] == flav) {\n                            vis[nr][nc] = true;\n                            q.emplace(nr, nc);\n                            ++sz;\n                        }\n                    }\n                }\n                sumsq += 1LL * sz * sz;\n            }\n        }\n    }\n    return sumsq;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    vector<int> f(101);\n    for (int i = 1; i <= 100; ++i) {\n        cin >> f[i];\n    }\n    vv grid(10, vector<int>(10, 0));\n    set<pii> empties;\n    for (int r = 0; r < 10; ++r) {\n        for (int c = 0; c < 10; ++c) {\n            empties.emplace(r, c);\n        }\n    }\n    string dirs = \"FBLR\";\n    int dr[] = {-1, 0, 1, 0};\n    int dc[] = {0, 1, 0, -1};\n    for (int t = 1; t <= 100; ++t) {\n        int p;\n        cin >> p;\n        auto it = empties.begin();\n        advance(it, p - 1);\n        auto [pr, pc] = *it;\n        grid[pr][pc] = f[t];\n        empties.erase(it);\n        int flav = f[t];\n\n        long long best_sc = -1;\n        int best_md = 999;\n        int best_pot = -1;\n        int best_dc = 999;\n        char best_dir = 'Z';\n        for (char d : dirs) {\n            vv temp = grid;\n            simulate(temp, d);\n            long long sc = compute(temp);\n            auto [nr, nc] = get_new_pos(grid, pr, pc, d);\n\n            // min dist to nearest other same\n            int mind = 11;\n            for (int i = 0; i < 10; ++i) {\n                for (int j = 0; j < 10; ++j) {\n                    if (temp[i][j] == flav && (i != nr || j != nc)) {\n                        int dd = abs(i - nr) + abs(j - nc);\n                        if (dd < mind) mind = dd;\n                    }\n                }\n            }\n\n            // line potential and CoM\n            vector<int> rowc(10, 0), colc(10, 0);\n            int sumr = 0, sumc_ = 0, num = 0;\n            for (int i = 0; i < 10; ++i) {\n                for (int j = 0; j < 10; ++j) {\n                    if (temp[i][j] == flav) {\n                        rowc[i]++;\n                        colc[j]++;\n                        sumr += i;\n                        sumc_ += j;\n                        num++;\n                    }\n                }\n            }\n            int pot = rowc[nr] + colc[nc] - 2;\n            int meanr = (num == 0 ? nr : sumr / num);\n            int meanc = (num == 0 ? nc : sumc_ / num);\n            int distc = abs(nr - meanr) + abs(nc - meanc);\n\n            // compare\n            bool better = false;\n            if (sc > best_sc) better = true;\n            else if (sc == best_sc) {\n                if (mind < best_md) better = true;\n                else if (mind == best_md) {\n                    if (pot > best_pot) better = true;\n                    else if (pot == best_pot) {\n                        if (distc < best_dc) better = true;\n                        else if (distc == best_dc) {\n                            if (d < best_dir) better = true;\n                        }\n                    }\n                }\n            }\n            if (better) {\n                best_sc = sc;\n                best_md = mind;\n                best_pot = pot;\n                best_dc = distc;\n                best_dir = d;\n            }\n        }\n        cout << best_dir << endl;\n        simulate(grid, best_dir);\n    }\n    return 0;\n}","ahc016":"#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <limits>\nusing namespace std;\n\nusing Eigen::MatrixXd;\nusing Eigen::SelfAdjointEigenSolver;\nusing Eigen::VectorXd;\n\nusing Feature = vector<double>;\n\nint tri_index(int N, int i, int j) {\n  if (i > j) swap(i, j);\n  int pos = 0;\n  for (int a = 0; a < i; ++a) {\n    pos += N - 1 - a;\n  }\n  pos += j - i - 1;\n  return pos;\n}\n\nstring make_clique(int s, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  s = min(s, N);\n  for (int i = 0; i < s; ++i) {\n    for (int j = i + 1; j < s; ++j) {\n      g[tri_index(N, i, j)] = '1';\n    }\n  }\n  return g;\n}\n\nstring make_star(int leaves, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  leaves = min(leaves, N - 1);\n  for (int lv = 1; lv <= leaves; ++lv) {\n    g[tri_index(N, 0, lv)] = '1';\n  }\n  return g;\n}\n\nstring make_bipart(int a, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  a = min(a, N / 2);\n  int left = a;\n  for (int i = 0; i < left; ++i) {\n    for (int jj = 0; jj < N - left; ++jj) {\n      int j = left + jj;\n      g[tri_index(N, i, j)] = '1';\n    }\n  }\n  return g;\n}\n\nstring make_path(int s, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  s = min(s, N);\n  for (int i = 0; i < s - 1; ++i) {\n    g[tri_index(N, i, i + 1)] = '1';\n  }\n  return g;\n}\n\nstring make_cycle(int c, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  c = min(c, N);\n  if (c < 3) return make_path(c, N);\n  for (int i = 0; i < c; ++i) {\n    int j = (i + 1) % c;\n    g[tri_index(N, i, j)] = '1';\n  }\n  return g;\n}\n\nstring make_wheel(int rim, int N) {\n  int B = N * (N - 1) / 2;\n  string g(B, '0');\n  rim = min(rim, N - 1);\n  int hub = 0;\n  // hub to rim\n  for (int i = 1; i <= rim; ++i) {\n    g[tri_index(N, hub, i)] = '1';\n  }\n  // rim cycle\n  if (rim >= 2) {\n    for (int i = 1; i < rim; ++i) {\n      g[tri_index(N, i, i + 1)] = '1';\n    }\n    g[tri_index(N, rim, 1)] = '1';\n  }\n  return g;\n}\n\nFeature get_feature(const string& s, int N, double flip_prob) {\n  int B = N * (N - 1) / 2;\n  assert((int)s.size() == B);\n  MatrixXd A(N, N);\n  A.setZero();\n  double denom = 1.0 - 2.0 * flip_prob;\n  bool denoise = (flip_prob > 1e-12);\n  for (int i = 0; i < N; ++i) {\n    for (int j = i + 1; j < N; ++j) {\n      double val_obs = s[tri_index(N, i, j)] - '0';\n      double val = denoise ? (val_obs - flip_prob) / denom : val_obs;\n      A(i, j) = val;\n      A(j, i) = val;\n    }\n  }\n  // Adjacency eigenvalues\n  SelfAdjointEigenSolver<MatrixXd> solverA(A);\n  VectorXd evA = solverA.eigenvalues();\n  vector<double> lambdaA(N);\n  for (int k = 0; k < N; ++k) lambdaA[k] = evA(k);\n  sort(lambdaA.rbegin(), lambdaA.rend());\n\n  // Sorted degrees descending\n  VectorXd deg = A.rowwise().sum();\n  vector<double> sdeg(N);\n  for (int k = 0; k < N; ++k) sdeg[k] = deg(k);\n  sort(sdeg.rbegin(), sdeg.rend());\n\n  // Laplacian eigenvalues\n  MatrixXd L(N, N);\n  L.setZero();\n  L.diagonal() = deg;\n  L -= A;\n  SelfAdjointEigenSolver<MatrixXd> solverL(L);\n  VectorXd evL = solverL.eigenvalues();\n  vector<double> lambdaL(N);\n  for (int k = 0; k < N; ++k) lambdaL[k] = evL(k);\n  sort(lambdaL.rbegin(), lambdaL.rend());\n\n  // Concatenate\n  Feature feat;\n  feat.reserve(3 * N);\n  feat.insert(feat.end(), lambdaA.begin(), lambdaA.end());\n  feat.insert(feat.end(), sdeg.begin(), sdeg.end());\n  feat.insert(feat.end(), lambdaL.begin(), lambdaL.end());\n  return feat;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n  int M;\n  double eps;\n  cin >> M >> eps;\n  int N = min(100, max(4, (int)(20 + 80 * (1 - eps))));\n  cout << N << '\\n';\n\n  vector<string> cand_repr;\n  vector<Feature> cand_feat;\n  auto add_cand = [&](const string& g) {\n    cand_repr.push_back(g);\n    cand_feat.push_back(get_feature(g, N, 0.0));\n  };\n  // Cliques\n  for (int s = 1; s <= N; ++s) {\n    add_cand(make_clique(s, N));\n  }\n  // Stars\n  for (int l = 1; l < N; ++l) {\n    add_cand(make_star(l, N));\n  }\n  // Bipartites\n  for (int a = 1; a <= N / 2; ++a) {\n    add_cand(make_bipart(a, N));\n  }\n  // Paths\n  for (int s = 2; s <= N; ++s) {\n    add_cand(make_path(s, N));\n  }\n  // Cycles\n  for (int c = 3; c <= N; ++c) {\n    add_cand(make_cycle(c, N));\n  }\n  // Wheels\n  for (int rim = 3; rim < N; ++rim) {\n    add_cand(make_wheel(rim, N));\n  }\n  int nc = cand_feat.size();\n  vector<bool> used(nc, false);\n  vector<int> chosen;\n  for (int ck = 0; ck < M; ++ck) {\n    int best_ci = -1;\n    double max_mind = -numeric_limits<double>::infinity();\n    for (int ci = 0; ci < nc; ++ci) {\n      if (used[ci]) continue;\n      double mind = numeric_limits<double>::infinity();\n      for (int pi : chosen) {\n        double dd = 0.0;\n        const auto& f1 = cand_feat[ci];\n        const auto& f2 = cand_feat[pi];\n        for (size_t j = 0; j < f1.size(); ++j) {\n          double dif = f1[j] - f2[j];\n          dd += dif * dif;\n        }\n        mind = min(mind, dd);\n      }\n      if (mind > max_mind) {\n        max_mind = mind;\n        best_ci = ci;\n      }\n    }\n    assert(best_ci != -1);\n    used[best_ci] = true;\n    chosen.push_back(best_ci);\n  }\n\n  vector<Feature> codebook_feat(M);\n  for (int k = 0; k < M; ++k) {\n    int ci = chosen[k];\n    cout << cand_repr[ci] << '\\n';\n    codebook_feat[k] = cand_feat[ci];\n  }\n  cout << std::flush;\n\n  for (int q = 0; q < 100; ++q) {\n    string H;\n    cin >> H;\n    Feature fh = get_feature(H, N, eps);\n    double best_d = numeric_limits<double>::infinity();\n    int tk = 0;\n    for (int k = 0; k < M; ++k) {\n      double dd = 0.0;\n      const auto& fk = codebook_feat[k];\n      for (size_t j = 0; j < fh.size(); ++j) {\n        double dif = fh[j] - fk[j];\n        dd += dif * dif;\n      }\n      if (dd < best_d) {\n        best_d = dd;\n        tk = k;\n      }\n    }\n    cout << tk << '\\n' << std::flush;\n  }\n  return 0;\n}","ahc017":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing pli = pair<ll, int>;\nusing tp = tuple<int, int, ll>;  // to, eid, w\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, D, K;\n  cin >> N >> M >> D >> K;\n  struct Edge {\n    int u, v;\n    ll w;\n  };\n  vector<Edge> edges(M);\n  vector<vector<tp>> adj(N + 1);\n  for (int i = 0; i < M; i++) {\n    int u, v;\n    ll w;\n    cin >> u >> v >> w;\n    edges[i] = {u, v, w};\n    adj[u].emplace_back(v, i, w);\n    adj[v].emplace_back(u, i, w);\n  }\n  for (int i = 0; i < N; i++) {\n    int dummy1, dummy2;\n    cin >> dummy1 >> dummy2;\n  }\n  const ll INF = 4LL * (1LL << 60);  // large enough\n  const ll UNREACH = 1000000000LL;\n  auto dijk = [&](int s, int fa, int fb) -> vector<ll> {\n    vector<ll> d(N + 1, INF);\n    d[s] = 0;\n    priority_queue<pli, vector<pli>, greater<pli>> pq;\n    pq.emplace(0, s);\n    while (!pq.empty()) {\n      auto [cost, u] = pq.top();\n      pq.pop();\n      if (cost > d[u]) continue;\n      for (auto [v, eid, w] : adj[u]) {\n        if ((u == fa && v == fb) || (u == fb && v == fa)) continue;\n        if (d[v] > d[u] + w) {\n          d[v] = d[u] + w;\n          pq.emplace(d[v], v);\n        }\n      }\n    }\n    return d;\n  };\n  vector<ll> slack(M);\n  for (int i = 0; i < M; i++) {\n    int u = edges[i].u;\n    int v = edges[i].v;\n    ll w = edges[i].w;\n    auto dd = dijk(u, u, v);\n    ll alt = dd[v];\n    if (alt >= INF / 2) alt = UNREACH;\n    slack[i] = alt - w;\n  }\n  // small slack: safe to remove first (small increase)\n  vector<int> order(M);\n  iota(order.begin(), order.end(), 0);\n  sort(order.begin(), order.end(), [&](int a, int b) {\n    if (slack[a] != slack[b]) return slack[a] < slack[b];\n    return a < b;\n  });\n  // round-robin assign to days\n  vector<vector<int>> groups(D);\n  int day_idx = 0;\n  for (int eid : order) {\n    groups[day_idx].push_back(eid);\n    day_idx = (day_idx + 1) % D;\n  }\n  // build assignment\n  vector<int> assignment(M);\n  for (int d = 0; d < D; d++) {\n    for (int eid : groups[d]) {\n      assignment[eid] = d + 1;\n    }\n  }\n  // output\n  for (int i = 0; i < M; i++) {\n    if (i > 0) cout << \" \";\n    cout << assignment[i];\n  }\n  cout << \"\\n\";\n  return 0;\n}","ahc019":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Rod {\n    int dir, fix1, fix2, st, len;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int D;\n    cin >> D;\n    vector<vector<string>> f(2, vector<string>(D));\n    vector<vector<string>> r(2, vector<string>(D));\n    for (int i = 0; i < 2; ++i) {\n        for (int z = 0; z < D; ++z) cin >> f[i][z];\n        for (int z = 0; z < D; ++z) cin >> r[i][z];\n    }\n    const int MAXND = 200;\n    const int VOL = D * D * D;\n    vector<vector<int>> bb(2, vector<int>(VOL, 0));\n    bitset<MAXND> remain_f[2], remain_r[2];\n    int DD = D * D;\n    for (int i = 0; i < 2; ++i) {\n        remain_f[i].reset();\n        remain_r[i].reset();\n        for (int z = 0; z < D; ++z) {\n            for (int k = 0; k < D; ++k) {\n                if (f[i][z][k] == '1') remain_f[i][z * D + k] = 1;\n                if (r[i][z][k] == '1') remain_r[i][z * D + k] = 1;\n            }\n        }\n    }\n    vector<Rod> cands;\n    // Dir 0: vary x, fix y=fix1, z=fix2\n    for (int y = 0; y < D; ++y) {\n        for (int z = 0; z < D; ++z) {\n            if (r[0][z][y] != '1' || r[1][z][y] != '1') continue;\n            int pos = 0;\n            while (pos < D) {\n                if (f[0][z][pos] != '1' || f[1][z][pos] != '1') {\n                    ++pos;\n                    continue;\n                }\n                int s = pos;\n                while (pos < D && f[0][z][pos] == '1' && f[1][z][pos] == '1') ++pos;\n                cands.push_back({0, y, z, s, pos - s});\n            }\n        }\n    }\n    // Dir 1: vary y, fix x=fix1, z=fix2\n    for (int x = 0; x < D; ++x) {\n        for (int z = 0; z < D; ++z) {\n            if (f[0][z][x] != '1' || f[1][z][x] != '1') continue;\n            int pos = 0;\n            while (pos < D) {\n                if (r[0][z][pos] != '1' || r[1][z][pos] != '1') {\n                    ++pos;\n                    continue;\n                }\n                int s = pos;\n                while (pos < D && r[0][z][pos] == '1' && r[1][z][pos] == '1') ++pos;\n                cands.push_back({1, x, z, s, pos - s});\n            }\n        }\n    }\n    // Dir 2: vary z, fix x=fix1, y=fix2\n    for (int x = 0; x < D; ++x) {\n        for (int y = 0; y < D; ++y) {\n            int pos = 0;\n            while (pos < D) {\n                bool p0 = (f[0][pos][x] == '1' && r[0][pos][y] == '1');\n                bool p1 = (f[1][pos][x] == '1' && r[1][pos][y] == '1');\n                if (!(p0 && p1)) {\n                    ++pos;\n                    continue;\n                }\n                int s = pos;\n                while (pos < D) {\n                    p0 = (f[0][pos][x] == '1' && r[0][pos][y] == '1');\n                    p1 = (f[1][pos][x] == '1' && r[1][pos][y] == '1');\n                    if (!(p0 && p1)) break;\n                    ++pos;\n                }\n                cands.push_back({2, x, y, s, pos - s});\n            }\n        }\n    }\n    // Sort longest first\n    sort(cands.begin(), cands.end(), [](const Rod& a, const Rod& b) {\n        if (a.len != b.len) return a.len > b.len;\n        return a.dir < b.dir;\n    });\n    int block_id = 1;\n    for (auto& rd : cands) {\n        if (rd.len == 0) continue;\n        // Check\n        bool ok = true;\n        for (int p = 0; p < rd.len; ++p) {\n            int x, y, z;\n            if (rd.dir == 0) {\n                x = rd.st + p;\n                y = rd.fix1;\n                z = rd.fix2;\n            } else if (rd.dir == 1) {\n                x = rd.fix1;\n                y = rd.st + p;\n                z = rd.fix2;\n            } else {\n                x = rd.fix1;\n                y = rd.fix2;\n                z = rd.st + p;\n            }\n            int fidx = z * D + x;\n            int ridx = z * D + y;\n            if (!remain_f[0][fidx] || !remain_f[1][fidx] || !remain_r[0][ridx] || !remain_r[1][ridx]) {\n                ok = false;\n                break;\n            }\n        }\n        if (!ok) continue;\n        // Place\n        for (int p = 0; p < rd.len; ++p) {\n            int x, y, z;\n            if (rd.dir == 0) {\n                x = rd.st + p;\n                y = rd.fix1;\n                z = rd.fix2;\n            } else if (rd.dir == 1) {\n                x = rd.fix1;\n                y = rd.st + p;\n                z = rd.fix2;\n            } else {\n                x = rd.fix1;\n                y = rd.fix2;\n                z = rd.st + p;\n            }\n            int idx = x * D * D + y * D + z;\n            bb[0][idx] = block_id;\n            bb[1][idx] = block_id;\n            int fidx = z * D + x;\n            int ridx = z * D + y;\n            remain_f[0][fidx] = 0;\n            remain_f[1][fidx] = 0;\n            remain_r[0][ridx] = 0;\n            remain_r[1][ridx] = 0;\n        }\n        ++block_id;\n    }\n    // Remaining 1x1 sharing\n    vector<array<int, 3>> poss_rem[2];\n    for (int cas = 0; cas < 2; ++cas) {\n        poss_rem[cas].clear();\n        for (int z = 0; z < D; ++z) {\n            vector<int> rem_rx, rem_ry, orig_rx, orig_ry;\n            for (int k = 0; k < D; ++k) {\n                int pidx = z * D + k;\n                if (remain_f[cas][pidx]) rem_rx.push_back(k);\n                if (f[cas][z][k] == '1') orig_rx.push_back(k);\n                if (remain_r[cas][pidx]) rem_ry.push_back(k);\n                if (r[cas][z][k] == '1') orig_ry.push_back(k);\n            }\n            int nrrx = rem_rx.size();\n            int nrry = rem_ry.size();\n            if (nrrx == 0 && nrry == 0) continue;\n            int px_extra = orig_rx.empty() ? -1 : orig_rx[0];\n            int py_extra = orig_ry.empty() ? -1 : orig_ry[0];\n            if (nrrx >= nrry) {\n                for (int j = 0; j < nrry; ++j) {\n                    poss_rem[cas].push_back({rem_rx[j], rem_ry[j], z});\n                }\n                for (int j = nrry; j < nrrx; ++j) {\n                    if (py_extra == -1) continue;\n                    poss_rem[cas].push_back({rem_rx[j], py_extra, z});\n                }\n            } else {\n                for (int j = 0; j < nrrx; ++j) {\n                    poss_rem[cas].push_back({rem_rx[j], rem_ry[j], z});\n                }\n                for (int j = nrrx; j < nrry; ++j) {\n                    if (px_extra == -1) continue;\n                    poss_rem[cas].push_back({px_extra, rem_ry[j], z});\n                }\n            }\n        }\n    }\n    size_t sz0 = poss_rem[0].size();\n    size_t sz1 = poss_rem[1].size();\n    size_t minsz = min(sz0, sz1);\n    for (size_t j = 0; j < minsz; ++j) {\n        auto [x0, y0, z0] = poss_rem[0][j];\n        int idx0 = x0 * D * D + y0 * D + z0;\n        bb[0][idx0] = block_id;\n        auto [x1, y1, z1] = poss_rem[1][j];\n        int idx1 = x1 * D * D + y1 * D + z1;\n        bb[1][idx1] = block_id;\n        ++block_id;\n    }\n    if (sz0 > minsz) {\n        for (size_t j = minsz; j < sz0; ++j) {\n            auto [x, y, z] = poss_rem[0][j];\n            int idx = x * D * D + y * D + z;\n            bb[0][idx] = block_id++;\n        }\n    }\n    if (sz1 > minsz) {\n        for (size_t j = minsz; j < sz1; ++j) {\n            auto [x, y, z] = poss_rem[1][j];\n            int idx = x * D * D + y * D + z;\n            bb[1][idx] = block_id++;\n        }\n    }\n    int n = block_id - 1;\n    cout << n << '\\n';\n    for (int cas = 0; cas < 2; ++cas) {\n        for (int j = 0; j < VOL; ++j) {\n            if (j) cout << ' ';\n            cout << bb[cas][j];\n        }\n        cout << '\\n';\n    }\n}","ahc020":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint calc_p(ll d2) {\n    if (d2 == 0) return 0;\n    double sd = sqrt((double)d2);\n    int p = (int)ceil(sd);\n    while ((ll)p * p < d2 && p < 5000) ++p;\n    return min(5000, p);\n}\n\nstruct Edge {\n    int u, v, id;\n    ll w;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N, M, K;\n    cin >> N >> M >> K;\n    vector<ll> xs(N + 1), ys(N + 1);\n    for (int i = 1; i <= N; ++i) {\n        cin >> xs[i] >> ys[i];\n    }\n    vector<Edge> edgs(M);\n    for (int j = 0; j < M; ++j) {\n        int u, v;\n        ll w;\n        cin >> u >> v >> w;\n        edgs[j] = {u, v, j + 1, w};\n    }\n    vector<ll> as(K + 1), bs(K + 1);\n    for (int k = 1; k <= K; ++k) {\n        cin >> as[k] >> bs[k];\n    }\n    // adj: {nei, eid}\n    vector<vector<pair<int, int>>> adj(N + 1);\n    for (int j = 0; j < M; ++j) {\n        int u = edgs[j].u, v = edgs[j].v, eid = edgs[j].id;\n        adj[u].emplace_back(v, eid);\n        adj[v].emplace_back(u, eid);\n    }\n    // distsq\n    const ll INF_LL = 9e18 / 2;\n    vector<vector<ll>> distsq(N + 1, vector<ll>(K + 1));\n    for (int i = 1; i <= N; ++i) {\n        for (int k = 1; k <= K; ++k) {\n            ll dx = xs[i] - as[k];\n            ll dy = ys[i] - bs[k];\n            distsq[i][k] = dx * dx + dy * dy;\n        }\n    }\n    // benefit\n    vector<ll> benefit(N + 1, 0LL);\n    for (int k = 1; k <= K; ++k) {\n        ll min1 = INF_LL, min2 = INF_LL;\n        int id1 = -1;\n        for (int i = 1; i <= N; ++i) {\n            ll d2 = distsq[i][k];\n            if (d2 < min1) {\n                min2 = min1;\n                min1 = d2;\n                id1 = i;\n            } else if (d2 < min2) {\n                min2 = d2;\n            }\n        }\n        int p1 = calc_p(min1);\n        int p2 = calc_p(min2);\n        benefit[id1] += (ll)p2 * p2 - (ll)p1 * p1;\n    }\n    // Floyd-Warshall + next_node for path recon\n    vector<vector<ll>> gdist(N + 1, vector<ll>(N + 1, INF_LL));\n    vector<vector<int>> nextn(N + 1, vector<int>(N + 1, -1));\n    for (int i = 1; i <= N; ++i) gdist[i][i] = 0;\n    for (auto& e : edgs) {\n        gdist[e.u][e.v] = e.w;\n        gdist[e.v][e.u] = e.w;\n        nextn[e.u][e.v] = e.v;\n        nextn[e.v][e.u] = e.u;\n    }\n    for (int k = 1; k <= N; ++k) {\n        for (int i = 1; i <= N; ++i) {\n            for (int j = 1; j <= N; ++j) {\n                if (gdist[i][k] >= INF_LL || gdist[k][j] >= INF_LL) continue;\n                ll cand = gdist[i][k] + gdist[k][j];\n                if (cand < gdist[i][j]) {\n                    gdist[i][j] = cand;\n                    nextn[i][j] = nextn[i][k];\n                }\n            }\n        }\n    }\n    // Select terminals: benefit[t] >= 1.1 * dist[1][t]\n    set<int> terms;\n    terms.insert(1);\n    double factor = 1.1;\n    for (int t = 2; t <= N; ++t) {\n        ll conn = gdist[1][t];\n        if (conn < INF_LL / 2 && benefit[t] >= factor * conn) {\n            terms.insert(t);\n        }\n    }\n    // Term list\n    vector<int> term_list(terms.begin(), terms.end());\n    int T = term_list.size();\n    // MST on terminals using gdist: generate pairs\n    vector<tuple<ll, int, int>> term_pairs;\n    for (int ii = 0; ii < T; ++ii) {\n        for (int jj = ii + 1; jj < T; ++jj) {\n            int t1 = term_list[ii], t2 = term_list[jj];\n            ll dw = gdist[t1][t2];\n            if (dw < INF_LL / 2) {\n                term_pairs.emplace_back(dw, t1, t2);\n            }\n        }\n    }\n    sort(term_pairs.begin(), term_pairs.end());\n    // UF for terms\n    vector<int> tpar(N + 1);\n    iota(tpar.begin(), tpar.end(), 0);\n    auto tfind = [&](auto self, int x) -> int {\n        return tpar[x] == x ? x : tpar[x] = self(self, tpar[x]);\n    };\n    auto tunite = [&](int a, int b) {\n        a = tfind(tfind, a); b = tfind(tfind, b);\n        if (a == b) return false;\n        tpar[a] = b;\n        return true;\n    };\n    // B init 0\n    vector<int> B(M + 1, 0);\n    // Add paths for MST term edges\n    auto add_path = [&](int s, int t) {\n        int u = s;\n        while (u != t) {\n            int v = nextn[u][t];\n            if (v == -1) return;  // error\n            // find eid u-v\n            for (auto [nei, eid] : adj[u]) {\n                if (nei == v) {\n                    B[eid] = 1;\n                    break;\n                }\n            }\n            u = v;\n        }\n    };\n    for (auto [dw, t1, t2] : term_pairs) {\n        if (tunite(t1, t2)) {\n            add_path(t1, t2);\n        }\n    }\n    // Connected comp from 1\n    vector<bool> vis(N + 1, false);\n    queue<int> qcomp;\n    qcomp.push(1); vis[1] = true;\n    vector<int> comp = {1};\n    while (!qcomp.empty()) {\n        int u = qcomp.front(); qcomp.pop();\n        for (auto [v, eid] : adj[u]) {\n            if (B[eid] && !vis[v]) {\n                vis[v] = true;\n                qcomp.push(v);\n                comp.push_back(v);\n            }\n        }\n    }\n    // needs\n    vector<ll> need(N + 1, 0LL);\n    for (int k = 1; k <= K; ++k) {\n        ll md2 = INF_LL;\n        int bi = -1;\n        for (int i : comp) {\n            ll d2 = distsq[i][k];\n            if (d2 < md2) {\n                md2 = d2;\n                bi = i;\n            }\n        }\n        need[bi] = max(need[bi], md2);\n    }\n    // P\n    vector<int> PP(N + 1, 0);\n    for (int i = 1; i <= N; ++i) {\n        PP[i] = calc_p(need[i]);\n    }\n    // Output\n    for (int i = 1; i <= N; ++i) {\n        cout << PP[i];\n        if (i < N) cout << \" \";\n        else cout << \"\\n\";\n    }\n    for (int j = 1; j <= M; ++j) {\n        cout << B[j];\n        if (j < M) cout << \" \";\n        else cout << \"\\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  int N = 30;\n  int total = N * (N + 1) / 2;\n  vector<int> cum(N + 1, 0);\n  for (int i = 1; i <= N; ++i) {\n    cum[i] = cum[i - 1] + i;\n  }\n  vector<pair<int, int>> coord(total);\n  vector<vector<int>> flat_pos(N, vector<int>(N));\n  for (int x = 0; x < N; ++x) {\n    for (int y = 0; y <= x; ++y) {\n      int id = cum[x] + y;\n      coord[id] = {x, y};\n      flat_pos[x][y] = id;\n    }\n  }\n  vector<int> a(total);\n  for (int i = 0; i < total; ++i) {\n    cin >> a[i];\n  }\n  vector<vector<int>> childs(total);\n  for (int x = 0; x < N - 1; ++x) {\n    for (int y = 0; y <= x; ++y) {\n      int p = flat_pos[x][y];\n      int l = flat_pos[x + 1][y];\n      int r = flat_pos[x + 1][y + 1];\n      childs[p] = {l, r};\n    }\n  }\n  vector<int> cur_a = a;\n  vector<vector<int>> ops;\n  auto sim_siftdown = [&](vector<int>& arr, int node) -> int {\n    int cnt = 0;\n    int cur_node = node;\n    while (true) {\n      const auto& ch = childs[cur_node];\n      if (ch.empty()) return cnt;\n      int l = ch[0], r = ch[1];\n      int sm = cur_node;\n      if (arr[l] < arr[sm]) sm = l;\n      if (arr[r] < arr[sm]) sm = r;\n      if (sm == cur_node) return cnt;\n      swap(arr[cur_node], arr[sm]);\n      ++cnt;\n      cur_node = sm;\n    }\n  };\n  auto real_siftdown = [&](int node) -> void {\n    int cur_node = node;\n    while (true) {\n      const auto& ch = childs[cur_node];\n      if (ch.empty()) return;\n      int l = ch[0], r = ch[1];\n      int sm = cur_node;\n      if (cur_a[l] < cur_a[sm]) sm = l;\n      if (cur_a[r] < cur_a[sm]) sm = r;\n      if (sm == cur_node) return;\n      swap(cur_a[cur_node], cur_a[sm]);\n      auto [x1, y1] = coord[cur_node];\n      auto [x2, y2] = coord[sm];\n      ops.push_back({x1, y1, x2, y2});\n      cur_node = sm;\n    }\n  };\n  mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n  const int INF = 1e9;\n  for (int xx = N - 2; xx >= 0; --xx) {\n    vector<int> nodes;\n    for (int y = 0; y <= xx; ++y) {\n      nodes.push_back(flat_pos[xx][y]);\n    }\n    int m = nodes.size();\n    vector<vector<int>> strategies;\n    // Heuristics 1-4: prev\n    strategies.push_back(nodes); // LTR\n    { auto ord = nodes; reverse(ord.begin(), ord.end()); strategies.push_back(ord); } // RTL\n    { auto ord = nodes; sort(ord.begin(), ord.end(), [&](int i, int j){ return cur_a[i] > cur_a[j]; }); strategies.push_back(ord); } // largest parent\n    { auto ord = nodes; sort(ord.begin(), ord.end(), [&](int i, int j){\n        int vi = cur_a[i] - min(cur_a[childs[i][0]], cur_a[childs[i][1]]);\n        int vj = cur_a[j] - min(cur_a[childs[j][0]], cur_a[childs[j][1]]);\n        return vi > vj;\n      }); strategies.push_back(ord); } // largest violation\n    // New 5-8\n    { auto ord = nodes; sort(ord.begin(), ord.end(), [&](int i, int j){ return cur_a[i] < cur_a[j]; }); strategies.push_back(ord); } // smallest parent\n    { auto ord = nodes; sort(ord.begin(), ord.end(), [&](int i, int j){\n        int vi = cur_a[i] - min(cur_a[childs[i][0]], cur_a[childs[i][1]]);\n        int vj = cur_a[j] - min(cur_a[childs[j][0]], cur_a[childs[j][1]]);\n        return vi < vj;\n      }); strategies.push_back(ord); } // smallest violation\n    // Alone sift cost desc\n    {\n      vector<pair<int, int>> alone(m);\n      for (int i = 0; i < m; ++i) {\n        vector<int> temp = cur_a;\n        int cost = sim_siftdown(temp, nodes[i]);\n        alone[i] = {-cost, i}; // desc cost\n      }\n      sort(alone.begin(), alone.end());\n      vector<int> ord(m);\n      for (int i = 0; i < m; ++i) ord[i] = nodes[alone[i].second];\n      strategies.push_back(ord);\n    }\n    // Avg child desc\n    {\n      auto ord = nodes;\n      sort(ord.begin(), ord.end(), [&](int i, int j){\n        int ai = (cur_a[childs[i][0]] + cur_a[childs[i][1]]) / 2;\n        int aj = (cur_a[childs[j][0]] + cur_a[childs[j][1]]) / 2;\n        return ai > aj;\n      });\n      strategies.push_back(ord);\n    }\n    // Adaptive randoms\n    int num_random = 50 + xx * 2;\n    for (int r = 0; r < num_random; ++r) {\n      auto ord = nodes;\n      shuffle(ord.begin(), ord.end(), rng);\n      strategies.push_back(ord);\n    }\n    // Find best\n    int min_swaps = INF;\n    vector<int> best_ord;\n    for (const auto& strat : strategies) {\n      vector<int> temp = cur_a;\n      int sw = 0;\n      for (int node : strat) {\n        sw += sim_siftdown(temp, node);\n      }\n      if (sw < min_swaps) {\n        min_swaps = sw;\n        best_ord = strat;\n      }\n    }\n    // Replay\n    for (int node : best_ord) {\n      real_siftdown(node);\n    }\n  }\n  cout << ops.size() << '\\n';\n  for (auto& op : ops) {\n    cout << op[0] << ' ' << op[1] << ' ' << op[2] << ' ' << op[3] << '\\n';\n  }\n}","toyota2023summer-final":"","ahc024":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n, m;\n  cin >> n >> m;\n  vector<vector<int>> grid(n, vector<int>(n));\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      cin >> grid[i][j];\n    }\n  }\n  vector<int> touches0(m + 1, 0);\n  vector<pair<int, int>> anchor(m + 1, make_pair(-1, -1));\n  vector<int> cursize(m + 1, 0);\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      int c = grid[i][j];\n      cursize[c]++;\n      if ((i == 0 || i == n - 1 || j == 0 || j == n - 1) && anchor[c].first == -1) {\n        anchor[c] = {i, j};\n        touches0[c] = 1;\n      } else if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {\n        touches0[c] = 1;\n      }\n    }\n  }\n  vector<vector<int>> cnt(m + 1, vector<int>(m + 1, 0));\n  // horizontal\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n - 1; ++j) {\n      int a = grid[i][j], b = grid[i][j + 1];\n      if (a != b && a > 0 && b > 0) {\n        int u = min(a, b), v = max(a, b);\n        cnt[u][v]++;\n      }\n    }\n  }\n  // vertical\n  for (int i = 0; i < n - 1; ++i) {\n    for (int j = 0; j < n; ++j) {\n      int a = grid[i][j], b = grid[i + 1][j];\n      if (a != b && a > 0 && b > 0) {\n        int u = min(a, b), v = max(a, b);\n        cnt[u][v]++;\n      }\n    }\n  }\n\n  vector<pair<int, int>> dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n  auto peel = [&](vector<vector<int>> g, const vector<int>& init_size) -> pair<vector<vector<int>>, int> {\n    vector<vector<int>> out = g;\n    vector<int> size_ = init_size;\n    auto cnte = cnt;\n    bool changed = true;\n    while (changed) {\n      changed = false;\n      for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n          if (out[i][j] == 0) continue;\n          int c = out[i][j];\n          if (anchor[c].first == i && anchor[c].second == j) continue;\n          if (size_[c] == 1) continue;\n          int same_n = 0;\n          bool can_zero = (i == 0 || i == n - 1 || j == 0 || j == n - 1);\n          int adj_cnt[101] = {};\n          bool would_hurt_i = false;\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) continue;\n            int nc = out[ni][nj];\n            if (nc == c) {\n              ++same_n;\n            } else if (nc == 0) {\n              can_zero = true;\n            } else {\n              ++adj_cnt[nc];\n              if (touches0[nc] == 0) would_hurt_i = true;\n            }\n          }\n          bool safe_adj = true;\n          for (int nc = 1; nc <= m; ++nc) {\n            if (adj_cnt[nc] > 0) {\n              int u = min(c, nc), v = max(c, nc);\n              if (cnte[u][v] == adj_cnt[nc]) {\n                safe_adj = false;\n                break;\n              }\n            }\n          }\n          if (same_n > 1 || !safe_adj || !can_zero || would_hurt_i) continue;\n          // remove\n          out[i][j] = 0;\n          size_[c]--;\n          // update cnt\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n              int nc = out[ni][nj];\n              if (nc > 0 && nc != c) {\n                int u = min(c, nc), v = max(c, nc);\n                cnte[u][v]--;\n              }\n            }\n          }\n          changed = true;\n        }\n      }\n    }\n    int zeros = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        if (out[i][j] == 0) ++zeros;\n      }\n    }\n    return {out, zeros};\n  };\n\n  auto [out1, z1] = peel(grid, cursize);\n\n  auto peel_rev = [&](vector<vector<int>> g, const vector<int>& init_size) -> pair<vector<vector<int>>, int> {\n    vector<vector<int>> out = g;\n    vector<int> size_ = init_size;\n    auto cnte = cnt;\n    bool changed = true;\n    while (changed) {\n      changed = false;\n      for (int i = n - 1; i >= 0; --i) {\n        for (int j = n - 1; j >= 0; --j) {\n          if (out[i][j] == 0) continue;\n          int c = out[i][j];\n          if (anchor[c].first == i && anchor[c].second == j) continue;\n          if (size_[c] == 1) continue;\n          int same_n = 0;\n          bool can_zero = (i == 0 || i == n - 1 || j == 0 || j == n - 1);\n          int adj_cnt[101] = {};\n          bool would_hurt_i = false;\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni < 0 || ni >= n || nj < 0 || nj >= n) continue;\n            int nc = out[ni][nj];\n            if (nc == c) {\n              ++same_n;\n            } else if (nc == 0) {\n              can_zero = true;\n            } else {\n              ++adj_cnt[nc];\n              if (touches0[nc] == 0) would_hurt_i = true;\n            }\n          }\n          bool safe_adj = true;\n          for (int nc = 1; nc <= m; ++nc) {\n            if (adj_cnt[nc] > 0) {\n              int u = min(c, nc), v = max(c, nc);\n              if (cnte[u][v] == adj_cnt[nc]) {\n                safe_adj = false;\n                break;\n              }\n            }\n          }\n          if (same_n > 1 || !safe_adj || !can_zero || would_hurt_i) continue;\n          // remove\n          out[i][j] = 0;\n          size_[c]--;\n          // update cnt\n          for (auto [di, dj] : dirs) {\n            int ni = i + di, nj = j + dj;\n            if (ni >= 0 && ni < n && nj >= 0 && nj < n) {\n              int nc = out[ni][nj];\n              if (nc > 0 && nc != c) {\n                int u = min(c, nc), v = max(c, nc);\n                cnte[u][v]--;\n              }\n            }\n          }\n          changed = true;\n        }\n      }\n    }\n    int zeros = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        if (out[i][j] == 0) ++zeros;\n      }\n    }\n    return {out, zeros};\n  };\n\n  auto [out2, z2] = peel_rev(grid, cursize);\n\n  // pick the better one\n  vector<vector<int>> final_out = (z1 >= z2 ? out1 : out2);\n\n  // output\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < n; ++j) {\n      cout << final_out[i][j];\n      if (j < n - 1) cout << \" \";\n    }\n    cout << \"\\n\";\n  }\n  return 0;\n}","ahc025":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  unsigned seed = chrono::duration_cast<chrono::microseconds>(\n      chrono::steady_clock::now().time_since_epoch()).count();\n  mt19937 rng(seed);\n  int N, D, Q;\n  cin >> N >> D >> Q;\n  vector<vector<int8_t>> cmp(N, vector<int8_t>(N, -2));\n  vector<int> perm(N);\n  iota(perm.begin(), perm.end(), 0);\n  int q_used = 0;\n  // Main querying loop with shuffled pairings\n  while (q_used < Q) {\n    shuffle(perm.begin(), perm.end(), rng);\n    for (int i = 0; i + 1 < N; i += 2) {\n      if (q_used >= Q) break;\n      int a = perm[i], b = perm[i + 1];\n      if (cmp[a][b] != -2) continue;\n      // Query\n      cout << 1 << ' ' << 1 << ' ' << a << ' ' << b << '\\n';\n      cout.flush();\n      string res;\n      cin >> res;\n      int8_t val;\n      if (res == \"<\") val = -1;\n      else if (res == \">\") val = 1;\n      else val = 0;\n      cmp[a][b] = val;\n      cmp[b][a] = -val;\n      q_used++;\n    }\n  }\n  // Dummy queries to reach exactly Q if needed\n  int dummy_a = 0, dummy_b = 1;\n  while (q_used < Q) {\n    cout << 1 << ' ' << 1 << ' ' << dummy_a << ' ' << dummy_b << '\\n';\n    cout.flush();\n    string res;\n    cin >> res;\n    q_used++;\n  }\n  // Build beat graph: adj[i] = lighter items directly beaten by i (cmp[i][j] > 0)\n  vector<vector<int>> adj(N);\n  for (int i = 0; i < N; i++) {\n    for (int j = 0; j < N; j++) {\n      if (i != j && cmp[i][j] > 0) {\n        adj[i].push_back(j);\n      }\n    }\n  }\n  // Compute reachability sizes\n  vector<int> reach(N);\n  for (int s = 0; s < N; s++) {\n    vector<char> vis(N, 0);\n    queue<int> qq;\n    qq.push(s);\n    vis[s] = 1;\n    int cnt = 1;\n    while (!qq.empty()) {\n      int u = qq.front();\n      qq.pop();\n      for (int v : adj[u]) {\n        if (!vis[v]) {\n          vis[v] = 1;\n          cnt++;\n          qq.push(v);\n        }\n      }\n    }\n    reach[s] = cnt;\n  }\n  // Rank by descending reach size\n  vector<pair<int, int>> ranked;\n  for (int i = 0; i < N; i++) {\n    ranked.emplace_back(-reach[i], i);\n  }\n  sort(ranked.begin(), ranked.end());\n  // Assign groups round-robin from heaviest\n  vector<int> group(N);\n  int gid = 0;\n  for (auto& p : ranked) {\n    group[p.second] = gid;\n    gid = (gid + 1) % D;\n  }\n  // Output assignment\n  for (int i = 0; i < N; i++) {\n    cout << group[i];\n    if (i + 1 < N) cout << ' ';\n    else cout << '\\n';\n  }\n  return 0;\n}","ahc026":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int n, m;\n  cin >> n >> m;\n  int h = n / m;\n  vector<vector<int>> stacks(m);\n  vector<int> location(n + 1, -1);\n  for (int i = 0; i < m; i++) {\n    stacks[i].resize(h);\n    for (int j = 0; j < h; j++) {\n      cin >> stacks[i][j];\n      location[stacks[i][j]] = i;\n    }\n  }\n  vector<pair<int, int>> ops;\n  int next_box = 1;\n  const int INF = 1000000000;\n  const int PENALTY = 0;\n  const int DEPTH = 20;\n  while (next_box <= n) {\n    int s = location[next_box];\n    if (s != -1 && !stacks[s].empty() && stacks[s].back() == next_box) {\n      ops.emplace_back(next_box, 0);\n      stacks[s].pop_back();\n      location[next_box] = -1;\n      next_box++;\n      continue;\n    }\n    auto& stk = stacks[s];\n    auto it = find(stk.begin(), stk.end(), next_box);\n    int p = it - stk.begin();\n    int start_idx = p + 1;\n    vector<int> pile(stk.begin() + start_idx, stk.end());\n    int v_move = pile[0];\n    int pile_top = pile.back();\n    // Unified lookahead ALL dests, pure sim\n    tuple<int, int, int> best_key = {INF, -INF, INF};\n    int best_d = -1;\n    for (int d = 0; d < m; d++) {\n      if (d == s) continue;\n      const auto& dstk = stacks[d];\n      int orig_tt = dstk.empty() ? INF : dstk.back();\n      int orig_sz = dstk.size();\n      bool acc = dstk.empty() || orig_tt > pile_top;\n      // Trial\n      auto trial_stacks = stacks;\n      auto trial_loc = location;\n      auto& t_stk = trial_stacks[s];\n      auto& t_dst = trial_stacks[d];\n      t_stk.resize(start_idx);\n      t_dst.insert(t_dst.end(), pile.begin(), pile.end());\n      for (int bb : pile) trial_loc[bb] = d;\n      t_stk.pop_back();\n      trial_loc[next_box] = -1;\n      // Future costs\n      int tcost = 0;\n      int tnext = next_box + 1;\n      for (int dep = 0; dep < DEPTH; ++dep) {\n        if (tnext > n) break;\n        int ts2 = trial_loc[tnext];\n        if (ts2 == -1 || trial_stacks[ts2].empty()) {\n          ++tnext;\n          continue;\n        }\n        const auto& tstkk = trial_stacks[ts2];\n        if (tstkk.back() == tnext) {\n          ++tnext;\n          continue;\n        }\n        auto tiit = find(tstkk.begin(), tstkk.end(), tnext);\n        int tpos = tiit - tstkk.begin();\n        int tabove = tstkk.size() - tpos - 1;\n        tcost += tabove + 1;\n        ++tnext;\n      }\n      if (!acc) tcost += PENALTY;\n      auto tkey = make_tuple(tcost, -orig_tt, orig_sz);\n      if (tkey < best_key) {\n        best_key = tkey;\n        best_d = d;\n      }\n    }\n    // Commit\n    auto& dstk = stacks[best_d];\n    stk.resize(start_idx);\n    dstk.insert(dstk.end(), pile.begin(), pile.end());\n    for (int b : pile) {\n      location[b] = best_d;\n    }\n    ops.emplace_back(v_move, best_d + 1);\n  }\n  for (auto [v, i] : ops) {\n    cout << v << ' ' << i << '\\n';\n  }\n}","ahc027":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N;\n  cin >> N;\n  vector<string> H(N - 1);\n  for (auto& s : H) cin >> s;\n  vector<string> V(N);\n  for (auto& s : V) cin >> s;\n  vector<vector<int>> D(N, vector<int>(N));\n  long long sumD = 0;\n  for (int i = 0; i < N; i++)\n    for (int j = 0; j < N; j++) {\n      cin >> D[i][j];\n      sumD += D[i][j];\n    }\n  int dr[] = {0, 1, 0, -1};\n  int dc[] = {1, 0, -1, 0};\n  char dirchar[] = {'R', 'D', 'L', 'U'};\n  auto no_wall = [&](int r, int c, int d) -> bool {\n    int nr = r + dr[d], nc = c + dc[d];\n    if (nr < 0 || nr >= N || nc < 0 || nc >= N) return false;\n    if (dr[d] == 0) {\n      int cmin = min(c, nc);\n      return V[r][cmin] == '0';\n    } else {\n      int rmin = min(r, nr);\n      return H[rmin][c] == '0';\n    }\n  };\n  // Precompute Dist and prev from (0,0)\n  vector<vector<int>> Dist(N, vector<int>(N, -1));\n  vector<vector<int>> prevr(N, vector<int>(N, -1)), prevc(N, vector<int>(N, -1));\n  {\n    queue<pair<int, int>> q;\n    q.emplace(0, 0);\n    Dist[0][0] = 0;\n    while (!q.empty()) {\n      auto [r, c] = q.front(); q.pop();\n      for (int d = 0; d < 4; d++) {\n        int nr = r + dr[d], nc = c + dc[d];\n        if (nr >= 0 && nr < N && nc >= 0 && nc < N && Dist[nr][nc] == -1 && no_wall(r, c, d)) {\n          Dist[nr][nc] = Dist[r][c] + 1;\n          prevr[nr][nc] = r;\n          prevc[nr][nc] = c;\n          q.emplace(nr, nc);\n        }\n      }\n    }\n  }\n  // SP reconstruct target from src (0,0)\n  auto sp_to = [&](int ti, int tj) -> string {\n    if (Dist[ti][tj] == -1) return \"\";\n    string sp;\n    int r = ti, c = tj;\n    while (r != 0 || c != 0) {\n      int pr = prevr[r][c], pc = prevc[r][c];\n      char ch;\n      if (r == pr + 1) ch = 'U';\n      else if (r == pr - 1) ch = 'D';\n      else if (c == pc + 1) ch = 'L';\n      else ch = 'R';\n      sp += ch;\n      r = pr; c = pc;\n    }\n    reverse(sp.begin(), sp.end());\n    return sp;\n  };\n  auto rt_to = [&](int ti, int tj) -> string {\n    string forth = sp_to(ti, tj);\n    string back;\n    for (char ch : forth) {\n      if (ch == 'R') back += 'L';\n      else if (ch == 'L') back += 'R';\n      else if (ch == 'U') back += 'D';\n      else back += 'U';\n    }\n    reverse(back.begin(), back.end());\n    return forth + back;\n  };\n  auto compute_score = [&](const string& p) -> double {\n    int L = p.size();\n    if (L == 0 || L % 2 != 0 || L > 99999) return 1e18;\n    vector<vector<int>> lastv(N, vector<int>(N, 0));\n    int r = 0, c = 0, t = 0;\n    array<int, 256> dir2d = {};\n    dir2d['R'] = 0; dir2d['D'] = 1; dir2d['L'] = 2; dir2d['U'] = 3;\n    // Simulate first cycle\n    for (char ch : p) {\n      int d = dir2d[ch];\n      if (!no_wall(r, c, d)) return 1e18;\n      int nr = r + dr[d], nc = c + dc[d];\n      t++;\n      lastv[nr][nc] = t;\n      r = nr; c = nc;\n    }\n    if (r != 0 || c != 0) return 1e18;\n    bool allv = true;\n    for (int i = 0; i < N && allv; i++)\n      for (int j = 0; j < N; j++)\n        if (lastv[i][j] == 0) allv = false;\n    if (!allv) return 1e18;\n    // Compute sum S_L .. S_{2L-1}\n    long long total = 0;\n    for (int i = 0; i < N; i++)\n      for (int j = 0; j < N; j++)\n        total += 1LL * D[i][j] * (t - lastv[i][j]);\n    long long sumS = total;\n    // Second cycle L-1 steps\n    for (int i = 0; i < L - 1; i++) {\n      char ch = p[i];\n      int d = dir2d[ch];\n      int nr = r + dr[d], nc = c + dc[d];\n      long long oldc = 1LL * D[nr][nc] * (t - lastv[nr][nc]);\n      long long delta = sumD - D[nr][nc] - oldc;\n      total += delta;\n      t++;\n      lastv[nr][nc] = t;\n      sumS += total;\n      r = nr; c = nc;\n    }\n    return static_cast<double>(sumS) / L;\n  };\n  // Multi-heuristic DFS gen\n  auto gen_tree = [&](auto&& prio) -> string {\n    vector<vector<bool>> vis(N, vector<bool>(N, false));\n    string path;\n    path.reserve(4 * N * N);\n    auto dfs = [&](auto&& self, int r, int c) -> void {\n      vis[r][c] = true;\n      vector<pair<double, int>> cands;\n      for (int d = 0; d < 4; d++) {\n        int nr = r + dr[d], nc = c + dc[d];\n        if (nr >= 0 && nr < N && nc >= 0 && nc < N && !vis[nr][nc] && no_wall(r, c, d)) {\n          cands.emplace_back(-prio(nr, nc), d);\n        }\n      }\n      sort(cands.begin(), cands.end());\n      for (auto [_, d] : cands) {\n        int nr = r + dr[d], nc = c + dc[d];\n        path += dirchar[d];\n        self(self, nr, nc);\n        path += dirchar[(d + 2) % 4];\n      }\n    };\n    dfs(dfs, 0, 0);\n    return path;\n  };\n  // Priors\n  vector<function<double(int, int)>> prios;\n  vector<double> as = {0.3, 0.4, 0.45, 0.5, 0.55, 0.6, 0.7};\n  for (double a : as)\n    prios.push_back([&](int i, int j) { return pow(D[i][j], a); });\n  prios.push_back([&](int i, int j) { return D[i][j]; });\n  prios.push_back([&](int i, int j) { return sqrt(D[i][j]); });\n  prios.push_back([&](int i, int j) { return sqrt(D[i][j]) / (1 + Dist[i][j]); });\n  prios.push_back([&](int i, int j) { return D[i][j] / (1 + Dist[i][j]); });\n  prios.push_back([&](int i, int j) { return 1. / (1 + Dist[i][j]); });\n  prios.push_back([&](int i, int j) { return -Dist[i][j]; });\n  prios.push_back([&](int i, int j) { return 1e5 / (1. + i * N + j); });  // row-major\n  prios.push_back([&](int i, int j) {\n    int col = (i % 2 ? N - 1 - j : j);\n    return 1e5 / (1. + i * N + col);\n  });  // snake\n  // Find best tree\n  string best = \"\";\n  double best_sc = 1e100;\n  for (auto& pr : prios) {\n    string cand = gen_tree(pr);\n    double sc = compute_score(cand);\n    if (sc < best_sc) {\n      best_sc = sc;\n      best = move(cand);\n    }\n  }\n  // Compute visits on best tree\n  auto visits = [&]() -> vector<vector<int>> {\n    vector<vector<int>> v(N, vector<int>(N, 0));\n    int r = 0, c = 0;\n    array<int, 256> dir2d{};\n    dir2d['R'] = 0; dir2d['D'] = 1; dir2d['L'] = 2; dir2d['U'] = 3;\n    for (char ch : best) {\n      int d = dir2d[ch];\n      r += dr[d]; c += dc[d];\n      v[r][c]++;\n    }\n    return v;\n  }();\n  // Boost candidates: high (D/vis) / dist\n  vector<tuple<double, int, int>> boosts;\n  for (int i = 0; i < N; i++)\n    for (int j = 0; j < N; j++)\n      if (Dist[i][j] > 0 && visits[i][j] > 0)\n        boosts.emplace_back(D[i][j] * 1. / visits[i][j] / Dist[i][j], i, j);\n  sort(boosts.rbegin(), boosts.rend());\n  boosts.resize(min(30, (int)boosts.size()));\n  // Greedy append RTs\n  string curr = best;\n  for (int bi = 0; bi < boosts.size(); bi++) {\n    auto [_, ti, tj] = boosts[bi];\n    string rt = rt_to(ti, tj);\n    if (rt.empty()) continue;\n    int rtlen = rt.size();\n    for (int reps = 1; reps <= 3; reps++) {\n      string trial = curr + string(reps, ' ') + rt;  // temp marker\n      int newL = curr.size() + reps * rtlen;\n      if (newL > 99999) break;\n      string newpath = curr;\n      for (int k = 0; k < reps; k++) newpath += rt;\n      double newsc = compute_score(newpath);\n      if (newsc < best_sc) {\n        best_sc = newsc;\n        curr = move(newpath);\n        // Update visits? But since append after, approx ok for next residuals\n      }\n    }\n  }\n  cout << curr << '\\n';\n}","ahc028":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing pii = pair<int, int>;\nint manh(pii a, pii b) { return abs(a.first - b.first) + abs(a.second - b.second); }\n\nconst int INF = 1000000010;\n\nstruct PartialEmb {\n  int movecost = INF;\n  vector<pii> seq;\n};\n\nstruct Emb {\n  array<pii, 5> seq;\n  int intd;\n};\n\nint compute_T(const vector<pii>& pa, pii inip) {\n  if (pa.empty()) return 0;\n  int res = 0;\n  pii pr = inip;\n  for (auto p : pa) {\n    res += manh(pr, p) + 1;\n    pr = p;\n  }\n  return res;\n}\n\nvector<int> do_2opt(vector<int> ord, pii initp, const vector<Emb>& embs, int M) {\n  int passes = 0;\n  bool improved;\n  do {\n    improved = false;\n    for (int a = 0; a < M; ++a) {\n      for (int b = a + 1; b < M; ++b) {\n        pii prev_end = (a == 0 ? initp : embs[ord[a - 1]].seq[4]);\n        pii sa = embs[ord[a]].seq[0];\n        int old1 = manh(prev_end, sa);\n        int old2 = (b == M - 1 ? 0 : manh(embs[ord[b]].seq[4], embs[ord[b + 1]].seq[0]));\n        pii sb = embs[ord[b]].seq[0];\n        int new1 = manh(prev_end, sb);\n        pii ea = embs[ord[a]].seq[4];\n        int new2 = (b == M - 1 ? 0 : manh(ea, embs[ord[b + 1]].seq[0]));\n        int delta = new1 + new2 - old1 - old2;\n        if (delta < 0) {\n          reverse(ord.begin() + a, ord.begin() + b + 1);\n          improved = true;\n        }\n      }\n    }\n  } while (improved && ++passes < 500);\n  return ord;\n}\n\nint compute_inter(const vector<int>& ord, pii initp, const vector<Emb>& embs) {\n  int M = ord.size();\n  if (M == 0) return 0;\n  int sumd = manh(initp, embs[ord[0]].seq[0]);\n  for (int i = 0; i < M - 1; ++i) {\n    sumd += manh(embs[ord[i]].seq[4], embs[ord[i + 1]].seq[0]);\n  }\n  return sumd;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M;\n  cin >> N >> M;\n  int si, sj;\n  cin >> si >> sj;\n  pii initp = {si, sj};\n  vector<string> grid(N);\n  for (auto& s : grid) cin >> s;\n  vector<vector<pii>> pos(26);\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      int c = grid[i][j] - 'A';\n      pos[c].emplace_back(i, j);\n    }\n  }\n  vector<string> ts(M);\n  for (auto& s : ts) cin >> s;\n\n  // Precompute best partials\n  vector<vector<vector<PartialEmb>>> best_partials(M, vector<vector<PartialEmb>>(5));\n  vector<vector<int>> cand_sz(M, vector<int>(5));\n  for (int k = 0; k < M; ++k) {\n    string t = ts[k];\n    auto& szz = cand_sz[k];\n    for (int l = 0; l < 5; ++l) {\n      int cc = t[l] - 'A';\n      szz[l] = pos[cc].size();\n      best_partials[k][l].assign(szz[l], PartialEmb());\n    }\n    vector<pii> candd[5];\n    for (int l = 0; l < 5; ++l) candd[l] = pos[t[l] - 'A'];\n    int sz[5];\n    for (int l = 0; l < 5; ++l) sz[l] = szz[l];\n    for (int a0 = 0; a0 < sz[0]; ++a0) {\n      pii p0 = candd[0][a0];\n      for (int a1 = 0; a1 < sz[1]; ++a1) {\n        pii p1 = candd[1][a1];\n        int d01 = manh(p0, p1);\n        for (int a2 = 0; a2 < sz[2]; ++a2) {\n          pii p2 = candd[2][a2];\n          int d12 = manh(p1, p2);\n          int cum2 = d01 + d12;\n          for (int a3 = 0; a3 < sz[3]; ++a3) {\n            pii p3 = candd[3][a3];\n            int d23 = manh(p2, p3);\n            int cum3 = cum2 + d23;\n            for (int a4 = 0; a4 < sz[4]; ++a4) {\n              pii p4 = candd[4][a4];\n              int d34 = manh(p3, p4);\n              int cum4 = cum3 + d34;\n              // sl=0\n              {\n                auto& pe = best_partials[k][0][a0];\n                if (cum4 < pe.movecost) {\n                  pe.movecost = cum4;\n                  pe.seq = {p0, p1, p2, p3, p4};\n                }\n              }\n              // sl=1\n              {\n                int mc = cum4 - d01;\n                auto& pe = best_partials[k][1][a1];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p1, p2, p3, p4};\n                }\n              }\n              // sl=2\n              {\n                int mc = cum4 - cum2;\n                auto& pe = best_partials[k][2][a2];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p2, p3, p4};\n                }\n              }\n              // sl=3\n              {\n                int mc = cum4 - cum3;\n                auto& pe = best_partials[k][3][a3];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p3, p4};\n                }\n              }\n              // sl=4\n              {\n                int mc = 0;\n                auto& pe = best_partials[k][4][a4];\n                if (mc < pe.movecost) {\n                  pe.movecost = mc;\n                  pe.seq = {p4};\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  // Extract fixed embs\n  vector<Emb> embs(M);\n  for (int k = 0; k < M; ++k) {\n    int min_intd = INF;\n    int best_a = -1;\n    for (int a = 0; a < cand_sz[k][0]; ++a) {\n      int mc = best_partials[k][0][a].movecost;\n      if (mc < min_intd) {\n        min_intd = mc;\n        best_a = a;\n      }\n    }\n    embs[k].intd = min_intd;\n    embs[k].seq = {best_partials[k][0][best_a].seq[0], best_partials[k][0][best_a].seq[1],\n                   best_partials[k][0][best_a].seq[2], best_partials[k][0][best_a].seq[3],\n                   best_partials[k][0][best_a].seq[4]};\n  }\n\n  // Compute dist_init\n  vector<int> dist_init(M);\n  for (int k = 0; k < M; ++k) {\n    dist_init[k] = manh(initp, embs[k].seq[0]);\n  }\n\n  // NN order\n  vector<int> order_nn(M);\n  vector<bool> usd(M, false);\n  pii curp = initp;\n  for (int st = 0; st < M; ++st) {\n    int bestk = -1;\n    int mindd = INF;\n    for (int k = 0; k < M; ++k) {\n      if (usd[k]) continue;\n      pii stp = embs[k].seq[0];\n      int dd = manh(curp, stp);\n      if (dd < mindd || (dd == mindd && k < bestk)) {\n        mindd = dd;\n        bestk = k;\n      }\n    }\n    order_nn[st] = bestk;\n    usd[bestk] = true;\n    curp = embs[bestk].seq[4];\n  }\n  auto order1 = do_2opt(order_nn, initp, embs, M);\n  vector<pii> path1;\n  for (int idx : order1) {\n    for (auto pp : embs[idx].seq) path1.push_back(pp);\n  }\n\n  // Spatial order\n  vector<int> order_spa(M);\n  iota(order_spa.begin(), order_spa.end(), 0);\n  sort(order_spa.begin(), order_spa.end(), [&](int aa, int bb) {\n    int cia = (embs[aa].seq[0].first + embs[aa].seq[4].first) / 2;\n    int cja = (embs[aa].seq[0].second + embs[aa].seq[4].second) / 2;\n    int cib = (embs[bb].seq[0].first + embs[bb].seq[4].first) / 2;\n    int cjb = (embs[bb].seq[0].second + embs[bb].seq[4].second) / 2;\n    return cia * N + cja < cib * N + cjb;\n  });\n  auto order3 = do_2opt(order_spa, initp, embs, M);\n  vector<pii> path3;\n  for (int idx : order3) {\n    for (auto pp : embs[idx].seq) path3.push_back(pp);\n  }\n\n  // Close to init\n  vector<int> order_close(M);\n  iota(order_close.begin(), order_close.end(), 0);\n  sort(order_close.begin(), order_close.end(), [&](int x, int y) { return dist_init[x] < dist_init[y]; });\n  auto order_close_opt = do_2opt(order_close, initp, embs, M);\n  vector<pii> path_close;\n  for (int idx : order_close_opt) {\n    for (auto pp : embs[idx].seq) path_close.push_back(pp);\n  }\n\n  // SA improved\n  mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n  vector<int> sa_ord = order_nn;  // start from NN\n  int cur_c = compute_inter(sa_ord, initp, embs);\n  int sa_bestc = cur_c;\n  vector<int> sa_bestord = sa_ord;\n  double sa_T = 8000.0;\n  double cooling = 0.9999;\n  int maxit_sa = 80000;\n  uniform_int_distribution<int> uid(0, M - 1);\n  uniform_real_distribution<double> urd(0.0, 1.0);\n  for (int it = 0; it < maxit_sa; ++it) {\n    int ra = uid(rng), rb = uid(rng);\n    if (ra > rb) swap(ra, rb);\n    if (ra == rb) {\n      --it;\n      continue;\n    }\n    vector<int> trial = sa_ord;\n    reverse(trial.begin() + ra, trial.begin() + rb + 1);\n    int trial_c = compute_inter(trial, initp, embs);\n    int delta = trial_c - cur_c;\n    double prob = (delta < 0) ? 1.0 : exp(-double(delta) / sa_T);\n    if (urd(rng) < prob) {\n      sa_ord = move(trial);\n      cur_c = trial_c;\n      if (trial_c < sa_bestc) {\n        sa_bestc = trial_c;\n        sa_bestord = sa_ord;\n      }\n    }\n    sa_T *= cooling;\n    if (sa_T < 5.0) break;\n  }\n  auto order_sa_opt = do_2opt(sa_bestord, initp, embs, M);\n  vector<pii> path_sa;\n  for (int idx : order_sa_opt) {\n    for (auto pp : embs[idx].seq) path_sa.push_back(pp);\n  }\n\n  // Dynamic greedy with overlaps\n  vector<pii> path_dyn;\n  pii curr_pos = initp;\n  string recent_str = \"\";\n  vector<bool> covered_dyn(M, false);\n  int remaining = M;\n  while (remaining > 0 && (int)path_dyn.size() <= 4990) {\n    int best_kk = -1;\n    int best_added_t = INF;\n    int best_oo = -1;\n    int best_aa = -1;\n    int best_overlap = -1;\n    for (int kk = 0; kk < M; ++kk) {\n      if (covered_dyn[kk]) continue;\n      string tk = ts[kk];\n      int temp_best = INF;\n      int temp_o = -1;\n      int temp_a = -1;\n      int temp_max_ol = -1;\n      size_t rlen = recent_str.size();\n      int maxoo = min(4, (int)rlen);\n      for (int oo = 0; oo <= maxoo; ++oo) {\n        bool match = true;\n        for (int j = 0; j < oo; ++j) {\n          if (recent_str[rlen - oo + j] != tk[j]) {\n            match = false;\n            break;\n          }\n        }\n        if (!match) continue;\n        int ll = oo;\n        int rrem = 5 - oo;\n        if (rrem <= 0) continue;\n        int min_conn = INF;\n        int ba_this = -1;\n        int ncand = cand_sz[kk][ll];\n        for (int aid = 0; aid < ncand; ++aid) {\n          const auto& pe = best_partials[kk][ll][aid];\n          if (pe.seq.empty() || pe.movecost >= INF / 2) continue;\n          int cd = manh(curr_pos, pe.seq[0]) + pe.movecost;\n          if (cd < min_conn) {\n            min_conn = cd;\n            ba_this = aid;\n          }\n        }\n        if (min_conn == INF) continue;\n        int addedd = min_conn + rrem;\n        if (addedd < temp_best || (addedd == temp_best && oo > temp_max_ol)) {\n          temp_best = addedd;\n          temp_o = oo;\n          temp_a = ba_this;\n          temp_max_ol = oo;\n        }\n      }\n      if (temp_best < INF / 2) {\n        if (temp_best < best_added_t || (temp_best == best_added_t && temp_o > best_overlap)) {\n          best_added_t = temp_best;\n          best_kk = kk;\n          best_oo = temp_o;\n          best_aa = temp_a;\n          best_overlap = temp_o;\n        }\n      }\n    }\n    if (best_kk == -1) break;\n    int ll = best_oo;\n    const auto& pe = best_partials[best_kk][ll][best_aa];\n    for (auto p : pe.seq) {\n      path_dyn.push_back(p);\n    }\n    string addl = \"\";\n    for (auto p : pe.seq) {\n      addl += grid[p.first][p.second];\n    }\n    recent_str += addl;\n    if (recent_str.size() > 4) {\n      recent_str = recent_str.substr(recent_str.size() - 4);\n    }\n    curr_pos = pe.seq.back();\n    covered_dyn[best_kk] = true;\n    --remaining;\n  }\n  // Append remaining if any\n  if (remaining > 0) {\n    pii cur_rem = curr_pos;\n    vector<bool> usd_rem(M, false);  // reuse covered_dyn false for uncovered\n    for (int st = 0; st < remaining; ++st) {\n      int bestk = -1;\n      int mindd = INF;\n      for (int k = 0; k < M; ++k) {\n        if (covered_dyn[k]) continue;\n        int dd = manh(cur_rem, embs[k].seq[0]);\n        if (dd < mindd || (dd == mindd && k < bestk)) {\n          mindd = dd;\n          bestk = k;\n        }\n      }\n      for (auto p : embs[bestk].seq) path_dyn.push_back(p);\n      covered_dyn[bestk] = true;\n      cur_rem = embs[bestk].seq[4];\n    }\n  }\n\n  // Pick best among all\n  vector<pair<int, const vector<pii>*>> candts = {\n      {compute_T(path1, initp), &path1},\n      {compute_T(path3, initp), &path3},\n      {compute_T(path_close, initp), &path_close},\n      {compute_T(path_sa, initp), &path_sa},\n      {compute_T(path_dyn, initp), &path_dyn}};\n  sort(candts.begin(), candts.end());\n  const vector<pii>& best_path = *candts[0].second;\n  for (auto p : best_path) {\n    cout << p.first << \" \" << p.second << '\\n';\n  }\n}","ahc030":"#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <random>\n#include <chrono>\nusing namespace std;\nusing namespace Eigen;\n\nconst int MAXNN = 400;\nconst int MAXM = 20;\nconst int MAXB = 512;\n\nstruct State {\n    double score;\n    int choice[MAXM];\n};\n\nstruct Placement {\n    int di, dj;\n    double score;\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout << fixed << setprecision(10);\n    int N, M;\n    double eps;\n    cin >> N >> M >> eps;\n    vector<vector<pair<int, int>>> shapes(M);\n    int total_mass = 0;\n    for (int m = 0; m < M; ++m) {\n        int d;\n        cin >> d;\n        shapes[m].resize(d);\n        for (int l = 0; l < d; ++l) {\n            cin >> shapes[m][l].first >> shapes[m][l].second;\n        }\n        total_mass += d;\n    }\n    int NN = N * N;\n    assert(NN <= MAXNN);\n    assert(M <= MAXM);\n    mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n    int QQ = 48;\n    int ksize = max(8, NN / 2);\n    double alpha = 1.0 - 2 * eps;\n    vector<double> ys(QQ);\n    vector<int> ks(QQ);\n    MatrixXd A(QQ, NN);\n    A.setZero();\n    vector<vector<int>> subsets(QQ);\n    for (int q = 0; q < QQ; ++q) {\n        vector<int> all_cells(NN);\n        iota(all_cells.begin(), all_cells.end(), 0);\n        shuffle(all_cells.begin(), all_cells.end(), rng);\n        int actual_k = min(ksize, NN);\n        subsets[q].reserve(actual_k);\n        for (int t = 0; t < actual_k; ++t) {\n            subsets[q].push_back(all_cells[t]);\n        }\n        printf(\"q %d\", (int)subsets[q].size());\n        for (int cc : subsets[q]) {\n            printf(\" %d %d\", cc / N, cc % N);\n        }\n        printf(\"\\n\");\n        fflush(stdout);\n        int y;\n        cin >> y;\n        ys[q] = y;\n        ks[q] = subsets[q].size();\n        for (int cc : subsets[q]) {\n            A(q, cc) = 1.0;\n        }\n    }\n    VectorXd sh(QQ);\n    for (int q = 0; q < QQ; ++q) {\n        double bq = eps * ks[q];\n        sh(q) = max(0.0, (ys[q] - bq) / alpha);\n    }\n    ColPivHouseholderQR<MatrixXd> decomp(A);\n    VectorXd vhat_raw = decomp.solve(sh);\n    vector<vector<double>> dens(N, vector<double>(N));\n    for (int c = 0; c < NN; ++c) {\n        int i = c / N, j = c % N;\n        dens[i][j] = max(0.0, vhat_raw(c));\n    }\n    // Smooth twice 5x5 tent\n    for (int pass = 0; pass < 2; ++pass) {\n        vector<vector<double>> newd(N, vector<double>(N));\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < N; ++j) {\n                double sum = 0.0, wsum = 0.0;\n                for (int di = -2; di <= 2; ++di) {\n                    for (int dj = -2; dj <= 2; ++dj) {\n                        int ni = i + di, nj = j + dj;\n                        if (ni >= 0 && ni < N && nj >= 0 && nj < N) {\n                            double w = 1.0 / (1.0 + abs(di) + abs(dj));\n                            sum += w * dens[ni][nj];\n                            wsum += w;\n                        }\n                    }\n                }\n                newd[i][j] = sum / wsum;\n            }\n        }\n        dens = std::move(newd);\n    }\n    // Top placements\n    int LL = 40;\n    vector<vector<Placement>> top_placements(M);\n    for (int m = 0; m < M; ++m) {\n        const auto& shp = shapes[m];\n        int d = shp.size();\n        int hmax = 0, wmax = 0;\n        for (auto [ii, jj] : shp) {\n            hmax = max(hmax, ii + 1);\n            wmax = max(wmax, jj + 1);\n        }\n        int ndi = N - hmax + 1;\n        int ndj = N - wmax + 1;\n        vector<tuple<double, int, int>> cand;\n        cand.reserve((size_t)ndi * ndj);\n        for (int di = 0; di < ndi; ++di) {\n            for (int dj = 0; dj < ndj; ++dj) {\n                double sc = 0.0;\n                for (auto [ri, rj] : shp) {\n                    sc += dens[di + ri][dj + rj];\n                }\n                double avg_sc = sc / d;\n                cand.emplace_back(-avg_sc, di, dj);\n            }\n        }\n        sort(cand.begin(), cand.end());\n        int tk = min(LL, (int)cand.size());\n        top_placements[m].reserve(tk);\n        for (int l = 0; l < tk; ++l) {\n            auto [nsc, di, dj] = cand[l];\n            top_placements[m].push_back({di, dj, -nsc});\n        }\n    }\n    // Order by size desc\n    vector<int> order(M);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int a, int b) {\n        return shapes[a].size() > shapes[b].size();\n    });\n    // Beam search\n    int BB = 256;\n    double lambda = 0.25;\n    int temp_cover[MAXNN];\n    vector<State> current_beam;\n    current_beam.reserve(BB);\n    State init_st;\n    memset(init_st.choice, -1, sizeof(init_st.choice));\n    init_st.score = 0.0;\n    current_beam.push_back(init_st);\n    for (int s = 0; s < M; ++s) {\n        int fld = order[s];\n        vector<State> next_beam;\n        next_beam.reserve(current_beam.size() * (size_t)LL);\n        for (const auto& st : current_beam) {\n            const auto& tpls = top_placements[fld];\n            for (size_t l = 0; l < tpls.size(); ++l) {\n                State nst = st;\n                nst.choice[fld] = (int)l;\n                memset(temp_cover, 0, (size_t)NN * sizeof(int));\n                for (int ff = 0; ff < M; ++ff) {\n                    int cl = nst.choice[ff];\n                    if (cl < 0) continue;\n                    const auto& pl = top_placements[ff][cl];\n                    const auto& shp = shapes[ff];\n                    for (auto p : shp) {\n                        int x = pl.di + p.first;\n                        int y = pl.dj + p.second;\n                        temp_cover[x * N + y]++;\n                    }\n                }\n                double sc = 0.0;\n                for (int x = 0; x < N; ++x) {\n                    for (int y = 0; y < N; ++y) {\n                        int c = x * N + y;\n                        int cv = temp_cover[c];\n                        double vh = dens[x][y];\n                        sc += vh * cv - lambda * cv * (double)cv;\n                    }\n                }\n                nst.score = sc;\n                next_beam.push_back(std::move(nst));\n            }\n        }\n        sort(next_beam.begin(), next_beam.end(), [](const State& aa, const State& bb) {\n            return aa.score > bb.score;\n        });\n        current_beam.clear();\n        current_beam.reserve(BB);\n        int nb = min(BB, (int)next_beam.size());\n        for (int bi = 0; bi < nb; ++bi) {\n            current_beam.push_back(std::move(next_beam[bi]));\n        }\n    }\n    // Best guess\n    const State& best = current_beam[0];\n    set<pair<int, int>> union_set;\n    for (int ff = 0; ff < M; ++ff) {\n        int cl = best.choice[ff];\n        if (cl < 0) continue;\n        const auto& pl = top_placements[ff][cl];\n        const auto& shp = shapes[ff];\n        for (auto p : shp) {\n            union_set.emplace(pl.di + p.first, pl.dj + p.second);\n        }\n    }\n    vector<pair<int, int>> ans(union_set.begin(), union_set.end());\n    printf(\"a %zu\", ans.size());\n    for (auto [i, j] : ans) {\n        printf(\" %d %d\", i, j);\n    }\n    printf(\"\\n\");\n    fflush(stdout);\n    int ver;\n    cin >> ver;\n    if (ver == 1) {\n        return 0;\n    }\n    // Fallback 1: drill candidate cells\n    double fb_thresh = 0.10;\n    double sumhat = 0.0;\n    for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j) sumhat += dens[i][j];\n    double avg_dens = sumhat / NN;\n    fb_thresh = max(0.10, 0.35 * avg_dens);\n    vector<pair<int, int>> cand;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (dens[i][j] > fb_thresh) {\n                cand.emplace_back(i, j);\n            }\n        }\n    }\n    vector<vector<char>> drilled_grid(N, vector<char>(N, 0));\n    vector<pair<int, int>> true_oil;\n    for (auto [i, j] : cand) {\n        drilled_grid[i][j] = 1;\n        printf(\"q 1 %d %d\\n\", i, j);\n        fflush(stdout);\n        int vv;\n        cin >> vv;\n        if (vv > 0) {\n            true_oil.emplace_back(i, j);\n        }\n    }\n    printf(\"a %zu\", true_oil.size());\n    for (auto [i, j] : true_oil) {\n        printf(\" %d %d\", i, j);\n    }\n    printf(\"\\n\");\n    fflush(stdout);\n    int ver2;\n    cin >> ver2;\n    if (ver2 == 1) {\n        return 0;\n    }\n    // Super fallback: drill remaining\n    vector<pair<int, int>> all_oil = true_oil;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (drilled_grid[i][j]) continue;\n            drilled_grid[i][j] = 1;\n            printf(\"q 1 %d %d\\n\", i, j);\n            fflush(stdout);\n            int vv;\n            cin >> vv;\n            if (vv > 0) {\n                all_oil.emplace_back(i, j);\n            }\n        }\n    }\n    sort(all_oil.begin(), all_oil.end());\n    printf(\"a %zu\", all_oil.size());\n    for (auto [i, j] : all_oil) {\n        printf(\" %d %d\", i, j);\n    }\n    printf(\"\\n\");\n    fflush(stdout);\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  int W, D, N;\n  cin >> W >> D >> N;\n  vector<vector<int>> A(D, vector<int>(N));\n  for (int d = 0; d < D; ++d) {\n    for (int k = 0; k < N; ++k) {\n      cin >> A[d][k];\n    }\n  }\n  vector<int> prev_w(N);\n  for (int d = 0; d < D; ++d) {\n    // Compute ideal widths using greedy PQ\n    vector<int> ideal(N, 1);\n    int totalw = N;\n    priority_queue<tuple<ll, int>> pq;\n    vector<ll> covered(N, 0);\n    for (int k = 0; k < N; ++k) {\n      ll ar = A[d][k];\n      ll gain = min((ll)W, ar);\n      covered[k] += gain;\n      ll remain = ar - covered[k];\n      ll nextg = min((ll)W, remain);\n      if (nextg > 0) {\n        pq.emplace(nextg, k);\n      }\n    }\n    while (totalw < W && !pq.empty()) {\n      auto [gainv, k] = pq.top();\n      pq.pop();\n      ideal[k]++;\n      totalw++;\n      covered[k] += gainv;\n      ll remain = (ll)A[d][k] - covered[k];\n      ll nextg = min((ll)W, remain);\n      if (nextg > 0) {\n        pq.emplace(nextg, k);\n      }\n    }\n    int remainw = W - totalw;\n    if (remainw > 0) {\n      int bestk = 0;\n      for (int k = 1; k < N; ++k) {\n        if (A[d][k] > A[d][bestk]) bestk = k;\n      }\n      ideal[bestk] += remainw;\n    }\n    // Now set w\n    vector<int> w(N);\n    if (d == 0) {\n      w = ideal;\n    } else {\n      // Start from prev_w\n      w = prev_w;\n      // Local search: transfer units to reduce shortfall\n      const int MAX_ITERS = 3000;\n      int iters = 0;\n      bool improved = true;\n      while (improved && iters++ < MAX_ITERS) {\n        improved = false;\n        int best_from = -1;\n        int best_to = -1;\n        ll best_delta = 0;\n        for (int from = 0; from < N; ++from) {\n          if (w[from] <= 1) continue;\n          for (int to = 0; to < N; ++to) {\n            if (to == from) continue;\n            // delta for from --\n            ll old_from_s = max(0LL, (ll)A[d][from] - (ll)w[from] * W);\n            ll new_from_s = max(0LL, (ll)A[d][from] - (ll)(w[from] - 1) * W);\n            ll d_from = new_from_s - old_from_s;\n            // delta for to ++\n            ll old_to_s = max(0LL, (ll)A[d][to] - (ll)w[to] * W);\n            ll new_to_s = max(0LL, (ll)A[d][to] - (ll)(w[to] + 1) * W);\n            ll d_to = new_to_s - old_to_s;\n            ll total_d = d_from + d_to;\n            if (total_d < best_delta) {\n              best_delta = total_d;\n              best_from = from;\n              best_to = to;\n            }\n          }\n        }\n        if (best_delta < 0) {\n          w[best_from]--;\n          w[best_to]++;\n          improved = true;\n        }\n      }\n    }\n    // Now output using w in k-order\n    vector<int> pref(N + 1, 0);\n    for (int k = 0; k < N; ++k) {\n      pref[k + 1] = pref[k] + w[k];\n    }\n    for (int k = 0; k < N; ++k) {\n      cout << 0 << ' ' << pref[k] << ' ' << W << ' ' << pref[k + 1] << '\\n';\n    }\n    // Update prev\n    prev_w = w;\n  }\n}","ahc032":"#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll MOD = 998244353LL;\nconst int TRIALS = 512;\nconst int TOPK = 48;\nconst int SZ = 9;\nconst int POS = 7;\nconst int STAMPSZ = 20;\nconst int OPSMAX = 81;\n\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, K;\n  cin >> N >> M >> K;\n  ll board[SZ][SZ];\n  for (int i = 0; i < SZ; i++)\n    for (int j = 0; j < SZ; j++)\n      cin >> board[i][j];\n  ll stamps[STAMPSZ][3][3];\n  for (int m = 0; m < STAMPSZ; m++)\n    for (int i = 0; i < 3; i++)\n      for (int j = 0; j < 3; j++)\n        cin >> stamps[m][i][j];\n  ll best_score = -1LL<<60;\n  vector<tuple<int,int,int>> best_ops;\n  for (int trial = 0; trial < TRIALS; trial++) {\n    ll cur[SZ][SZ];\n    memcpy(cur, board, sizeof(board));\n    vector<tuple<int,int,int>> ops;\n    for (int step = 0; step < OPSMAX; step++) {\n      vector<tuple<ll,int,int,int>> cands;\n      cands.reserve(1024);\n      for (int m = 0; m < STAMPSZ; m++) {\n        for (int p = 0; p < POS; p++) {\n          for (int q = 0; q < POS; q++) {\n            ll delta = 0;\n            for (int di = 0; di < 3; di++) {\n              for (int dj = 0; dj < 3; dj++) {\n                int x = p + di, y = q + dj;\n                ll s = stamps[m][di][dj];\n                ll r = cur[x][y];\n                ll nr = r + s;\n                if (nr >= MOD) nr -= MOD;\n                delta += nr - r;\n              }\n            }\n            cands.emplace_back(delta, m, p, q);\n          }\n        }\n      }\n      int tk = (trial % 16 == 0) ? 1 : min(TOPK, (int)cands.size());\n      nth_element(cands.begin(), cands.begin() + tk, cands.end(),\n                  greater<tuple<ll,int,int,int>>());\n      int pick = (trial % 16 == 0) ? 0 : (rng() % tk);\n      auto [delta, bm, bp, bq] = cands[pick];\n      for (int di = 0; di < 3; di++) {\n        for (int dj = 0; dj < 3; dj++) {\n          int x = bp + di, y = bq + dj;\n          ll s = stamps[bm][di][dj];\n          ll r = cur[x][y];\n          ll nr = r + s;\n          if (nr >= MOD) nr -= MOD;\n          cur[x][y] = nr;\n        }\n      }\n      ops.emplace_back(bm, bp, bq);\n    }\n    ll score = 0;\n    for (int i = 0; i < SZ; i++)\n      for (int j = 0; j < SZ; j++)\n        score += cur[i][j];\n    if (score > best_score) {\n      best_score = score;\n      best_ops = move(ops);\n    }\n  }\n  cout << best_ops.size() << '\\n';\n  for (auto [m, p, q] : best_ops) {\n    cout << m << ' ' << p << ' ' << q << '\\n';\n  }\n}","ahc033":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\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    vector<pair<double, int>> orders;\n    for (int i = 0; i < N; i++) {\n        double sum_c = 0;\n        for (int j = 0; j < N; j++) {\n            sum_c += A[i][j];\n        }\n        orders.emplace_back(sum_c / N, i);\n    }\n    sort(orders.begin(), orders.end());  // Low avg_c first\n    vector<int> start_time(N, 0);\n    int cur_time = 0;\n    for (auto& p : orders) {\n        int i = p.second;\n        int sum_adr = 0;\n        for (int k = 0; k < N; k++) {\n            int t = A[i][k] / N;\n            sum_adr += abs(t - i);\n        }\n        int crane_len = 10 * N + 2 * sum_adr;\n        start_time[i] = cur_time;\n        cur_time += crane_len;\n    }\n    vector<string> actions(N);\n    for (int i = 0; i < N; i++) {\n        string s(start_time[i], '.');\n        for (int k = 0; k < N; k++) {\n            int c = A[i][k];\n            int t = c / N;\n            int dr = t - i;\n            int adr = abs(dr);\n            char hdir = (dr > 0 ? 'D' : (dr < 0 ? 'U' : '.'));\n            string hold_vert(adr, hdir);\n            string hold_path = string(N - 1, 'R') + hold_vert;\n            char bdir = (dr < 0 ? 'D' : (dr > 0 ? 'U' : '.'));\n            string back_vert(adr, bdir);\n            string back_path = back_vert + string(N - 1, 'L');\n            s += 'P';\n            s += hold_path;\n            s += 'Q';\n            s += back_path;\n        }\n        actions[i] = s;\n    }\n    size_t maxl = 0;\n    for (const auto& ss : actions) {\n        maxl = max(maxl, ss.size());\n    }\n    for (auto& ss : actions) {\n        cout << ss + string(maxl - ss.size(), '.') << '\\n';\n    }\n    return 0;\n}","ahc034":"#include <bits/stdc++.h>\nusing namespace std;\n\nvector<string> get_moves(int r1, int c1, int r2, int c2) {\n    vector<string> res;\n    int dr = r2 - r1;\n    int dc = c2 - c1;\n    string vdir = \"\";\n    if (dr > 0) vdir = \"D\";\n    else if (dr < 0) vdir = \"U\";\n    string hdir = \"\";\n    if (dc > 0) hdir = \"R\";\n    else if (dc < 0) hdir = \"L\";\n    for (int i = 0; i < abs(dr); ++i) {\n        res.push_back(vdir);\n    }\n    for (int i = 0; i < abs(dc); ++i) {\n        res.push_back(hdir);\n    }\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int N;\n    cin >> N;\n    vector<vector<int>> height(N, vector<int>(N));\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            cin >> height[i][j];\n        }\n    }\n    vector<string> ops;\n    int cur_r = 0, cur_c = 0;\n    long long current_load = 0;\n    while (ops.size() < 95000) {\n        // check if done\n        bool is_done = (current_load == 0);\n        if (is_done) {\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (height[i][j] != 0) {\n                        is_done = false;\n                        goto next;\n                    }\n                }\n            }\n        }\n    next:;\n        if (is_done) break;\n\n        double best_score = 1e100;\n        int best_secondary = -1;\n        int best_r = -1, best_c = -1;\n        if (current_load > 0) {\n            // find best sink (closest, tie largest need)\n            for (int i = 0; i < N; ++i) {\n                for (int j = 0; j < N; ++j) {\n                    if (height[i][j] < 0) {\n                        double dist = abs(i - cur_r) + abs(j - cur_c);\n                        int camt = -height[i][j];\n                        double cscore = dist;\n                        if (cscore < best_score || (cscore == best_score && camt > best_secondary)) {\n                            best_score = cscore;\n                            best_secondary = camt;\n                            best_r = i;\n                            best_c = j;\n                        }\n                    }\n                }\n            }\n        } else {\n            // find best source (min est_cost = D*100 + min_ds*(100 + amt), tie largest amt)\n            for (int sr = 0; sr < N; ++sr) {\n                for (int sc = 0; sc < N; ++sc) {\n                    if (height[sr][sc] > 0) {\n                        int camt = height[sr][sc];\n                        double D = abs(sr - cur_r) + abs(sc - cur_c);\n                        double min_ds = 1e9;\n                        int sink_sec = -1;\n                        for (int tr = 0; tr < N; ++tr) {\n                            for (int tc = 0; tc < N; ++tc) {\n                                if (height[tr][tc] < 0) {\n                                    double ds = abs(tr - sr) + abs(tc - sc);\n                                    int ssamt = -height[tr][tc];\n                                    if (ds < min_ds || (ds == min_ds && ssamt > sink_sec)) {\n                                        min_ds = ds;\n                                        sink_sec = ssamt;\n                                    }\n                                }\n                            }\n                        }\n                        double cscore = D * 100.0 + min_ds * (100.0 + (double)camt);\n                        if (cscore < best_score || (cscore == best_score && camt > best_secondary)) {\n                            best_score = cscore;\n                            best_secondary = camt;\n                            best_r = sr;\n                            best_c = sc;\n                        }\n                    }\n                }\n            }\n        }\n        if (best_r == -1) break;\n\n        // move\n        auto path = get_moves(cur_r, cur_c, best_r, best_c);\n        for (auto& p : path) {\n            ops.push_back(p);\n        }\n        cur_r = best_r;\n        cur_c = best_c;\n\n        // act\n        if (current_load > 0) {\n            // unload\n            long long need = -(long long)height[best_r][best_c];\n            long long d = min(current_load, need);\n            ops.push_back(\"-\" + to_string(d));\n            height[best_r][best_c] += (int)d;\n            current_load -= d;\n        } else {\n            // load\n            long long d = height[best_r][best_c];\n            ops.push_back(\"+\" + to_string(d));\n            height[best_r][best_c] -= (int)d;\n            current_load += d;\n        }\n    }\n    for (auto& s : ops) {\n        cout << s << '\\n';\n    }\n}","ahc035":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int N, M, T;\n    cin >> N >> M >> T;\n    const int P = N * N; // 36\n    const int S = 2 * N * (N - 1); // 60\n    vector<vector<int>> cur(S, vector<int>(M));\n    for (int k = 0; k < S; k++) {\n        for (int j = 0; j < M; j++) {\n            cin >> cur[k][j];\n        }\n    }\n\n    auto pid = [N](int i, int j) { return i * N + j; };\n\n    // adjacency list\n    vector<vector<int>> adj(P);\n    for (int i = 0; i < N; i++) {\n        for (int j = 0; j < N - 1; j++) {\n            int u = pid(i, j), v = pid(i, j + 1);\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n    }\n    for (int i = 0; i < N - 1; i++) {\n        for (int j = 0; j < N; j++) {\n            int u = pid(i, j), v = pid(i + 1, j);\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n    }\n\n    // edges\n    vector<pair<int, int>> edges;\n    for (int u = 0; u < P; u++) {\n        for (int v : adj[u]) {\n            if (v > u) edges.emplace_back(u, v);\n        }\n    }\n\n    // degrees & pos_order (high deg first)\n    vector<int> degree(P);\n    for (int i = 0; i < P; i++) degree[i] = adj[i].size();\n    vector<int> pos_order(P);\n    iota(pos_order.begin(), pos_order.end(), 0);\n    sort(pos_order.begin(), pos_order.end(), [&](int pa, int pb) {\n        return degree[pa] > degree[pb] || (degree[pa] == degree[pb] && pa < pb);\n    });\n\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n    uniform_int_distribution<int> uni_pos(0, P - 1);\n    uniform_real_distribution<double> uni_prob(0.0, 1.0);\n\n    for (int t = 0; t < T; t++) {\n        // values\n        vector<long long> val(S, 0);\n        for (int k = 0; k < S; k++) {\n            for (int j = 0; j < M; j++) val[k] += cur[k][j];\n        }\n\n        // global sort by val desc\n        vector<int> idx(S);\n        iota(idx.begin(), idx.end(), 0);\n        sort(idx.begin(), idx.end(), [&](int a, int b) {\n            return val[a] > val[b] || (val[a] == val[b] && a < b);\n        });\n\n        // elites: dim maxes\n        set<int> elites_set;\n        for (int l = 0; l < M; l++) {\n            int best = -1, mx = -1;\n            for (int k = 0; k < S; k++) {\n                if (cur[k][l] > mx) {\n                    mx = cur[k][l];\n                    best = k;\n                }\n            }\n            if (best != -1) elites_set.insert(best);\n        }\n        int num_elite = elites_set.size();\n        if (t >= 6) num_elite = min(8, num_elite); // late: fewer elites\n\n        // complementary score for non-elites\n        vector<double> comp_score(S, 0.0);\n        if (!elites_set.empty()) {\n            double inv_ne = 1.0 / num_elite;\n            for (int k = 0; k < S; k++) {\n                if (elites_set.count(k)) continue;\n                long long sum_sup = 0;\n                for (int e : elites_set) {\n                    for (int m = 0; m < M; m++) {\n                        sum_sup += max((long long)cur[k][m], (long long)cur[e][m]);\n                    }\n                }\n                comp_score[k] = sum_sup * inv_ne;\n            }\n        }\n\n        // candidates: top comp_score non-elites (or val if no elites)\n        vector<int> candidates;\n        vector<int> non_elite_idx;\n        for (int ii = 0; ii < S; ii++) {\n            int k = idx[ii];\n            if (elites_set.count(k) == 0) non_elite_idx.push_back(k);\n        }\n        sort(non_elite_idx.begin(), non_elite_idx.end(), [&](int a, int b) {\n            if (comp_score[a] != comp_score[b]) return comp_score[a] > comp_score[b];\n            return val[a] > val[b] || (val[a] == val[b] && a < b);\n        });\n        int need_more = P - num_elite;\n        for (int i = 0; i < need_more && i < (int)non_elite_idx.size(); i++) {\n            candidates.push_back(non_elite_idx[i]);\n        }\n\n        // top36\n        vector<int> top36(elites_set.begin(), elites_set.end());\n        top36.insert(top36.end(), candidates.begin(), candidates.end());\n\n        // locals\n        vector<vector<int>> loc(P, vector<int>(M));\n        vector<long long> local_val(P);\n        for (int li = 0; li < P; li++) {\n            int gi = top36[li];\n            local_val[li] = val[gi];\n            for (int m = 0; m < M; m++) loc[li][m] = cur[gi][m];\n        }\n\n        // sort locals by val desc\n        vector<int> local_order(P);\n        iota(local_order.begin(), local_order.end(), 0);\n        sort(local_order.begin(), local_order.end(), [&](int a, int b) {\n            return local_val[a] > local_val[b] || (local_val[a] == local_val[b] && a < b);\n        });\n\n        // supersum lambda\n        auto supersum = [&](int lid1, int lid2) -> long long {\n            long long s = 0;\n            for (int m = 0; m < M; m++) {\n                s += max((long long)loc[lid1][m], (long long)loc[lid2][m]);\n            }\n            return s;\n        };\n\n        // Multi-start SA\n        vector<int> best_assignment(P);\n        long long best_score = LLONG_MIN / 2;\n        const int NUM_STARTS = 2;\n        const int MAX_ITER = 400000;\n        const double TEMP_START = 15000.0;\n        const double COOL_RATE = 0.9997;\n\n        for (int st = 0; st < NUM_STARTS; st++) {\n            // init assignment: top locals to high-deg pos\n            vector<int> assignment(P);\n            for (int pp = 0; pp < P; pp++) {\n                assignment[pos_order[pp]] = local_order[pp];\n            }\n\n            // init score\n            long long score = 0;\n            for (auto [u, v] : edges) {\n                score += supersum(assignment[u], assignment[v]);\n            }\n\n            // SA\n            double cur_temp = TEMP_START;\n            for (int iter = 0; iter < MAX_ITER; iter++) {\n                int a = uni_pos(rng), b = uni_pos(rng);\n                if (a == b) continue;\n\n                int sidA = assignment[a], sidB = assignment[b];\n                long long delta = 0;\n\n                for (int n : adj[a]) {\n                    if (n == b) continue;\n                    delta += supersum(assignment[n], sidB) - supersum(assignment[n], sidA);\n                }\n                for (int n : adj[b]) {\n                    if (n == a) continue;\n                    delta += supersum(assignment[n], sidA) - supersum(assignment[n], sidB);\n                }\n\n                bool accept = delta >= 0;\n                if (!accept) {\n                    double p = exp((double)delta / cur_temp);\n                    accept = uni_prob(rng) < p;\n                }\n                if (accept) {\n                    swap(assignment[a], assignment[b]);\n                    score += delta;\n                }\n\n                cur_temp *= COOL_RATE;\n                if (cur_temp < 1.0) break;\n            }\n\n            if (score > best_score) {\n                best_score = score;\n                best_assignment = assignment;\n            }\n        }\n\n        // build grid\n        vector<vector<int>> grid(N, vector<int>(N));\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                int pos = pid(i, j);\n                int lid = best_assignment[pos];\n                grid[i][j] = top36[lid];\n            }\n        }\n\n        // output\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                cout << grid[i][j];\n                if (j + 1 < N) cout << ' ';\n                else cout << '\\n';\n            }\n        }\n        cout.flush();\n\n        // read new\n        for (int k = 0; k < S; k++) {\n            for (int m = 0; m < M; m++) {\n                cin >> cur[k][m];\n            }\n        }\n    }\n    return 0;\n}","ahc038":"#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, V;\n  cin >> N >> M >> V;\n  vector<string> S(N), T(N);\n  for (auto& str : S) cin >> str;\n  for (auto& str : T) cin >> str;\n  vector<vector<int>> board(N, vector<int>(N, 0));\n  vector<vector<int>> targ(N, vector<int>(N, 0));\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      board[i][j] = S[i][j] - '0';\n      targ[i][j] = T[i][j] - '0';\n    }\n  }\n\n  // Design star with two fingers\n  int Vp = 3;\n  int L1 = max(1, (N + 2) / 3);\n  int L2 = max(1, 2 * (N + 2) / 3);\n  cout << Vp << '\\n';\n  cout << 0 << \" \" << L1 << '\\n';\n  cout << 0 << \" \" << L2 << '\\n';\n\n  // Initial position\n  double sum_ex_x = 0, sum_ex_y = 0, sum_ho_x = 0, sum_ho_y = 0;\n  int ex_cnt0 = 0, ho_cnt0 = 0;\n  for (int i = 0; i < N; ++i) {\n    for (int j = 0; j < N; ++j) {\n      if (board[i][j] && !targ[i][j]) {\n        sum_ex_x += i;\n        sum_ex_y += j;\n        ++ex_cnt0;\n      } else if (!board[i][j] && targ[i][j]) {\n        sum_ho_x += i;\n        sum_ho_y += j;\n        ++ho_cnt0;\n      }\n    }\n  }\n  double ex_cx0 = ex_cnt0 ? sum_ex_x / ex_cnt0 : N / 2.0;\n  double ex_cy0 = ex_cnt0 ? sum_ex_y / ex_cnt0 : N / 2.0;\n  double ho_cx0 = ho_cnt0 ? sum_ho_x / ho_cnt0 : N / 2.0;\n  double ho_cy0 = ho_cnt0 ? sum_ho_y / ho_cnt0 : N / 2.0;\n  int rx = max(0, min(N - 1, (int)round((ex_cx0 + ho_cx0) / 2)));\n  int ry = max(0, min(N - 1, (int)round((ex_cy0 + ho_cy0) / 2)));\n  cout << rx << \" \" << ry << '\\n';\n\n  // State\n  int cur_rx = rx, cur_ry = ry;\n  array<int, 2> cur_dir{0, 0};\n  array<bool, 2> holding{false, false};\n\n  // Directions: 0:R, 1:D, 2:L, 3:U\n  int dx[4] = {0, 1, 0, -1};\n  int dy[4] = {1, 0, -1, 0};\n\n  auto rebuild = [&]() -> tuple<int, int, double, double, double, double> {\n    double sum_ex_x = 0, sum_ex_y = 0, sum_ho_x = 0, sum_ho_y = 0;\n    int ex_cnt = 0, ho_cnt = 0;\n    for (int i = 0; i < N; ++i) {\n      for (int j = 0; j < N; ++j) {\n        if (board[i][j] && !targ[i][j]) {\n          sum_ex_x += i;\n          sum_ex_y += j;\n          ++ex_cnt;\n        }\n        if (!board[i][j] && targ[i][j]) {\n          sum_ho_x += i;\n          sum_ho_y += j;\n          ++ho_cnt;\n        }\n      }\n    }\n    double ex_cx = ex_cnt ? sum_ex_x / ex_cnt : N / 2.0;\n    double ex_cy = ex_cnt ? sum_ex_y / ex_cnt : N / 2.0;\n    double ho_cx = ho_cnt ? sum_ho_x / ho_cnt : N / 2.0;\n    double ho_cy = ho_cnt ? sum_ho_y / ho_cnt : N / 2.0;\n    return {ex_cnt, ho_cnt, ex_cx, ex_cy, ho_cx, ho_cy};\n  };\n\n  const int MAX_TURNS = 100000;\n  int turn = 0;\n  while (turn < MAX_TURNS) {\n    auto [ex_cnt, ho_cnt, ex_cx, ex_cy, ho_cx, ho_cy] = rebuild();\n    if (ex_cnt == 0 && ho_cnt == 0 && !holding[0] && !holding[1]) {\n      break;\n    }\n\n    // Find best action\n    string best_op(6, '.');\n    int best_sc = INT_MIN / 2;\n\n    char mv_opts[5] = {'.', 'U', 'D', 'L', 'R'};\n    int mv_drx[5] = {0, -1, 1, 0, 0};\n    int mv_dry[5] = {0, 0, 0, -1, 1};\n    char rot_opts[3] = {'.', 'R', 'L'};\n    int rot_delta[3] = {0, 1, 3};\n    char pk_opts[2] = {'.', 'P'};\n\n    for (int mvi = 0; mvi < 5; ++mvi) {\n      char mvc = mv_opts[mvi];\n      int nrx = cur_rx + mv_drx[mvi];\n      int nry = cur_ry + mv_dry[mvi];\n      if (nrx < 0 || nrx >= N || nry < 0 || nry >= N) continue;\n\n      for (int r1i = 0; r1i < 3; ++r1i) {\n        int ndir1 = (cur_dir[0] + rot_delta[r1i]) % 4;\n        char r1c = rot_opts[r1i];\n        for (int r2i = 0; r2i < 3; ++r2i) {\n          int ndir2 = (cur_dir[1] + rot_delta[r2i]) % 4;\n          char r2c = rot_opts[r2i];\n          for (int p1i = 0; p1i < 2; ++p1i) {\n            bool do_p1 = p1i == 1;\n            for (int p2i = 0; p2i < 2; ++p2i) {\n              bool do_p2 = p2i == 1;\n\n              // Positions\n              int nf1x = nrx + L1 * dx[ndir1];\n              int nf1y = nry + L1 * dy[ndir1];\n              int nf2x = nrx + L2 * dx[ndir2];\n              int nf2y = nry + L2 * dy[ndir2];\n\n              bool in1 = 0 <= nf1x && nf1x < N && 0 <= nf1y && nf1y < N;\n              bool in2 = 0 <= nf2x && nf2x < N && 0 <= nf2y && nf2y < N;\n              bool same_pos = in1 && in2 && nf1x == nf2x && nf1y == nf2y;\n              int cell1 = in1 ? board[nf1x][nf1y] : -1;\n              int cell2 = in2 ? board[nf2x][nf2y] : -1;\n\n              array<bool, 2> temp_h = holding;\n              int t_success = 0;\n              bool success1 = false;\n              bool success2 = false;\n\n              // Finger 1 (vertex 1)\n              if (do_p1 && in1) {\n                bool h = temp_h[0];\n                if (h && cell1 == 0) {\n                  temp_h[0] = false;\n                  t_success += 50;\n                  if (targ[nf1x][nf1y]) t_success += 200;\n                  cell1 = 1;\n                  success1 = true;\n                } else if (!h && cell1 == 1) {\n                  temp_h[0] = true;\n                  t_success += 50;\n                  if (!targ[nf1x][nf1y]) t_success += 200;\n                  cell1 = 0;\n                  success1 = true;\n                }\n              }\n\n              // Finger 2 (vertex 2)\n              if (do_p2 && in2) {\n                int curr_cell2 = same_pos ? cell1 : cell2;\n                bool h = temp_h[1];\n                if (h && curr_cell2 == 0) {\n                  temp_h[1] = false;\n                  t_success += 50;\n                  if (targ[nf2x][nf2y]) t_success += 200;\n                  success2 = true;\n                } else if (!h && curr_cell2 == 1) {\n                  temp_h[1] = true;\n                  t_success += 50;\n                  if (!targ[nf2x][nf2y]) t_success += 200;\n                  success2 = true;\n                }\n              }\n\n              // Penalize P without success\n              int penalty = 0;\n              if (do_p1 && !success1) penalty -= 1000000;\n              if (do_p2 && !success2) penalty -= 1000000;\n\n              // Future score\n              int fut_score = 0;\n              // Finger 1\n              {\n                int px = nf1x, py = nf1y;\n                bool ib = 0 <= px && px < N && 0 <= py && py < N;\n                bool hld = temp_h[0];\n                int md = 0;\n                double tgt_cx = hld ? ho_cx : ex_cx;\n                double tgt_cy = hld ? ho_cy : ex_cy;\n                if (ex_cnt + ho_cnt > 0) {\n                  int tgx = max(0, min(N - 1, (int)round(tgt_cx)));\n                  int tgy = max(0, min(N - 1, (int)round(tgt_cy)));\n                  md = abs(px - tgx) + abs(py - tgy);\n                }\n                if (!ib) md += 200;\n                fut_score -= md * 10;\n              }\n              // Finger 2\n              {\n                int px = nf2x, py = nf2y;\n                bool ib = 0 <= px && px < N && 0 <= py && py < N;\n                bool hld = temp_h[1];\n                int md = 0;\n                double tgt_cx = hld ? ho_cx : ex_cx;\n                double tgt_cy = hld ? ho_cy : ex_cy;\n                if (ex_cnt + ho_cnt > 0) {\n                  int tgx = max(0, min(N - 1, (int)round(tgt_cx)));\n                  int tgy = max(0, min(N - 1, (int)round(tgt_cy)));\n                  md = abs(px - tgx) + abs(py - tgy);\n                }\n                if (!ib) md += 200;\n                fut_score -= md * 10;\n              }\n\n              // Costs\n              int acost = (mvc != '.') + (r1c != '.') + (r2c != '.') + (do_p1 ? 1 : 0) + (do_p2 ? 1 : 0);\n              int sc = t_success + fut_score + penalty - acost * 5;\n\n              if (sc > best_sc) {\n                best_sc = sc;\n                best_op[0] = mvc;\n                best_op[1] = r1c;\n                best_op[2] = r2c;\n                best_op[3] = '.'; // root\n                best_op[4] = pk_opts[p1i];\n                best_op[5] = pk_opts[p2i];\n              }\n            }\n          }\n        }\n      }\n    }\n\n    // Output\n    cout << best_op << '\\n';\n\n    // Apply move\n    char mvc = best_op[0];\n    int ardx = 0, ardy = 0;\n    if (mvc == 'U') ardx = -1;\n    else if (mvc == 'D') ardx = 1;\n    else if (mvc == 'L') ardy = -1;\n    else if (mvc == 'R') ardy = 1;\n    cur_rx += ardx;\n    cur_ry += ardy;\n\n    // Apply rotations\n    char r1c = best_op[1];\n    int delta1 = 0;\n    if (r1c == 'R') delta1 = 1;\n    else if (r1c == 'L') delta1 = 3;\n    cur_dir[0] = (cur_dir[0] + delta1) % 4;\n\n    char r2c = best_op[2];\n    int delta2 = 0;\n    if (r2c == 'R') delta2 = 1;\n    else if (r2c == 'L') delta2 = 3;\n    cur_dir[1] = (cur_dir[1] + delta2) % 4;\n\n    // Finger positions\n    int af1x = cur_rx + L1 * dx[cur_dir[0]];\n    int af1y = cur_ry + L1 * dy[cur_dir[0]];\n    int af2x = cur_rx + L2 * dx[cur_dir[1]];\n    int af2y = cur_ry + L2 * dy[cur_dir[1]];\n\n    // Apply P for finger1 (v1)\n    if (best_op[4] == 'P') {\n      bool inb = 0 <= af1x && af1x < N && 0 <= af1y && af1y < N;\n      if (inb) {\n        bool h = holding[0];\n        int cell = board[af1x][af1y];\n        if (h && cell == 0) {\n          board[af1x][af1y] = 1;\n          holding[0] = false;\n        } else if (!h && cell == 1) {\n          board[af1x][af1y] = 0;\n          holding[0] = true;\n        }\n      }\n    }\n\n    // Apply P for finger2 (v2)\n    if (best_op[5] == 'P') {\n      bool inb = 0 <= af2x && af2x < N && 0 <= af2y && af2y < N;\n      if (inb) {\n        bool h = holding[1];\n        int cell = board[af2x][af2y];\n        if (h && cell == 0) {\n          board[af2x][af2y] = 1;\n          holding[1] = false;\n        } else if (!h && cell == 1) {\n          board[af2x][af2y] = 0;\n          holding[1] = true;\n        }\n      }\n    }\n\n    ++turn;\n  }\n  return 0;\n}","ahc039":"#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Point {\n    int x, y;\n    bool operator<(const Point& p) const { return x < p.x || (x == p.x && y < p.y); }\n};\n\nauto comp_y = [](const Point& a, const Point& b) { return a.y < b.y || (a.y == b.y && a.x < b.x); };\n\nvector<Point> make_small_rect(const Point& p) {\n    int lx = p.x, rx = p.x, ly = p.y, ry = p.y;\n    if (p.x < 100000) rx = p.x + 1; else if (p.x > 0) lx = p.x - 1;\n    if (p.y < 100000) ry = p.y + 1; else if (p.y > 0) ly = p.y - 1;\n    return {{lx, ly}, {rx, ly}, {rx, ry}, {lx, ry}};\n}\n\npair<int, pair<int,int>> get_max_sub(const vector<pair<int,int>>& events) {\n    if (events.empty()) return {INT_MIN/2, {0,0}};\n    int max_prof = INT_MIN/2, best_s = -1, best_e = -1;\n    int curr = 0, st = 0;\n    for (int e = 0; e < (int)events.size(); ++e) {\n        curr += events[e].second;\n        if (curr > max_prof) { max_prof = curr; best_s = st; best_e = e; }\n        if (curr < 0) { curr = 0; st = e + 1; }\n    }\n    if (max_prof <= 0 || best_s < 0) return {0, {0,0}};\n    int cl = events[best_s].first, cr = events[best_e].first;\n    if (cl >= cr) return {0, {0,0}};\n    return {max_prof, {cl, cr}};\n}\n\nint main() {\n    ios::sync_with_stdio(false); cin.tie(nullptr);\n\n    int N; cin >> N;\n    vector<Point> mack(N), sard(N);\n    for (auto& p : mack) cin >> p.x >> p.y;\n    for (auto& p : sard) cin >> p.x >> p.y;\n\n    int best_profit = 1;\n    int best_xl = INT_MAX, best_xr = INT_MIN, best_yl = INT_MAX, best_yr = INT_MIN;\n    {\n        auto rect = make_small_rect(mack[0]);\n        for (const auto& pt : rect) {\n            best_xl = min(best_xl, pt.x); best_xr = max(best_xr, pt.x);\n            best_yl = min(best_yl, pt.y); best_yr = max(best_yr, pt.y);\n        }\n    }\n\n    auto update = [&](int xl, int xr, int yl, int yr, int prof) {\n        if (prof > best_profit && xl < xr && yl < yr) {\n            best_profit = prof; best_xl = xl; best_xr = xr; best_yl = yl; best_yr = yr;\n        }\n    };\n\n    // Global BB\n    int gxmin = INT_MAX, gxmax = INT_MIN, gymin = INT_MAX, gymax = INT_MIN;\n    for (auto& p : mack) { gxmin = min(gxmin, p.x); gxmax = max(gxmax, p.x); gymin = min(gymin, p.y); gymax = max(gymax, p.y); }\n    int sb = 0; for (auto& s : sard) if (gxmin <= s.x && s.x <= gxmax && gymin <= s.y && s.y <= gymax) ++sb;\n    update(gxmin, gxmax, gymin, gymax, N - sb);\n\n    // Sorted arrays\n    vector<Point> mxs = mack, sxs = sard, mys = mack, sys = sard;\n    sort(mxs.begin(), mxs.end()); sort(sxs.begin(), sxs.end());\n    sort(mys.begin(), mys.end(), comp_y); sort(sys.begin(), sys.end(), comp_y);\n\n    // Strip Kadane X->Y\n    vector<int> ths = {1,3,10,25,50,100,200,300,500,800,1200,2000,3000,5000,8000,12000,20000,50000,100000};\n    for (int th : ths) {\n        int i = 0; while (i < N) {\n            int j = i; while (j + 1 < N && mxs[j + 1].x - mxs[j].x <= th) ++j;\n            int xl = mxs[i].x, xr = mxs[j].x; if (xl >= xr) { i = j + 1; continue; }\n            vector<pair<int,int>> events; events.reserve(1024);\n            for (int k = i; k <= j; ++k) events.emplace_back(mxs[k].y, 1);\n            auto lit = lower_bound(sxs.begin(), sxs.end(), Point{xl, INT_MIN});\n            auto rit = upper_bound(lit, sxs.end(), Point{xr, INT_MAX});\n            for (auto it = lit; it != rit; ++it) events.emplace_back(it->y, -1);\n            sort(events.begin(), events.end());\n            auto [prof, prng] = get_max_sub(events);\n            if (prof > 0) { auto [yl, yr] = prng; update(xl, xr, yl, yr, prof); }\n            i = j + 1;\n        }\n    }\n\n    // Strip Kadane Y->X\n    for (int th : ths) {\n        int i = 0; while (i < N) {\n            int j = i; while (j + 1 < N && mys[j + 1].y - mys[j].y <= th) ++j;\n            int yl = mys[i].y, yr = mys[j].y; if (yl >= yr) { i = j + 1; continue; }\n            vector<pair<int,int>> events; events.reserve(1024);\n            for (int k = i; k <= j; ++k) events.emplace_back(mys[k].x, 1);\n            Point plow = {INT_MIN, yl}; auto lit = lower_bound(sys.begin(), sys.end(), plow, comp_y);\n            Point pup = {INT_MAX, yr}; auto rit = upper_bound(lit, sys.end(), pup, comp_y);\n            for (auto it = lit; it != rit; ++it) events.emplace_back(it->x, -1);\n            sort(events.begin(), events.end());\n            auto [prof, prng] = get_max_sub(events);\n            if (prof > 0) { auto [xl, xr] = prng; update(xl, xr, yl, yr, prof); }\n            i = j + 1;\n        }\n    }\n\n    // Global Kadane full-X Yopt & full-Y Xopt\n    {\n        int xl = mxs[0].x, xr = mxs.back().x; if (xl < xr) {\n            vector<pair<int,int>> events; events.reserve(2 * N);\n            for (auto& p : mack) events.emplace_back(p.y, 1);\n            auto lit = lower_bound(sxs.begin(), sxs.end(), Point{xl, INT_MIN});\n            auto rit = upper_bound(lit, sxs.end(), Point{xr, INT_MAX});\n            for (auto it = lit; it != rit; ++it) events.emplace_back(it->y, -1);\n            sort(events.begin(), events.end());\n            auto [prof, prng] = get_max_sub(events); if (prof > 0) { auto [yl, yr] = prng; update(xl, xr, yl, yr, prof); }\n        }\n    }\n    {\n        int yl = mys[0].y, yr = mys.back().y; if (yl < yr) {\n            vector<pair<int,int>> events; events.reserve(2 * N);\n            for (auto& p : mack) events.emplace_back(p.x, 1);\n            Point plow = {INT_MIN, yl}; auto lit = lower_bound(sys.begin(), sys.end(), plow, comp_y);\n            Point pup = {INT_MAX, yr}; auto rit = upper_bound(lit, sys.end(), pup, comp_y);\n            for (auto it = lit; it != rit; ++it) events.emplace_back(it->x, -1);\n            sort(events.begin(), events.end());\n            auto [prof, prng] = get_max_sub(events); if (prof > 0) { auto [xl, xr] = prng; update(xl, xr, yl, yr, prof); }\n        }\n    }\n\n    // Naive sliding windows X (larger MAXW)\n    const int MAXW = 400;\n    for (int i = 0; i < N; ++i) {\n        int ymin = INT_MAX, ymax = INT_MIN;\n        for (int j = i; j < N && j - i + 1 <= MAXW; ++j) {\n            ymin = min(ymin, mxs[j].y); ymax = max(ymax, mxs[j].y);\n            int xl = mxs[i].x, xr = mxs[j].x; if (xl >= xr) continue;\n            int aa = j - i + 1;\n            auto lit = lower_bound(sxs.begin(), sxs.end(), Point{xl, INT_MIN});\n            auto rit = upper_bound(lit, sxs.end(), Point{xr, INT_MAX});\n            int bb = 0;\n            for (auto it = lit; it != rit; ++it) if (ymin <= it->y && it->y <= ymax) ++bb;\n            update(xl, xr, ymin, ymax, aa - bb);\n        }\n    }\n    // Naive sliding windows Y\n    for (int i = 0; i < N; ++i) {\n        int xmin = INT_MAX, xmax = INT_MIN;\n        for (int j = i; j < N && j - i + 1 <= MAXW; ++j) {\n            xmin = min(xmin, mys[j].x); xmax = max(xmax, mys[j].x);\n            int yl = mys[i].y, yr = mys[j].y; if (yl >= yr) continue;\n            int aa = j - i + 1;\n            Point plow = {INT_MIN, yl}; auto lit = lower_bound(sys.begin(), sys.end(), plow, comp_y);\n            Point pup = {INT_MAX, yr}; auto rit = upper_bound(lit, sys.end(), pup, comp_y);\n            int bb = 0;\n            for (auto it = lit; it != rit; ++it) if (xmin <= it->x && it->x <= xmax) ++bb;\n            update(xmin, xmax, yl, yr, aa - bb);\n        }\n    }\n\n    // Gap-based clusters X-> BB+KadaneY\n    vector<int> gapths = {4000, 6000, 10000, 15000, 25000};\n    for (int gth : gapths) {\n        vector<pair<int,int>> clus;\n        int st = 0;\n        for (int k = 1; k < N; ++k) {\n            if (mxs[k].x - mxs[k - 1].x > gth) {\n                clus.emplace_back(st, k - 1);\n                st = k;\n            }\n        }\n        clus.emplace_back(st, N - 1);\n        for (auto [si, sj] : clus) {\n            if (si > sj) continue;\n            int xl = mxs[si].x, xr = mxs[sj].x; if (xl >= xr) continue;\n            // BB Y\n            int ymin = INT_MAX, ymax = INT_MIN;\n            for (int k = si; k <= sj; ++k) { ymin = min(ymin, mxs[k].y); ymax = max(ymax, mxs[k].y); }\n            int aa = sj - si + 1;\n            auto lit = lower_bound(sxs.begin(), sxs.end(), Point{xl, INT_MIN});\n            auto rit = upper_bound(lit, sxs.end(), Point{xr, INT_MAX});\n            int bb = 0;\n            for (auto it = lit; it != rit; ++it) if (ymin <= it->y && it->y <= ymax) ++bb;\n            update(xl, xr, ymin, ymax, aa - bb);\n            // Kadane Y\n            vector<pair<int,int>> events; events.reserve(1024);\n            for (int k = si; k <= sj; ++k) events.emplace_back(mxs[k].y, 1);\n            for (auto it = lit; it != rit; ++it) events.emplace_back(it->y, -1);\n            sort(events.begin(), events.end());\n            auto [prof, prng] = get_max_sub(events);\n            if (prof > 0) { auto [yl, yr] = prng; update(xl, xr, yl, yr, prof); }\n        }\n    }\n\n    // Gap-based clusters Y-> BB+KadaneX\n    for (int gth : gapths) {\n        vector<pair<int,int>> clus;\n        int st = 0;\n        for (int k = 1; k < N; ++k) {\n            if (mys[k].y - mys[k - 1].y > gth) {\n                clus.emplace_back(st, k - 1);\n                st = k;\n            }\n        }\n        clus.emplace_back(st, N - 1);\n        for (auto [si, sj] : clus) {\n            if (si > sj) continue;\n            int yl = mys[si].y, yr = mys[sj].y; if (yl >= yr) continue;\n            // BB X\n            int xmin = INT_MAX, xmax = INT_MIN;\n            for (int k = si; k <= sj; ++k) { xmin = min(xmin, mys[k].x); xmax = max(xmax, mys[k].x); }\n            int aa = sj - si + 1;\n            Point plow = {INT_MIN, yl}; auto lit = lower_bound(sys.begin(), sys.end(), plow, comp_y);\n            Point pup = {INT_MAX, yr}; auto rit = upper_bound(lit, sys.end(), pup, comp_y);\n            int bb = 0;\n            for (auto it = lit; it != rit; ++it) if (xmin <= it->x && it->x <= xmax) ++bb;\n            update(xmin, xmax, yl, yr, aa - bb);\n            // Kadane X\n            vector<pair<int,int>> events; events.reserve(1024);\n            for (int k = si; k <= sj; ++k) events.emplace_back(mys[k].x, 1);\n            for (auto it = lit; it != rit; ++it) events.emplace_back(it->x, -1);\n            sort(events.begin(), events.end());\n            auto [prof, prng] = get_max_sub(events);\n            if (prof > 0) { auto [xl, xr] = prng; update(xl, xr, yl, yr, prof); }\n        }\n    }\n\n    // Fallback\n    if (best_xl >= best_xr || best_yl >= best_yr) {\n        auto r = make_small_rect(mack[0]);\n        best_xl = INT_MAX; best_xr = INT_MIN; best_yl = INT_MAX; best_yr = INT_MIN;\n        for (auto& pt : r) {\n            best_xl = min(best_xl, pt.x); best_xr = max(best_xr, pt.x);\n            best_yl = min(best_yl, pt.y); best_yr = max(best_yr, pt.y);\n        }\n    }\n\n    cout << 4 << '\\n' << best_xl << ' ' << best_yl << '\\n'\n         << best_xr << ' ' << best_yl << '\\n' << best_xr << ' ' << best_yr << '\\n'\n         << best_xl << ' ' << best_yr << '\\n';\n\n    return 0;\n}","ahc040":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstruct Rect {\n    ll xl, xr, yt, yb;\n};\n\nstruct Placement {\n    int p, r, d, b;\n};\n\nstruct State {\n    vector<Rect> pos;\n    vector<Placement> placed_seq;\n    vector<int> placed_list;\n    int next_id;\n    ll cur_maxw, cur_maxh, penalty;\n};\n\nll get_score(const State& s) {\n    return s.cur_maxw + s.cur_maxh + s.penalty;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int N, T;\n    ll sigma;\n    cin >> N >> T >> sigma;\n    vector<ll> est_w(N), est_h(N);\n    for (int i = 0; i < N; i++) {\n        cin >> est_w[i] >> est_h[i];\n    }\n\n    const int BEAM_SIZE = 256;\n    const int MAX_BASES = 20;\n    const int NUM_PROBE = 40;\n\n    vector<State> beam(1);\n    beam[0].pos.assign(N, Rect{-1LL, -1LL, -1LL, -1LL});\n    beam[0].placed_seq.clear();\n    beam[0].placed_list.clear();\n    beam[0].next_id = 0;\n    beam[0].cur_maxw = 0;\n    beam[0].cur_maxh = 0;\n    beam[0].penalty = 0;\n\n    for (int step = 0; step < N; step++) {\n        vector<State> next_beam;\n        next_beam.reserve(200000);\n        for (const auto& st : beam) {\n            int nid = st.next_id;\n            if (nid == N) continue;\n\n            // Skip option\n            {\n                State news = st;\n                news.penalty += est_w[nid] + est_h[nid];\n                news.next_id++;\n                next_beam.push_back(std::move(news));\n            }\n\n            // Possible bases: -1 + recent placed\n            vector<int> poss_b;\n            poss_b.reserve(MAX_BASES + 1);\n            poss_b.push_back(-1);\n            int num_recent = min(MAX_BASES, (int)st.placed_list.size());\n            for (int ii = 0; ii < num_recent; ii++) {\n                poss_b.push_back(st.placed_list[st.placed_list.size() - 1 - ii]);\n            }\n\n            // Place options\n            for (int rot = 0; rot < 2; rot++) {\n                ll ww = rot ? est_h[nid] : est_w[nid];\n                ll hh = rot ? est_w[nid] : est_h[nid];\n                for (int dd = 0; dd < 2; dd++) {\n                    for (int bb : poss_b) {\n                        ll xl_, xr_, yt_, yb_;\n                        if (dd == 0) {  // U\n                            xl_ = (bb == -1 ? 0LL : st.pos[bb].xr);\n                            xr_ = xl_ + ww;\n                            yt_ = 0;\n                            for (int j = 0; j < nid; j++) {\n                                if (st.pos[j].xl < 0) continue;\n                                ll lx = max(st.pos[j].xl, xl_);\n                                ll rx = min(st.pos[j].xr, xr_);\n                                if (lx < rx) {\n                                    yt_ = max(yt_, st.pos[j].yb);\n                                }\n                            }\n                            yb_ = yt_ + hh;\n                        } else {  // L\n                            yt_ = (bb == -1 ? 0LL : st.pos[bb].yb);\n                            yb_ = yt_ + hh;\n                            xl_ = 0;\n                            for (int j = 0; j < nid; j++) {\n                                if (st.pos[j].xl < 0) continue;\n                                ll ty = max(st.pos[j].yt, yt_);\n                                ll by_ = min(st.pos[j].yb, yb_);\n                                if (ty < by_) {\n                                    xl_ = max(xl_, st.pos[j].xr);\n                                }\n                            }\n                            xr_ = xl_ + ww;\n                        }\n                        State news = st;\n                        news.pos[nid] = {xl_, xr_, yt_, yb_};\n                        news.placed_seq.push_back({nid, rot, dd, bb});\n                        news.placed_list.push_back(nid);\n                        news.next_id++;\n                        news.cur_maxw = max(st.cur_maxw, xr_);\n                        news.cur_maxh = max(st.cur_maxh, yb_);\n                        next_beam.push_back(std::move(news));\n                    }\n                }\n            }\n        }\n        // Sort by score\n        sort(next_beam.begin(), next_beam.end(), [](const State& a, const State& b) {\n            return get_score(a) < get_score(b);\n        });\n        // Keep top\n        beam.clear();\n        beam.reserve(BEAM_SIZE);\n        int keep_cnt = min(BEAM_SIZE, (int)next_beam.size());\n        for (int k = 0; k < keep_cnt; k++) {\n            beam.push_back(std::move(next_beam[k]));\n        }\n    }\n\n    // Sort final beam\n    sort(beam.begin(), beam.end(), [](const State& a, const State& b) {\n        return get_score(a) < get_score(b);\n    });\n\n    // Probing phase\n    int num_probe = min({NUM_PROBE, (int)beam.size(), T});\n    ll min_proxy = LLONG_MAX;\n    int best_cid = 0;\n    for (int t = 0; t < T; t++) {\n        int cid = (t < num_probe ? t : best_cid);\n        const auto& conf = beam[cid].placed_seq;\n        cout << conf.size() << '\\n';\n        for (const auto& pl : conf) {\n            cout << pl.p << ' ' << pl.r << ' ' << (pl.d == 0 ? \"U\" : \"L\") << ' ' << pl.b << '\\n';\n        }\n        cout.flush();\n\n        ll Wp, Hp;\n        cin >> Wp >> Hp;\n\n        if (t < num_probe) {\n            ll proxy = Wp + Hp + beam[t].penalty;\n            if (proxy < min_proxy) {\n                min_proxy = proxy;\n                best_cid = t;\n            }\n        }\n    }\n    return 0;\n}","ahc041":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\npair<ll, bool> eval(const vector<vector<int>>& dist, const vector<int>& A, int N, int H, const vector<int>& S) {\n  const int INF = 1000000000;\n  ll sc = 0;\n  for (int v = 0; v < N; ++v) {\n    int dmin = INF;\n    for (int r : S) dmin = min(dmin, dist[r][v]);\n    if (dmin > H) return {0, false};\n    sc += 1LL * dmin * A[v];\n  }\n  return {sc, true};\n}\n\nint farthest(const vector<vector<int>>& adj, int start) {\n  int N = adj.size();\n  const int INF = 1000000000;\n  vector<int> dep(N, INF);\n  vector<bool> vis(N, false);\n  queue<int> q;\n  dep[start] = 0;\n  vis[start] = true;\n  q.push(start);\n  int far = start;\n  while (!q.empty()) {\n    int u = q.front(); q.pop();\n    far = u;\n    for (int nei : adj[u]) {\n      if (!vis[nei]) {\n        vis[nei] = true;\n        dep[nei] = dep[u] + 1;\n        q.push(nei);\n      }\n    }\n  }\n  return far;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  srand(42);\n  int N, M, H;\n  cin >> N >> M >> H;\n  vector<int> A(N);\n  for (int &a : A) cin >> a;\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  vector<int> X(N), Y(N);\n  for (int i = 0; i < N; ++i) {\n    cin >> X[i] >> Y[i];\n  }\n  const int INF = 1000000000;\n  vector<vector<int>> dist(N, vector<int>(N, INF));\n  for (int s = 0; s < N; ++s) {\n    vector<int> dep(N, INF);\n    vector<bool> vis(N, false);\n    queue<int> q;\n    dep[s] = 0;\n    vis[s] = true;\n    q.push(s);\n    while (!q.empty()) {\n      int u = q.front(); q.pop();\n      for (int nei : adj[u]) {\n        if (!vis[nei]) {\n          vis[nei] = true;\n          dep[nei] = dep[u] + 1;\n          q.push(nei);\n        }\n      }\n    }\n    dist[s] = dep;\n  }\n  // Precompute balls\n  vector<vector<int>> ball(N);\n  for (int r = 0; r < N; ++r) {\n    for (int v = 0; v < N; ++v) {\n      if (dist[r][v] <= H) ball[r].push_back(v);\n    }\n  }\n  // High-A\n  vector<pair<int, int>> high_A(N);\n  for (int i = 0; i < N; ++i) high_A[i] = {-A[i], i};\n  sort(high_A.begin(), high_A.end());\n  vector<int> top_highA;\n  for (int i = 0; i < min(100, N); ++i) top_highA.push_back(high_A[i].second);\n  // High-degree\n  vector<pair<int, int>> high_deg(N);\n  for (int i = 0; i < N; ++i) high_deg[i] = {-(int)adj[i].size(), i};\n  sort(high_deg.begin(), high_deg.end());\n  vector<int> top_highdeg;\n  for (int i = 0; i < min(50, N); ++i) top_highdeg.push_back(high_deg[i].second);\n  // Diameter ends\n  vector<int> diam_ends;\n  int rand_start = rand() % N;\n  int f1 = farthest(adj, rand_start);\n  int f2 = farthest(adj, f1);\n  diam_ends = {f1, f2};\n  // From f2, second farthest? approx more\n  vector<int> dep2(N, INF);\n  // reuse BFS from f2 if needed, but simple add f1,f2\n  auto get_greedy_roots = [&](int typ, int tie_highA) -> vector<int> {\n    bitset<1000> uncovered; uncovered.set();\n    vector<int> roots;\n    while (uncovered.any()) {\n      ll best_prof = -1;\n      int best_r = -1;\n      int best_ar = tie_highA ? INT_MIN : INT_MAX;\n      for (int r = 0; r < N; ++r) {\n        ll prof = 0;\n        for (int v : ball[r]) {\n          if (uncovered.test(v)) {\n            int d = dist[r][v];\n            if (typ == 0) prof += 1LL * d * A[v];\n            else if (typ == 1) ++prof;\n            else prof += A[v];\n          }\n        }\n        int comp_ar = tie_highA ? -A[r] : A[r];\n        bool better = (prof > best_prof) ||\n                      (prof == best_prof && comp_ar < best_ar);\n        if (better) {\n          best_prof = prof;\n          best_r = r;\n          best_ar = comp_ar;\n        }\n      }\n      assert(best_r != -1);\n      roots.push_back(best_r);\n      for (int v : ball[best_r]) uncovered.reset(v);\n    }\n    return roots;\n  };\n  auto get_farthest_graph = [&](bool weighted) -> vector<int> {\n    vector<int> roots;\n    vector<int> min_dd(N, INF);\n    while (true) {\n      ll max_dd = -1;\n      int best_u = -1;\n      int best_au = INT_MAX;\n      for (int u = 0; u < N; ++u) {\n        ll dd = weighted ? 1LL * min_dd[u] * A[u] : min_dd[u];\n        bool better = (dd > max_dd) || (dd == max_dd && A[u] < best_au);\n        if (better) {\n          max_dd = dd;\n          best_u = u;\n          best_au = A[u];\n        }\n      }\n      if (max_dd <= H) break;\n      roots.push_back(best_u);\n      for (int v = 0; v < N; ++v) min_dd[v] = min(min_dd[v], dist[best_u][v]);\n    }\n    return roots;\n  };\n  auto get_farthest_geo = [&](bool weighted) -> vector<int> {\n    vector<double> min_d(N, 1e18);\n    vector<int> roots;\n    int num_added = 0;\n    while (num_added < 100) {\n      double max_dd = -1;\n      int best_u = -1;\n      int best_au = INT_MAX;\n      for (int u = 0; u < N; ++u) {\n        double dd = weighted ? min_d[u] * A[u] : min_d[u];\n        bool better = (dd > max_dd) || (dd == max_dd && A[u] < best_au);\n        if (better) {\n          max_dd = dd;\n          best_u = u;\n          best_au = A[u];\n        }\n      }\n      if (max_dd <= 300.0) break;\n      roots.push_back(best_u);\n      for (int v = 0; v < N; ++v) {\n        double dgeo = hypot(X[best_u] - X[v], Y[best_u] - Y[v]);\n        min_d[v] = min(min_d[v], dgeo);\n      }\n      ++num_added;\n    }\n    return roots;\n  };\n  // Top solo centers\n  vector<pair<ll, int>> solos(N);\n  for (int r = 0; r < N; ++r) {\n    ll prof = 0;\n    for (int v : ball[r]) prof += 1LL * dist[r][v] * A[v];\n    solos[r] = {prof, r};\n  }\n  sort(solos.rbegin(), solos.rend());\n  vector<int> top_centers;\n  for (int i = 0; i < min(200, N); ++i) top_centers.push_back(solos[i].second);\n  // Candidates\n  vector<vector<int>> candidates{\n      get_greedy_roots(0, 0), get_greedy_roots(0, 1),  // depth profit, low/high A tie\n      get_greedy_roots(1, 0), get_greedy_roots(2, 0),\n      get_farthest_graph(false), get_farthest_graph(true),\n      get_farthest_geo(false), get_farthest_geo(true),\n      top_highA, top_highdeg, diam_ends, top_centers\n  };\n  ll best_sc = -1;\n  vector<int> best_S;\n  for (auto& S_ : candidates) {\n    sort(S_.begin(), S_.end());\n    S_.erase(unique(S_.begin(), S_.end()), S_.end());\n    auto [sc, valid] = eval(dist, A, N, H, S_);\n    if (valid && sc > best_sc) {\n      best_sc = sc;\n      best_S = S_;\n    }\n  }\n  // Prune\n  auto prune = [&]() -> bool {\n    bool improved = false;\n    for (size_t i = 0; i < best_S.size(); ++i) {\n      vector<int> trial;\n      for (size_t j = 0; j < best_S.size(); ++j) if (j != i) trial.push_back(best_S[j]);\n      auto [sc_trial, valid] = eval(dist, A, N, H, trial);\n      if (valid && sc_trial >= best_sc) {\n        best_sc = sc_trial;\n        best_S = move(trial);\n        improved = true;\n        break;\n      }\n    }\n    return improved;\n  };\n  while (prune());\n  // Neighbor LS extended\n  int ls_iters = 0;\n  bool ls_imp;\n  do {\n    ls_imp = false;\n    unordered_set<int> root_set(best_S.begin(), best_S.end());\n    vector<int> neigh_cands;\n    for (int r : best_S) for (int nb : adj[r]) if (root_set.count(nb) == 0) neigh_cands.push_back(nb);\n    sort(neigh_cands.begin(), neigh_cands.end());\n    neigh_cands.erase(unique(neigh_cands.begin(), neigh_cands.end()), neigh_cands.end());\n    for (size_t i = 0; i < best_S.size(); ++i) {\n      for (int nc : neigh_cands) {\n        vector<int> temp_S;\n        for (size_t j = 0; j < best_S.size(); ++j) if (j != i) temp_S.push_back(best_S[j]);\n        temp_S.push_back(nc);\n        sort(temp_S.begin(), temp_S.end());\n        temp_S.erase(unique(temp_S.begin(), temp_S.end()), temp_S.end());\n        auto [sc_t, valid] = eval(dist, A, N, H, temp_S);\n        if (valid && sc_t > best_sc) {\n          best_sc = sc_t;\n          best_S = move(temp_S);\n          ls_imp = true;\n          goto next_ls;\n        }\n      }\n    }\n    next_ls:;\n    ++ls_iters;\n  } while (ls_imp && ls_iters < 40);\n  // Biased randomized hill-climb, bias to good cands\n  vector<int> good_cands;\n  good_cands.insert(good_cands.end(), top_centers.begin(), top_centers.end());\n  good_cands.insert(good_cands.end(), top_highA.begin(), top_highA.end());\n  good_cands.insert(good_cands.end(), diam_ends.begin(), diam_ends.end());\n  sort(good_cands.begin(), good_cands.end());\n  good_cands.erase(unique(good_cands.begin(), good_cands.end()), good_cands.end());\n  const int ext_iters = 50000;\n  for (int iter = 0; iter < ext_iters; ++iter) {\n    vector<int> trial = best_S;\n    int r = rand() % 100;\n    bool did_change = false;\n    if (r < 20 && trial.size() > 1) {  // remove 20%\n      size_t idx = rand() % trial.size();\n      trial.erase(trial.begin() + idx);\n      did_change = true;\n    } else if (r < 45) {  // add good 25%\n      int ci = rand() % good_cands.size();\n      int cand = good_cands[ci];\n      auto it = find(trial.begin(), trial.end(), cand);\n      if (it == trial.end()) {\n        trial.push_back(cand);\n        did_change = true;\n      }\n    } else if (r < 80) {  // replace with good 35%\n      if (!trial.empty()) {\n        size_t idx = rand() % trial.size();\n        int ci = rand() % good_cands.size();\n        int cand = good_cands[ci];\n        auto it = find(trial.begin(), trial.end(), cand);\n        if (it == trial.end()) {\n          trial[idx] = cand;\n          did_change = true;\n        }\n      }\n    } else {  // neigh move 20%\n      if (!trial.empty()) {\n        size_t idx = rand() % trial.size();\n        int old_r = trial[idx];\n        if (!adj[old_r].empty()) {\n          int nci = rand() % adj[old_r].size();\n          int nc = adj[old_r][nci];\n          auto it = find(trial.begin(), trial.end(), nc);\n          if (it == trial.end()) {\n            trial[idx] = nc;\n            did_change = true;\n          }\n        }\n      }\n    }\n    if (did_change) {\n      sort(trial.begin(), trial.end());\n      trial.erase(unique(trial.begin(), trial.end()), trial.end());\n      auto [sc_t, valid] = eval(dist, A, N, H, trial);\n      if (valid && sc_t > best_sc) {\n        best_sc = sc_t;\n        best_S = move(trial);\n      }\n    }\n  }\n  // Final prune\n  while (prune());\n  // Build forest\n  vector<int> parent(N, -1);\n  vector<int> dep(N, INF);\n  queue<int> q;\n  for (int r : best_S) {\n    dep[r] = 0;\n    parent[r] = -1;\n    q.push(r);\n  }\n  while (!q.empty()) {\n    int u = q.front(); q.pop();\n    for (int v : adj[u]) {\n      if (dep[v] == INF) {\n        dep[v] = dep[u] + 1;\n        parent[v] = u;\n        q.push(v);\n      }\n    }\n  }\n  for (int i = 0; i < N; ++i) {\n    cout << parent[i];\n    if (i + 1 < N) cout << \" \";\n  }\n  cout << \"\\n\";\n}","ahc042":"#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<string> board(N);\n    vector<vector<int>> state(N, vector<int>(N, 0));\n    for (int i = 0; i < N; ++i) {\n        cin >> board[i];\n        for (int j = 0; j < N; ++j) {\n            if (board[i][j] == 'x') {\n                state[i][j] = 1;\n            }\n        }\n    }\n    \n    // kmax\n    vector<int> row_left_kmax(N), row_right_kmax(N);\n    for (int r = 0; r < N; ++r) {\n        int first_o = N;\n        for (int j = 0; j < N; ++j) if (board[r][j] == 'o') { first_o = j; break; }\n        row_left_kmax[r] = first_o;\n        int last_o = -1;\n        for (int j = N - 1; j >= 0; --j) if (board[r][j] == 'o') { last_o = j; break; }\n        row_right_kmax[r] = N - 1 - last_o;\n    }\n    vector<int> col_up_kmax(N), col_down_kmax(N);\n    for (int c = 0; c < N; ++c) {\n        int first_o = N;\n        for (int i = 0; i < N; ++i) if (board[i][c] == 'o') { first_o = i; break; }\n        col_up_kmax[c] = first_o;\n        int last_o = -1;\n        for (int i = N - 1; i >= 0; --i) if (board[i][c] == 'o') { last_o = i; break; }\n        col_down_kmax[c] = N - 1 - last_o;\n    }\n    \n    using Op = pair<char, int>;\n    vector<Op> best_sol;\n    size_t min_t = SIZE_MAX;\n    \n    // Heuristic 1-2: All-rows / all-cols optimal split cover\n    auto try_global = [&](const vector<vector<int>>& xs, const vector<int>& k_prefix, const vector<int>& k_suffix,\n                          char d_prefix, char d_suffix, char opp_prefix, char opp_suffix) -> vector<Op> {\n        vector<Op> ops;\n        bool feasible = true;\n        for (int ln = 0; ln < N; ++ln) {\n            vector<int> ps = xs[ln];\n            int m = ps.size();\n            if (m == 0) continue;\n            sort(ps.begin(), ps.end());\n            long long best_c = LLONG_MAX / 2;\n            int best_kpre = 0, best_ksuf = 0;\n            // all prefix\n            if (m > 0) {\n                int maxp = ps.back();\n                int kp = maxp + 1;\n                if (kp <= k_prefix[ln]) {\n                    long long c = 2LL * kp;\n                    if (c < best_c) {\n                        best_c = c;\n                        best_kpre = kp;\n                        best_ksuf = 0;\n                    }\n                }\n            }\n            // all suffix\n            if (m > 0) {\n                int minp = ps[0];\n                int ks = N - minp;\n                if (ks <= k_suffix[ln]) {\n                    long long c = 2LL * ks;\n                    if (c < best_c) {\n                        best_c = c;\n                        best_kpre = 0;\n                        best_ksuf = ks;\n                    }\n                }\n            }\n            // splits\n            for (int s = 0; s <= m; ++s) {\n                long long c = 0;\n                int kp = 0, ks = 0;\n                bool ok = true;\n                if (s > 0) {\n                    int maxpl = ps[s - 1];\n                    kp = maxpl + 1;\n                    if (kp > k_prefix[ln]) ok = false;\n                    else c += 2LL * kp;\n                }\n                if (s < m) {\n                    int minpr = ps[s];\n                    ks = N - minpr;\n                    if (ks > k_suffix[ln]) ok = false;\n                    else c += 2LL * ks;\n                }\n                if (ok && c < best_c) {\n                    best_c = c;\n                    best_kpre = kp;\n                    best_ksuf = ks;\n                }\n            }\n            if (best_c >= LLONG_MAX / 2) {\n                feasible = false;\n                break;\n            }\n            // add ops prefix first\n            for (int t = 0; t < best_kpre; ++t) ops.emplace_back(d_prefix, ln);\n            for (int t = 0; t < best_kpre; ++t) ops.emplace_back(opp_prefix, ln);\n            // suffix\n            for (int t = 0; t < best_ksuf; ++t) ops.emplace_back(d_suffix, ln);\n            for (int t = 0; t < best_ksuf; ++t) ops.emplace_back(opp_suffix, ln);\n        }\n        if (feasible) return ops;\n        return {};\n    };\n    \n    // row_xs\n    vector<vector<int>> row_xs(N);\n    for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) if (state[i][j]) row_xs[i].push_back(j);\n    auto row_ops = try_global(row_xs, row_left_kmax, row_right_kmax, 'L', 'R', 'R', 'L');\n    if (!row_ops.empty() && row_ops.size() < min_t) {\n        min_t = row_ops.size();\n        best_sol = row_ops;\n    }\n    \n    // col_xs\n    vector<vector<int>> col_xs(N);\n    for (int j = 0; j < N; ++j) for (int i = 0; i < N; ++i) if (state[i][j]) col_xs[j].push_back(i);\n    auto col_ops = try_global(col_xs, col_up_kmax, col_down_kmax, 'U', 'D', 'D', 'U');\n    if (!col_ops.empty() && col_ops.size() < min_t) {\n        min_t = col_ops.size();\n        best_sol = col_ops;\n    }\n    \n    // Greedy variants\n    for (int var_id = 0; var_id < 4; ++var_id) {\n        auto temp_state = state;\n        vector<Op> ops;\n        int rem_x = 0;\n        for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) rem_x += temp_state[i][j];\n        while (rem_x > 0) {\n            double best_score = -1.0;\n            int best_cnt = 0;\n            int best_kk = N + 1;\n            char best_d = ' ';\n            int best_p = -1;\n            // rows L\n            for (int r = 0; r < N; ++r) {\n                int kmaxx = row_left_kmax[r];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    for (int j = 0; j < kk; ++j) cntt += temp_state[r][j];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'L';\n                        best_p = r;\n                    }\n                }\n            }\n            // rows R\n            for (int r = 0; r < N; ++r) {\n                int kmaxx = row_right_kmax[r];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    int st = N - kk;\n                    for (int j = st; j < N; ++j) cntt += temp_state[r][j];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'R';\n                        best_p = r;\n                    }\n                }\n            }\n            // cols U\n            for (int c = 0; c < N; ++c) {\n                int kmaxx = col_up_kmax[c];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    for (int i = 0; i < kk; ++i) cntt += temp_state[i][c];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'U';\n                        best_p = c;\n                    }\n                }\n            }\n            // cols D\n            for (int c = 0; c < N; ++c) {\n                int kmaxx = col_down_kmax[c];\n                for (int kk = 1; kk <= kmaxx; ++kk) {\n                    int cntt = 0;\n                    int st = N - kk;\n                    for (int i = st; i < N; ++i) cntt += temp_state[i][c];\n                    if (cntt == 0) continue;\n                    double score;\n                    if (var_id == 0) score = (double)cntt / kk;\n                    else if (var_id == 1) score = 1e4 * cntt + (double)cntt / kk;\n                    else if (var_id == 2) score = (double)cntt * cntt / kk;\n                    else score = (double)cntt / sqrt(kk);\n                    bool better = score > best_score + 1e-9 ||\n                                  (abs(score - best_score) < 1e-9 && (cntt > best_cnt ||\n                                   (cntt == best_cnt && kk < best_kk)));\n                    if (better) {\n                        best_score = score;\n                        best_cnt = cntt;\n                        best_kk = kk;\n                        best_d = 'D';\n                        best_p = c;\n                    }\n                }\n            }\n            if (best_cnt == 0) break;  // safeguard\n            // apply\n            char dir = best_d;\n            int p = best_p;\n            int kk = best_kk;\n            char opp;\n            if (dir == 'L') opp = 'R';\n            else if (dir == 'R') opp = 'L';\n            else if (dir == 'U') opp = 'D';\n            else opp = 'U';\n            for (int t = 0; t < kk; ++t) ops.emplace_back(dir, p);\n            for (int t = 0; t < kk; ++t) ops.emplace_back(opp, p);\n            // update temp_state\n            if (dir == 'L' || dir == 'R') {\n                int r = p;\n                int st = (dir == 'L' ? 0 : N - kk);\n                for (int pos = st; pos < st + kk; ++pos) {\n                    temp_state[r][pos] = 0;\n                }\n            } else {\n                int c = p;\n                int st = (dir == 'U' ? 0 : N - kk);\n                for (int pos = st; pos < st + kk; ++pos) {\n                    temp_state[pos][c] = 0;\n                }\n            }\n            rem_x -= best_cnt;\n        }\n        size_t this_t = ops.size();\n        if (this_t < min_t) {\n            min_t = this_t;\n            best_sol = move(ops);\n        }\n    }\n    \n    // Output best\n    for (const auto& op : best_sol) {\n        cout << op.first << ' ' << op.second << '\\n';\n    }\n    return 0;\n}","ahc044":"#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nconst int N = 100;\nconst int L = 500000;\n\nll Target[N];\nint best_a[N], best_b[N];\n\nmt19937 rng(42);\n\nll compute_error(const int A[], const int B[], int cnt[] = nullptr) {\n  int lcnt[N] = {};\n  int cur = 0;\n  lcnt[0]++;\n  for (int w = 1; w < L; ++w) {\n    int t = lcnt[cur];\n    int nxt = (t & 1) ? A[cur] : B[cur];\n    lcnt[nxt]++;\n    cur = nxt;\n  }\n  ll e = 0;\n  for (int i = 0; i < N; ++i) {\n    e += abs((ll)lcnt[i] - Target[i]);\n  }\n  if (cnt) memcpy(cnt, lcnt, sizeof(int) * N);\n  return e;\n}\n\nint biased_pick(ll cumpick[], ll totals) {\n  uint64_t rr = ((uint64_t)rng() << 32) | rng();\n  ll rval = rr % totals;\n  int low = 0, high = N - 1;\n  while (low <= high) {\n    int mid = (low + high) / 2;\n    if (cumpick[mid + 1] > rval) high = mid - 1;\n    else low = mid + 1;\n  }\n  return low;\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int dummyN, dummyL;\n  cin >> dummyN >> dummyL;\n  for (int i = 0; i < N; ++i) cin >> Target[i];\n\n  ll cumpick[N + 1];\n  cumpick[0] = 0;\n  ll totals = 0;\n  for (int j = 0; j < N; ++j) {\n    cumpick[j + 1] = cumpick[j] + Target[j] + 1;\n    totals += Target[j] + 1;\n  }\n\n  ll best_err = LLONG_MAX / 2;\n  memset(best_a, 0, sizeof(best_a));\n  memset(best_b, 0, sizeof(best_b));\n\n  const int TRIALS = 200;\n  for (int trial = 0; trial < TRIALS; ++trial) {\n    ll projected[N] = {};\n    int temp_a[N], temp_b[N];\n\n    // Order by target desc + small perturb\n    vector<pair<ll, int>> sorter(N);\n    for (int i = 0; i < N; ++i) {\n      ll perturb = (ll)(rng() % 201) - 100;\n      sorter[i] = {Target[i] * 100LL + perturb, i};\n    }\n    sort(sorter.rbegin(), sorter.rend());\n    vector<int> order(N);\n    for (int k = 0; k < N; ++k) order[k] = sorter[k].second;\n\n    // Greedy assign top deficits\n    for (int oi = 0; oi < N; ++oi) {\n      int i = order[oi];\n      vector<pair<ll, int>> defs(N);\n      for (int j = 0; j < N; ++j) {\n        ll defic = Target[j] - (j == 0 ? 1LL : 0LL) - projected[j];\n        defs[j] = {defic, j};\n      }\n      sort(defs.rbegin(), defs.rend());\n      int nr1 = min(5, N);\n      int nr2 = min(5, N);\n      int r1 = rng() % nr1;\n      int r2 = rng() % nr2;\n      temp_a[i] = defs[r1].second;\n      temp_b[i] = defs[r2].second;\n\n      ll oddf = (Target[i] + 1) / 2;\n      ll evenf = Target[i] / 2;\n      projected[temp_a[i]] += oddf;\n      projected[temp_b[i]] += evenf;\n    }\n\n    ll this_err = compute_error(temp_a, temp_b);\n    if (this_err < best_err) {\n      best_err = this_err;\n      memcpy(best_a, temp_a, sizeof(int) * N);\n      memcpy(best_b, temp_b, sizeof(int) * N);\n    }\n  }\n\n  // Local search\n  const int LOCAL_STEPS = 100;\n  const int TRIES_PER_STEP = 5;\n  for (int step = 0; step < LOCAL_STEPS; ++step) {\n    int temp_a[N], temp_b[N];\n    memcpy(temp_a, best_a, sizeof(int) * N);\n    memcpy(temp_b, best_b, sizeof(int) * N);\n    int i = rng() % N;\n    bool is_a = (rng() % 2 == 0);\n    int* temp = is_a ? temp_a : temp_b;\n    int old_val = temp[i];\n\n    ll best_this_err = best_err;\n    int best_newj = old_val;\n    for (int ty = 0; ty < TRIES_PER_STEP; ++ty) {\n      int newj;\n      if (rng() % 4 == 0) {\n        newj = i;  // self\n      } else if (rng() % 3 == 0) {\n        newj = biased_pick(cumpick, totals);\n      } else {\n        newj = rng() % N;\n      }\n      temp[i] = newj;\n      ll newe = compute_error(temp_a, temp_b);\n      if (newe < best_this_err) {\n        best_this_err = newe;\n        best_newj = newj;\n      }\n    }\n    if (best_this_err < best_err) {\n      best_err = best_this_err;\n      temp[i] = best_newj;\n    }\n  }\n\n  // Refine: greedy on actual deficits from current best\n  {\n    int cur_cnt[N];\n    compute_error(best_a, best_b, cur_cnt);\n    ll deficits[N];\n    for (int j = 0; j < N; ++j) {\n      deficits[j] = Target[j] - cur_cnt[j];\n    }\n\n    // Order by |deficit| desc\n    vector<pair<ll, int>> sorter(N);\n    for (int i = 0; i < N; ++i) {\n      sorter[i] = {abs(deficits[i]) * 100LL + (rng() % 201LL - 100), i};\n    }\n    sort(sorter.rbegin(), sorter.rend());\n    vector<int> order(N);\n    for (int k = 0; k < N; ++k) order[k] = sorter[k].second;\n\n    int ref_a[N], ref_b[N];\n    memcpy(ref_a, best_a, sizeof(int) * N);\n    memcpy(ref_b, best_b, sizeof(int) * N);\n    for (int oi = 0; oi < N; ++oi) {\n      int i = order[oi];\n      vector<pair<ll, int>> defs(N);\n      for (int j = 0; j < N; ++j) {\n        defs[j] = {deficits[j], j};\n      }\n      sort(defs.rbegin(), defs.rend());\n      int nr = min(3, N);\n      int r1 = rng() % nr;\n      int r2 = rng() % nr;\n      ref_a[i] = defs[r1].second;\n      ref_b[i] = defs[r2].second;\n    }\n    ll newe = compute_error(ref_a, ref_b);\n    if (newe < best_err) {\n      memcpy(best_a, ref_a, sizeof(int) * N);\n      memcpy(best_b, ref_b, sizeof(int) * N);\n      best_err = newe;\n    }\n  }\n\n  for (int i = 0; i < N; ++i) {\n    cout << best_a[i] << ' ' << best_b[i] << '\\n';\n  }\n}","ahc045":"#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing pii = pair<int, int>;\nusing vpii = vector<pii>;\nusing u32 = uint32_t;\nusing tiii = tuple<int, int, int>;  // d, a, b with a < b\n\nu32 hilbert_order(int xx, int yy) {\n  const int n = 16384;\n  int x = max(0, min(n - 1, xx));\n  int y = max(0, min(n - 1, yy));\n  u32 d = 0;\n  u32 s;\n  for (s = n / 2; s > 0; s >>= 1) {\n    u32 rx = (x & s) > 0;\n    u32 ry = (y & s) > 0;\n    d += s * s * ((3 * rx) ^ ry);\n    if (ry == 0) {\n      if (rx == 1) {\n        x = n - 1 - x;\n        y = n - 1 - y;\n      }\n      swap(x, y);\n    }\n  }\n  return d;\n}\n\nvoid get_mst(const vector<int>& C, vpii& mst_edges) {\n  int l = C.size();\n  cout << \"? \" << l;\n  for (int u : C) cout << \" \" << u;\n  cout << endl << flush;\n  mst_edges.resize(l - 1);\n  for (int i = 0; i < l - 1; i++) {\n    int a, b;\n    cin >> a >> b;\n    if (a > b) swap(a, b);\n    mst_edges[i] = {a, b};\n  }\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M, Q_max, L, W;\n  cin >> N >> M >> Q_max >> L >> W;\n  vi G(M);\n  for (auto& g : G) cin >> g;\n  vi lx(N), rx(N), ly(N), ry(N);\n  vi cx(N), cy(N);\n  for (int i = 0; i < N; i++) {\n    cin >> lx[i] >> rx[i] >> ly[i] >> ry[i];\n    cx[i] = (lx[i] + rx[i]) / 2;\n    cy[i] = (ly[i] + ry[i]) / 2;\n  }\n  vector<u32> hidx(N);\n  for (int i = 0; i < N; i++) {\n    hidx[i] = hilbert_order(cx[i], cy[i]);\n  }\n  vi order(N);\n  iota(order.begin(), order.end(), 0);\n  auto cmp = [&](int i, int j) { return hidx[i] < hidx[j]; };\n  sort(order.begin(), order.end(), cmp);\n  vi cum(M + 1, 0);\n  for (int i = 1; i <= M; i++) {\n    cum[i] = cum[i - 1] + G[i - 1];\n  }\n  vvi groups(M);\n  for (int m = 0; m < M; m++) {\n    groups[m].assign(order.begin() + cum[m], order.begin() + cum[m + 1]);\n  }\n  auto proxy_dist = [&](int a, int b) -> int {\n    ll dx = cx[a] - cx[b];\n    ll dy = cy[a] - cy[b];\n    ll dd = dx * dx + dy * dy;\n    int res = (int)sqrt((double)dd);\n    while (1LL * (res + 1) * (res + 1) <= dd) ++res;\n    while (1LL * res * res > dd) --res;\n    return res;\n  };\n  vector<vpii> all_trees(M);\n  int queries_used = 0;\n  int step_size = 3;\n  for (int m = 0; m < M; m++) {\n    int g = groups[m].size();\n    if (g < 2) {\n      all_trees[m] = {};\n      continue;\n    }\n    vi C = groups[m];\n    vpii candidates;\n    if (g <= L) {\n      vpii temp;\n      get_mst(C, temp);\n      queries_used++;\n      all_trees[m] = std::move(temp);\n      continue;\n    }\n    // large group\n    int wsz = L;\n    int pos = 0;\n    while (pos + wsz <= g) {\n      vi sub(C.begin() + pos, C.begin() + pos + wsz);\n      vpii temp;\n      get_mst(sub, temp);\n      queries_used++;\n      for (auto e : temp) candidates.push_back(e);\n      pos += step_size;\n    }\n    if (pos < g) {\n      int rem = g - pos;\n      if (rem >= 2) {\n        int lsz = min(wsz, rem);\n        vi sub(C.begin() + pos, C.begin() + pos + lsz);\n        vpii temp;\n        get_mst(sub, temp);\n        queries_used++;\n        for (auto e : temp) candidates.push_back(e);\n      }\n    }\n    // now Kruskal with proxy dist\n    vi local_id(N, -1);\n    for (int loc = 0; loc < g; loc++) {\n      local_id[C[loc]] = loc;\n    }\n    vector<tiii> cand_edges;\n    for (auto [a, b] : candidates) {\n      int dd = proxy_dist(a, b);\n      cand_edges.emplace_back(dd, a, b);\n    }\n    // add consecutive edges\n    for (int i = 0; i < g - 1; i++) {\n      int u = C[i], v = C[i + 1];\n      int uu = min(u, v), vv = max(u, v);\n      int dd = proxy_dist(u, v);\n      cand_edges.emplace_back(dd, uu, vv);\n    }\n    // sort by proxy dist\n    sort(cand_edges.begin(), cand_edges.end());\n    // union-find\n    vi par(g);\n    iota(par.begin(), par.end(), 0);\n    auto find = [&](auto&& self, int x) -> int {\n      return par[x] == x ? x : par[x] = self(self, par[x]);\n    };\n    vpii tree_edges;\n    for (auto [d, aa, bb] : cand_edges) {\n      int la = local_id[aa], lb = local_id[bb];\n      int pa = find(find, la), pb = find(find, lb);\n      if (pa != pb) {\n        par[pa] = pb;\n        tree_edges.emplace_back(aa, bb);\n        if ((int)tree_edges.size() == g - 1) break;\n      }\n    }\n    // fallback if not connected\n    if ((int)tree_edges.size() < g - 1) {\n      tree_edges.clear();\n      for (int i = 0; i < g - 1; i++) {\n        int u = C[i], v = C[i + 1];\n        if (u > v) swap(u, v);\n        tree_edges.emplace_back(u, v);\n      }\n    }\n    all_trees[m] = std::move(tree_edges);\n  }\n  cout << \"!\" << endl;\n  for (int m = 0; m < M; m++) {\n    for (size_t i = 0; i < groups[m].size(); ++i) {\n      if (i > 0) cout << \" \";\n      cout << groups[m][i];\n    }\n    cout << '\\n';\n    for (const auto& e : all_trees[m]) {\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\nstruct State {\n  short k, p, b;\n};\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int N, M;\n  cin >> N >> M;\n  vector<pair<int, int>> pos(M);\n  for (int i = 0; i < M; ++i) {\n    cin >> pos[i].first >> pos[i].second;\n  }\n  const int NN = N * N;\n  const int BB = NN + 1;\n  const int KK = M;\n  const long long TOT = (long long)KK * NN * BB;\n  const short INF_S = 32001;\n  auto encode = [NN, BB](int kk, int pp, int bb) -> long long {\n    int bid = (bb < 0 ? 0 : bb + 1);\n    return ((long long)kk * NN + pp) * BB + bid;\n  };\n  vector<short> dist(TOT, INF_S);\n  vector<short> prev_k(TOT, -1);\n  vector<short> prev_p(TOT, -1);\n  vector<short> prev_b(TOT, -1);\n  vector<char> came_act(TOT, 0);\n  vector<char> came_dir(TOT, 0);\n  vector<int> target_id(M - 1);\n  for (int i = 0; i < M - 1; ++i) {\n    target_id[i] = pos[i + 1].first * N + pos[i + 1].second;\n  }\n  int start_p = pos[0].first * N + pos[0].second;\n  long long sstate = encode(0, start_p, -1);\n  dist[sstate] = 0;\n  queue<State> q;\n  q.push({0, (short)start_p, -1});\n  int dr[] = {-1, 1, 0, 0};\n  int dc[] = {0, 0, -1, 1};\n  char dirch[] = {'U', 'D', 'L', 'R'};\n  while (!q.empty()) {\n    State cs = q.front();\n    q.pop();\n    int ck = cs.k;\n    int cp = cs.p;\n    int cb = cs.b;\n    long long cstate = encode(ck, cp, cb);\n    short cd = dist[cstate];\n    if (cd == INF_S) continue;\n    if (ck == M - 1) continue;\n    int cr = cp / N;\n    int cc = cp % N;\n    int block_r = (cb >= 0 ? cb / N : -1);\n    int block_c = (cb >= 0 ? cb % N : -1);\n    // Slides first\n    for (int d = 0; d < 4; ++d) {\n      int er = cr, ec = cc;\n      while (true) {\n        int nr = er + dr[d];\n        int nc = ec + dc[d];\n        if (nr < 0 || nr >= N || nc < 0 || nc >= N ||\n            (cb >= 0 && nr == block_r && nc == block_c)) break;\n        er = nr;\n        ec = nc;\n      }\n      int np = er * N + ec;\n      int nb = cb;\n      int nk = ck;\n      if (ck < M - 1 && np == target_id[ck]) nk = ck + 1;\n      long long nstate = encode(nk, np, nb);\n      short nd = cd + 1;\n      if (dist[nstate] > nd) {\n        dist[nstate] = nd;\n        prev_k[nstate] = (short)ck;\n        prev_p[nstate] = (short)cp;\n        prev_b[nstate] = (short)cb;\n        came_act[nstate] = 'S';\n        came_dir[nstate] = dirch[d];\n        q.push({(short)nk, (short)np, (short)nb});\n      }\n    }\n    // Moves\n    for (int d = 0; d < 4; ++d) {\n      int nr = cr + dr[d];\n      int nc = cc + dc[d];\n      if (nr < 0 || nr >= N || nc < 0 || nc >= N ||\n          (cb >= 0 && nr == block_r && nc == block_c)) continue;\n      int np = nr * N + nc;\n      int nb = cb;\n      int nk = ck;\n      if (ck < M - 1 && np == target_id[ck]) nk = ck + 1;\n      long long nstate = encode(nk, np, nb);\n      short nd = cd + 1;\n      if (dist[nstate] > nd) {\n        dist[nstate] = nd;\n        prev_k[nstate] = (short)ck;\n        prev_p[nstate] = (short)cp;\n        prev_b[nstate] = (short)cb;\n        came_act[nstate] = 'M';\n        came_dir[nstate] = dirch[d];\n        q.push({(short)nk, (short)np, (short)nb});\n      }\n    }\n    // Alters\n    for (int d = 0; d < 4; ++d) {\n      int ar = cr + dr[d];\n      int ac = cc + dc[d];\n      if (ar < 0 || ar >= N || ac < 0 || ac >= N) continue;\n      int adjp = ar * N + ac;\n      int nb = cb;\n      if (cb == -1) {\n        nb = adjp;\n      } else if (cb == adjp) {\n        nb = -1;\n      } else {\n        continue;\n      }\n      int np = cp;\n      int nk = ck;\n      long long nstate = encode(nk, np, nb);\n      short nd = cd + 1;\n      if (dist[nstate] > nd) {\n        dist[nstate] = nd;\n        prev_k[nstate] = (short)ck;\n        prev_p[nstate] = (short)cp;\n        prev_b[nstate] = (short)cb;\n        came_act[nstate] = 'A';\n        came_dir[nstate] = dirch[d];\n        q.push({(short)nk, (short)np, (short)nb});\n      }\n    }\n  }\n  // Find min dist to any final state k=M-1\n  short min_d = INF_S;\n  int best_cp = -1;\n  int best_cb = -1;\n  for (int pp = 0; pp < NN; ++pp) {\n    for (int bidx = 0; bidx < BB; ++bidx) {\n      int bi = (bidx == 0 ? -1 : bidx - 1);\n      long long tstate = encode(M - 1, pp, bi);\n      if (dist[tstate] < min_d) {\n        min_d = dist[tstate];\n        best_cp = pp;\n        best_cb = bi;\n      }\n    }\n  }\n  if (min_d == INF_S) {\n    // Impossible, fallback empty but shouldn't happen\n    return 0;\n  }\n  // Reconstruct path\n  vector<pair<char, char>> path;\n  path.reserve(2000);\n  int ck = M - 1;\n  int cp = best_cp;\n  int cb = best_cb;\n  while (!(ck == 0 && cp == start_p && cb == -1)) {\n    long long cstate = encode(ck, cp, cb);\n    path.emplace_back(came_act[cstate], came_dir[cstate]);\n    ck = prev_k[cstate];\n    cp = prev_p[cstate];\n    cb = prev_b[cstate];\n  }\n  reverse(path.begin(), path.end());\n  for (auto [a, d] : path) {\n    cout << a << ' ' << d << '\\n';\n  }\n  return 0;\n}"}}}