//ルールを遵守し、元のPythonコードを生成AIを用いて仕様などそのままにC++に変換しました。 #include #include #include #include using namespace std; struct State { long long score; int r; int c; vector visited; vector> path; bool operator<(const State& other) const { return score > other.score; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); auto start = chrono::steady_clock::now(); int n, t; if (!(cin >> n >> t)) { return 0; } vector> g(n, vector(n)); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cin >> g[i][j]; } } vector init; for (int r = 0; r < n; ++r) { for (int c = 0; c < n; ++c) { int s = g[r][c]; int fid = r * n + c; vector visited(n * n, false); visited[fid] = true; vector> p; p.push_back({r, c}); init.push_back({(long long)s, r, c, visited, p}); } } vector> res_p; long long mx = -1; int dr[] = {-1, 1, 0, 0}; int dc[] = {0, 0, -1, 1}; double lim = 1.99; int bw = 5; while (true) { auto now = chrono::steady_clock::now(); chrono::duration diff = now - start; if (diff.count() > lim) { break; } sort(init.begin(), init.end()); vector bm; bool full = false; if (init.size() > (size_t)bw) { for (int i = 0; i < bw; ++i) { bm.push_back(init[i]); } full = true; } else { bm = init; } bool over = false; for (int step = 0; step < t - 1; ++step) { vector nxt; for (const auto& cur : bm) { long long cs = cur.score; int cr = cur.r; int cc = cur.c; if (cs > mx) { mx = cs; res_p = cur.path; } for (int i = 0; i < 4; ++i) { int nr = cr + dr[i]; int nc = cc + dc[i]; if (nr >= 0 && nr < n && nc >= 0 && nc < n) { int tid = nr * n + nc; if (!cur.visited[tid]) { long long ns = cs + g[nr][nc]; vector> np = cur.path; np.push_back({nr, nc}); vector nv = cur.visited; nv[tid] = true; nxt.push_back({ns, nr, nc, nv, np}); } } } } if (nxt.empty()) { break; } sort(nxt.begin(), nxt.end()); if (nxt.size() > (size_t)bw) { bm.clear(); for (int i = 0; i < bw; ++i) { bm.push_back(nxt[i]); } full = true; } else { bm = nxt; } auto now_inner = chrono::steady_clock::now(); chrono::duration diff_inner = now_inner - start; if (diff_inner.count() > lim) { over = true; break; } } for (const auto& fst : bm) { if (fst.score > mx) { mx = fst.score; res_p = fst.path; } } if (over || !full) { break; } bw = (int)(bw * 1.5); } cout << res_p.size() << "\n"; for (const auto& pos : res_p) { cout << pos.first << " " << pos.second << "\n"; } return 0; }