题面
来源:FrontierCS 官方 statement.txt,与模型收到的题面相同。
Story
--------
AtCoder frequently hosts onsite contests and has decided to build its own contest venue.
The planned construction site is in a mountain area, and the ground must first be leveled.
Leveling will involve using a dump truck, which incurs costs for loading, unloading, and transporting soil.
Determine the method to level the ground with as little cost as possible.
Problem Statement
--------
There is an $N \times N$ grid of land.
Let $(0,0)$ be the coordinates of the top-left square and $(i,j)$ be the coordinates of the square located $i$ squares down and $j$ squares to the right from there.
The height $h_{i,j}$ of each square $(i,j)$ is given as input.
The total height of all squares is exactly $0$.
Initially, the dump truck is at the square $(0,0)$ with an empty load.
In each turn, you can perform one of the following three operations:
- Specify an integer $d$ satisfying $0<d\leq 10^6$ to load $d$ units of soil from the current square onto the dump truck. This operation decreases the height of the current square by $d$ and increases the amount of soil loaded onto the dump truck by $d$. The height can become negative. This operation incurs a cost of $d$.
- Specify an integer $d$ satisfying $0<d\leq 10^6$ to unload $d$ units of soil from the dump truck to the current square. This operation increases the height of the current square by $d$ and decreases the amount of soil loaded onto the dump truck by $d$. The value of $d$ must not exceed the amount of soil currently loaded onto the dump truck. This operation incurs a cost of $d$.
- Move the dump truck to an adjacent square (up, down, left, or right). The dump truck cannot move outside the $N \times N$ grid. If the dump truck has $d$ units of soil loaded, this operation incurs a cost of $100+d$.
You can perform a maximum of $100000$ turns of operation.
Your task is to determine the sequence of operations that minimizes the cost to make the height of every square $0$.
Raw task objective
--------
The formulas in this section define the raw reward V, not final benchmark points. The Scoring section specifies the per-file award and its aggregation.
Let $\mathrm{cost}$ be the total cost of the output operation sequence.
Let $\mathrm{base}$ be the sum of $|h_{i,j}|$ for all $(i,j)$.
Let $h_{i,j}'$ be the final height of square $(i,j)$.
Define $\mathrm{diff}$ as the sum of $100|h_{i,j}'|+10000$ for all $(i,j)$ such that $h_{i,j}' \neq 0$.
The raw task reward V is defined as follows.
\\[
\mathrm{round}\left(10^9\times \frac{\mathrm{base}}{\mathrm{cost}+\mathrm{diff}}\right)
\\]
Input
--------
Input is given from Standard Input in the following format:
~~~
$N$
$h_{0,0}$ $\cdots$ $h_{0,N-1}$
$\vdots$
$h_{N-1,0}$ $\cdots$ $h_{N-1,N-1}$
~~~
In all test cases, $N$ is fixed at $20$.
The initial height $h_{i,j}$ of square $(i,j)$ is an integer that satisfies $-100 \leq h_{i,j} \leq 100$, and the total sum of all heights is guaranteed to be $0$.
Output
--------
Let $T$ be the number of operation turns.
The operation in the $t$-th turn is represented by the string $s_t$ as follows:
- The operation to load $d$ units of soil from the current square onto the dump truck: `+d`
- The operation to unload $d$ units of soil from the dump truck to the current square: `-d`
- The operation to move the dump truck to an adjacent square: `U`, `D`, `L`, and `R` for up, down, left, and right, respectively.
Then, output to Standard Output in the following format:
~~~
$s_0$
$\vdots$
$s_{T-1}$
~~~
<a href="https://img.atcoder.jp/ahc034/vImT4eac.html?lang=en&seed=0&output=sample">Show example</a>
Input Generation
--------
<details>
<p>
You are not required to understand this.
We recommend changing the seed value in the web visualizer to observe what kind of inputs are generated.
</p>
<p>
Let $\mathrm{rand}(L,U)$ be a function that generates a uniform random integer between $L$ and $U$, inclusive.
Let $\mathrm{noise}(y,x,\mathrm{seed})$ be a function that generates two-dimensional <a href="https://en.wikipedia.org/wiki/Perlin_noise">Perlin noise</a> scaled to the range between $-1$ and $1$ based on a random seed value $\mathrm{seed}$.
</p>
<p>
First, generate a seed value for Perlin noise generation as $\mathrm{seed}=\mathrm{rand}(0,2^{32}-1)$.
</p>
<p>
Next, for each $(i,j)$, generate $h_{i,j}=\mathrm{round}(\mathrm{noise}(i/10,j/10,\mathrm{seed})\times 50)$.
If $h_{i,j}=0$ for all $(i,j)$, then regenerate $\mathrm{seed}$.
</p>
<p>
Let $S$ be the sum of $h_{i,j}$.
To make $S=0$, perform the following transformation.
</p>
<p>
Shuffle all coordinates $(0,0),(0,1),\cdots,(N-1,N-1)$ in a uniformly random order, and let the $k$-th coordinate be $(i_k,j_k)$.
If $S>0$, then for each $k=0,1,\cdots,S-1$, decrease $h_{i_{k\% N^2},j_{k\% N^2}}$ by $1$.
If $S<0$, then for each $k=0,1,\cdots,-S-1$, increase $h_{i_{k\% N^2},j_{k\% N^2}}$ by $1$.
</p>
</details>
Tools (Input generator and visualizer)
--------
- <a href="https://img.atcoder.jp/ahc034/vImT4eac.html?lang=en">Web version</a>: This is more powerful than the local version providing animations.
- <a href="https://img.atcoder.jp/ahc034/vImT4eac.zip">Local version</a>: You need a compilation environment of <a href="https://www.rust-lang.org/">Rust language</a>.
- <a href="https://img.atcoder.jp/ahc034/vImT4eac_windows.zip">Pre-compiled binary for Windows</a>: If you are not familiar with the Rust language environment, please use this instead.
Please be aware that sharing visualization results or discussing solutions/ideas during the contest is prohibited.
{sample example}
## Scoring
All feasibility and interaction limits apply before scoring; invalid output receives zero. Points are averaged over test files. For the logarithmic branch, write x for the original minimizing quantity and a for its physical 60-point reference. The improvement factor is r=a/x, and the upper-band award is P=min(100,60+ln(r)). Here ln is natural: r=1 corresponds to 60 points, and on the uncapped logarithmic upper band, r=exp(P-60). Each additional point multiplies the physical improvement factor by e (divides a minimizing objective by e or multiplies a maximizing objective by e, as applicable). The lower-band, zero-objective, and completion rules below still apply.
Let V be the raw task reward defined in the problem, and let B and R be the stored baseline and reference rewards. They are calibration values, not assertions of optimality. The stored reward reference R is distinct from the physical reference a used in the logarithm; a is defined by the inverse or stage-specific formula below. Set L=60*max(0,(V-B)/(R-B)), with R>B, and T=R. For nonzero minimizing objectives, and all maximizing objectives, keep L exactly whenever L<=60. The following describes the upper band and any valid zero-cost optimum.
Here E is the operation cost plus sum(10000+100*abs(h)) over cells whose final height h is nonzero; K is the sum of absolute initial cell heights. For E>0, the raw reward is V=round(1e9*K/E); for E=0 the raw reward is set to zero, but the valid zero-cost award below takes priority. Use physical reference a=A=1e9*K/R. A valid E=0 earns 100 before testing L. For E>0 and L>60, take x=E, a=A, and r=a/x; award min(100,60+ln(r)). A nonpositive anchor has no defined positive-cost logarithmic comparison, so retain the existing nonzero-cost branch.
The stored reference reward is rounded. Its physical anchor is chosen by analytically inverting the unrounded reward at the center R (or T for a special branch). The lower-band condition keeps every result with the original 60-point reward at exactly 60. A rounded reward is not evidence of zero physical error or cost.
The checker reports points/100.
结果
Kimi K3.1 ProKimi
max
0.0
平均得分 ↑
- 0.0采样 1 · 运行错误
- 30.0k平均输出 token(含思考) ↓
- 30.5输出速度 tokens/s ↑
- 986 秒延迟 ↓
Kimi K3.1 Pro(high)Kimi high
high
27.5
平均得分 ↑
- 27.5采样 1 · 部分分
- 14.0k平均输出 token(含思考) ↓
- 26.2输出速度 tokens/s ↑
- 537 秒延迟 ↓
DeepSeek Flash V4.1-1017DeepSeek
auto(high)
2.1
平均得分 ↑
- 2.1采样 1 · 部分分
- 35.3k平均输出 token(含思考) ↓
- 179.6输出速度 tokens/s ↑
- 197 秒延迟 ↓
MiniMax M3.1 FlashMiniMax
auto(max)
0.0
平均得分 ↑
- 0.0采样 1 · 编译错误
- 69.5k平均输出 token(含思考) ↓
- 84.4输出速度 tokens/s ↑
- 825 秒延迟 ↓
↑ 越大越好,↓ 越小越好。得分 0–100,按官方时限判定,所有测试点都满分才算解出。CPU 时间 / 官方解为解出的答案在官方解最慢的 3 个测试点上的 CPU 时间之比(几何平均),只比较官方解至少需要 0.05 秒的题;复杂度按增长幂次相对官方解分类。判题与计分见 原理。
代码
Kimi K3.1 Pro · 采样 1 · 403 行
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll INF = (1LL << 60); struct Plan { vector<string> ops; ll cost = INF; bool valid = false; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; const int M = N * N; vector<int> h(M); bool any = false; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { cin >> h[i * N + j]; if (h[i * N + j] != 0) any = true; } } if (!any) return 0; auto startTime = chrono::steady_clock::now(); vector<vector<int>> dist(M, vector<int>(M)); for (int a = 0; a < M; ++a) { for (int b = 0; b < M; ++b) { dist[a][b] = abs(a / N - b / N) + abs(a % N - b % N); } } auto adjacent = [&](int a, int b) { return dist[a][b] == 1; }; struct Eval { ll cost = INF; int start = 0; int steps = 0; }; auto evaluate = [&](const vector<int>& c) { Eval ev; vector<ll> pref(M + 1, 0); vector<int> prevBefore(M, -1); ll sumAfter = 0; ll mn = 0; int prev = -1; int lastAny = -1; for (int k = 0; k < M; ++k) { prevBefore[k] = prev; pref[k + 1] = pref[k] + h[c[k]]; sumAfter += pref[k + 1]; mn = min(mn, pref[k + 1]); if (h[c[k]] != 0) { prev = k; lastAny = k; } } ll transport = sumAfter - (ll)M * mn; int bestMetric = INT_MAX; for (int s = 0; s < M; ++s) { if (pref[s] != mn) continue; int p = prevBefore[s]; if (p < 0) p = lastAny; int tail = (p - s + M) % M; int metric = dist[0][c[s]] + tail; if (metric < bestMetric) { bestMetric = metric; ev.start = s; ev.steps = tail; } } ev.cost = transport + 100LL * bestMetric; return ev; }; vector<pair<int, int>> baseCoords; for (int j = 0; j < N; ++j) baseCoords.push_back({0, j}); for (int i = 1; i < N; ++i) { if (i & 1) { for (int j = N - 1; j >= 1; --j) baseCoords.push_back({i, j}); } else { for (int j = 1; j < N; ++j) baseCoords.push_back({i, j}); } } for (int i = N - 1; i >= 1; --i) baseCoords.push_back({i, 0}); auto normalizedReverse = [&](const vector<int>& c) { vector<int> r(M); r[0] = c[0]; for (int k = 1; k < M; ++k) r[k] = c[M - k]; return r; }; vector<int> bestCycle; ll bestCost = INF; for (int t = 0; t < 8; ++t) { vector<int> c; c.reserve(M); for (auto [rr, cc] : baseCoords) { int r = rr, col = cc; if (t & 1) swap(r, col); if (t & 2) r = N - 1 - r; if (t & 4) col = N - 1 - col; c.push_back(r * N + col); } int z = 0; while (c[z] != 0) ++z; rotate(c.begin(), c.begin() + z, c.begin()); for (int rev = 0; rev < 2; ++rev) { Eval ev = evaluate(c); if (ev.cost < bestCost) { bestCost = ev.cost; bestCycle = c; } if (!rev) c = normalizedReverse(c); } } mt19937 rng(712367821); vector<int> current = bestCycle; ll currentCost = bestCost; vector<int> posInCycle(M); auto rebuildPos = [&]() { for (int k = 0; k < M; ++k) posInCycle[current[k]] = k; }; rebuildPos(); uniform_real_distribution<double> prob(0.0, 1.0); double progress = 0.0; bool intensified = false; ll iteration = 0; const double searchSeconds = 1.65; while (true) { ++iteration; if ((iteration & 1023) == 0) { double elapsed = chrono::duration<double>( chrono::steady_clock::now() - startTime).count(); if (elapsed >= searchSeconds) break; progress = elapsed / searchSeconds; if (progress > 0.72 && !intensified) { current = bestCycle; currentCost = bestCost; rebuildPos(); intensified = true; } } if ((iteration & 4095) == 0) { vector<int> rev = normalizedReverse(current); Eval ev = evaluate(rev); if (ev.cost < currentCost) { current = rev; currentCost = ev.cost; rebuildPos(); if (currentCost < bestCost) { bestCost = currentCost; bestCycle = current; } } continue; } int i = (int)(rng() % M); int A = current[i]; int B = current[(i + 1) % M]; int ar = A / N, ac = A % N; int br = B / N, bc = B % N; int dr = br - ar, dc = bc - ac; int side = (rng() & 1) ? 1 : -1; int pr = -dc * side; int pc = dr * side; int cr = ar + pr, cc = ac + pc; int dr2 = br + pr, dc2 = bc + pc; if (cr < 0 || cr >= N || cc < 0 || cc >= N || dr2 < 0 || dr2 >= N || dc2 < 0 || dc2 >= N) { continue; } int C = cr * N + cc; int D = dr2 * N + dc2; int j = posInCycle[C]; if (current[(j + 1) % M] != D) continue; int a = min(i, j), b = max(i, j); if (a == b || b == a + 1 || (a == 0 && b == M - 1)) continue; if (!adjacent(current[a], current[b]) || !adjacent(current[a + 1], current[(b + 1) % M])) { continue; } reverse(current.begin() + a + 1, current.begin() + b + 1); for (int k = a + 1; k <= b; ++k) posInCycle[current[k]] = k; Eval ev = evaluate(current); ll delta = ev.cost - currentCost; double temp = 10000.0 * pow(0.0001, progress) + 0.01; bool accept = (delta <= 0 || prob(rng) < exp(-(double)delta / temp)); if (accept) { currentCost = ev.cost; if (currentCost < bestCost) { bestCost = currentCost; bestCycle = current; } } else { reverse(current.begin() + a + 1, current.begin() + b + 1); for (int k = a + 1; k <= b; ++k) posInCycle[current[k]] = k; } } auto makeCyclePlan = [&]() { Plan plan; plan.ops.clear(); plan.cost = 0; plan.valid = true; Eval ev = evaluate(bestCycle); ll load = 0; int cur = 0; auto addMove = [&](int to) { int r = cur / N, c = cur % N; int nr = to / N, nc = to % N; string op; if (nr == r + 1) op = "D"; else if (nr == r - 1) op = "U"; else if (nc == c + 1) op = "R"; else op = "L"; plan.ops.push_back(op); plan.cost += 100 + load; cur = to; }; int target = bestCycle[ev.start]; int tr = target / N, tc = target % N; while (cur % N < tc) addMove(cur + 1); while (cur % N > tc) addMove(cur - 1); while (cur / N < tr) addMove(cur + N); while (cur / N > tr) addMove(cur - N); for (int rel = 0; rel <= ev.steps; ++rel) { int idx = (ev.start + rel) % M; int cell = bestCycle[idx]; if (cur != cell) { plan.valid = false; return plan; } if (h[cell] > 0) { int d = h[cell]; plan.ops.push_back("+" + to_string(d)); plan.cost += d; load += d; } else if (h[cell] < 0) { int d = -h[cell]; if (load < d) { plan.valid = false; return plan; } plan.ops.push_back("-" + to_string(d)); plan.cost += d; load -= d; } if (rel < ev.steps) { int next = bestCycle[(idx + 1) % M]; if (!adjacent(cur, next)) { plan.valid = false; return plan; } addMove(next); } } if (load != 0 || plan.ops.size() > 100000) plan.valid = false; return plan; }; Plan answer = makeCyclePlan(); auto greedyPlan = [&](int variant) { Plan plan; plan.cost = 0; plan.valid = true; vector<int> w = h; int remaining = 0; for (int x : w) if (x != 0) ++remaining; int cur = 0; ll load = 0; bool horizontalFirst = (variant & 1); int amountWeight = (variant >= 2) ? 15 : 0; auto addMove = [&](int to, const string& op) { plan.ops.push_back(op); plan.cost += 100 + load; cur = to; }; while (remaining > 0) { if ((int)plan.ops.size() > 90000) { plan.valid = false; return plan; } if (load == 0 && w[cur] > 0) { int d = w[cur]; plan.ops.push_back("+" + to_string(d)); plan.cost += d; load += d; w[cur] = 0; --remaining; continue; } if (load > 0 && w[cur] < 0) { int d = (int)min<ll>(load, -w[cur]); plan.ops.push_back("-" + to_string(d)); plan.cost += d; load -= d; w[cur] += d; if (w[cur] == 0) --remaining; continue; } int targetCell = -1; ll bestScore = INF; for (int cell = 0; cell < M; ++cell) { if (load == 0) { if (w[cell] <= 0) continue; } else { if (w[cell] >= 0) continue; } ll score = 100LL * dist[cur][cell]; if (load == 0) { score -= amountWeight * (ll)w[cell]; } else if (variant >= 2 && -w[cell] < load) { score += 40; } if (variant == 3) score += (ll)(rng() % 7); if (score < bestScore) { bestScore = score; targetCell = cell; } } if (targetCell < 0) { plan.valid = false; return plan; } int r = cur / N, c = cur % N; int tr = targetCell / N, tc = targetCell % N; bool canHorizontal = (c != tc); bool canVertical = (r != tr); bool goHorizontal = canHorizontal && (!canVertical || horizontalFirst); if (goHorizontal) { if (tc > c) addMove(cur + 1, "R"); else addMove(cur - 1, "L"); } else { if (tr > r) addMove(cur + N, "D"); else addMove(cur - N, "U"); } } if (load != 0 || plan.ops.size() > 100000) plan.valid = false; return plan; }; for (int variant = 0; variant < 4; ++variant) { Plan p = greedyPlan(variant); if (p.valid && (!answer.valid || p.cost < answer.cost)) { answer = move(p); } } for (const string& op : answer.ops) { cout << op << '\n'; } return 0; }
Kimi K3.1 Pro(high) · 采样 1 · 356 行
#include <bits/stdc++.h> using namespace std; struct Op { int type; // 0: load, 1: unload, 2: U, 3: D, 4: L, 5: R int d; }; struct Config { double emptyLook = 0.0; double nextLook = 0.0; double noise = 0.0; double amountBonus = 0.0; bool oppUnload = false; bool oppPick = false; bool oppLoad = false; int pathStyle = 0; int collectRadius = 0; int collectMaxLoad = 0; double collectRatio = 1.0; }; class Solver { static constexpr int N = 20; static constexpr int CELLS = N * N; array<int, CELLS> initial{}; mt19937 rng{123456789}; vector<Op> bestOps; long long bestCost = (1LL << 62); static int row(int p) { return p / N; } static int col(int p) { return p % N; } static int distance(int a, int b) { return abs(row(a) - row(b)) + abs(col(a) - col(b)); } pair<long long, vector<Op>> simulate(const Config &cfg) { array<int, CELLS> h = initial; vector<Op> ops; ops.reserve(12000); int pos = 0; int load = 0; int posCount = 0, negCount = 0; for (int i = 0; i < CELLS; ++i) { if (h[i] > 0) ++posCount; if (h[i] < 0) ++negCount; } long long cost = 0; auto doLoad = [&](int p) { int d = h[p]; h[p] = 0; load += d; cost += d; --posCount; ops.push_back({0, d}); }; auto doUnload = [&](int p) { int d = min(load, -h[p]); h[p] += d; load -= d; cost += d; if (h[p] == 0) --negCount; ops.push_back({1, d}); }; auto handleCurrent = [&](bool intermediate) { if (h[pos] > 0) { if (load == 0) { if (!intermediate || cfg.oppPick) { doLoad(pos); return true; } } else if (cfg.oppLoad) { doLoad(pos); return true; } } if (h[pos] < 0 && load > 0 && (!intermediate || cfg.oppUnload)) { doUnload(pos); return true; } return false; }; auto moveOne = [&](int type) { if (type == 2) pos -= N; else if (type == 3) pos += N; else if (type == 4) --pos; else ++pos; cost += 100 + load; ops.push_back({type, 0}); }; auto distanceField = [&](bool positive) { array<int, CELLS> dist; dist.fill(-1); queue<int> q; for (int i = 0; i < CELLS; ++i) { if ((positive && h[i] > 0) || (!positive && h[i] < 0)) { dist[i] = 0; q.push(i); } } const int dr[4] = {-1, 1, 0, 0}; const int dc[4] = {0, 0, -1, 1}; while (!q.empty()) { int p = q.front(); q.pop(); int r = row(p), c = col(p); for (int k = 0; k < 4; ++k) { int nr = r + dr[k], nc = c + dc[k]; if (nr < 0 || nr >= N || nc < 0 || nc >= N) continue; int np = nr * N + nc; if (dist[np] != -1) continue; dist[np] = dist[p] + 1; q.push(np); } } return dist; }; auto realNoise = [&]() { return uniform_real_distribution<double>(-1.0, 1.0)(rng); }; while (true) { handleCurrent(false); if (posCount == 0 && negCount == 0 && load == 0) break; int target = -1; if (load == 0) { array<int, CELLS> negDist{}; if (cfg.emptyLook != 0.0) negDist = distanceField(false); double best = 1e100; for (int s = 0; s < CELLS; ++s) { if (h[s] <= 0) continue; double score = distance(pos, s); if (cfg.emptyLook != 0.0 && negDist[s] >= 0) { score += cfg.emptyLook * negDist[s]; } score -= cfg.amountBonus * (double)h[s] / 100.0; score += cfg.noise * realNoise(); if (score < best) { best = score; target = s; } } } else { if (cfg.collectRadius > 0 && load < cfg.collectMaxLoad) { int nearestSource = -1; int ds = 1000; for (int s = 0; s < CELLS; ++s) { if (h[s] <= 0) continue; int d = distance(pos, s); if (d < ds) { ds = d; nearestSource = s; } } if (nearestSource != -1 && ds <= cfg.collectRadius) { array<int, CELLS> negDist = distanceField(false); int dn = negDist[pos] < 0 ? 1000 : negDist[pos]; if (ds < cfg.collectRatio * max(1, dn) + 1.0) { target = nearestSource; } } } if (target == -1) { array<int, CELLS> posDist{}; if (cfg.nextLook != 0.0) posDist = distanceField(true); double best = 1e100; for (int t = 0; t < CELLS; ++t) { if (h[t] >= 0) continue; double score = distance(pos, t); if (cfg.nextLook != 0.0 && load <= -h[t] && posDist[t] >= 0) { score += cfg.nextLook * posDist[t]; } score -= cfg.amountBonus * (double)(-h[t]) / 100.0; score += cfg.noise * realNoise(); if (score < best) { best = score; target = t; } } } } if (target == -1) break; while (pos != target) { int dr = row(target) - row(pos); int dc = col(target) - col(pos); vector<int> options; auto addHorizontal = [&]() { if (dc > 0) options.push_back(5); else if (dc < 0) options.push_back(4); }; auto addVertical = [&]() { if (dr > 0) options.push_back(3); else if (dr < 0) options.push_back(2); }; if (cfg.pathStyle == 0) { addHorizontal(); addVertical(); } else if (cfg.pathStyle == 1) { addVertical(); addHorizontal(); } else { addHorizontal(); addVertical(); if (options.size() == 2) { int chosen = 0; if (cfg.pathStyle == 2) { chosen = (rng() & 1); } else { double utility[2] = {0.0, 0.0}; for (int k = 0; k < 2; ++k) { int np = pos; if (options[k] == 2) np -= N; else if (options[k] == 3) np += N; else if (options[k] == 4) --np; else ++np; if (h[np] < 0 && load > 0 && cfg.oppUnload) { utility[k] += 2.0 + min(load, -h[np]) / 100.0; } if (h[np] > 0 && ((load == 0 && cfg.oppPick) || (load > 0 && cfg.oppLoad))) { utility[k] += 2.0 + h[np] / 100.0; } utility[k] += uniform_real_distribution<double>(0.0, 0.2)(rng); } chosen = utility[1] > utility[0]; } swap(options[0], options[chosen]); } } moveOne(options[0]); if (pos != target && handleCurrent(true)) break; } } return {cost, move(ops)}; } public: void readInput() { int n; cin >> n; for (int i = 0; i < CELLS; ++i) cin >> initial[i]; } void solve() { const int RUNS = 320; for (int run = 0; run < RUNS; ++run) { Config cfg; if (run == 1) { cfg.oppUnload = true; cfg.oppPick = true; cfg.pathStyle = 2; } else if (run == 2) { cfg.emptyLook = 1.0; cfg.oppUnload = true; cfg.oppPick = true; cfg.pathStyle = 3; } else if (run == 3) { cfg.emptyLook = 0.5; cfg.nextLook = 0.5; cfg.oppUnload = true; cfg.oppPick = true; cfg.pathStyle = 3; } else if (run == 4) { cfg.emptyLook = 0.5; cfg.nextLook = 0.25; cfg.oppUnload = true; cfg.oppPick = true; cfg.oppLoad = true; cfg.pathStyle = 3; } else if (run == 5) { cfg.emptyLook = 1.0; cfg.oppUnload = true; cfg.oppPick = true; cfg.oppLoad = true; cfg.pathStyle = 3; cfg.collectRadius = 2; cfg.collectMaxLoad = 400; cfg.collectRatio = 1.0; } else if (run >= 6) { const double looks[] = {0.0, 0.2, 0.4, 0.7, 1.0, 1.5, 2.0}; const double noises[] = {0.0, 0.05, 0.15, 0.35, 0.7, 1.2, 2.0}; cfg.emptyLook = looks[rng() % 7]; cfg.nextLook = looks[rng() % 7]; cfg.noise = noises[rng() % 7]; cfg.amountBonus = (rng() % 5 == 0) ? uniform_real_distribution<double>(0.0, 1.5)(rng) : 0.0; cfg.oppUnload = (rng() % 10 != 0); cfg.oppPick = (rng() % 10 < 8); cfg.oppLoad = (rng() % 10 < 4); cfg.pathStyle = 2 + (rng() & 1); if (rng() % 100 < 38) { cfg.collectRadius = 1 + rng() % 4; const int limits[] = {150, 250, 400, 700, 1200, 20000}; cfg.collectMaxLoad = limits[rng() % 6]; cfg.collectRatio = uniform_real_distribution<double>(0.45, 1.5)(rng); cfg.oppLoad = true; } } auto result = simulate(cfg); if (result.second.size() > 100000) continue; if (result.first < bestCost) { bestCost = result.first; bestOps = move(result.second); } } } void output() const { for (const Op &op : bestOps) { if (op.type == 0) cout << '+' << op.d << '\n'; else if (op.type == 1) cout << '-' << op.d << '\n'; else if (op.type == 2) cout << 'U' << '\n'; else if (op.type == 3) cout << 'D' << '\n'; else if (op.type == 4) cout << 'L' << '\n'; else cout << 'R' << '\n'; } } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); Solver solver; solver.readInput(); solver.solve(); solver.output(); return 0; }
DeepSeek Flash V4.1-1017 · 采样 1 · 241 行
#include <bits/stdc++.h> using namespace std; int N; vector<vector<int>> H; int baseCost; int manhattan(int r1, int c1, int r2, int c2) { return abs(r1-r2) + abs(c1-c2); } void moveTo(int tr, int tc, int load, int& pr, int& pc, vector<string>& ops, long long& cost) { while (pr != tr || pc != tc) { char dir; if (pr < tr) { pr++; dir='D'; } else if (pr > tr) { pr--; dir='U'; } else if (pc < tc) { pc++; dir='R'; } else { pc--; dir='L'; } cost += 100 + load; ops.push_back(string(1, dir)); } } struct Params { bool partial; bool allowPosLoaded; bool lookaheadPos; int noise; double posPenalty; double unloadWeight; }; void runGreedy(const Params& P, vector<string>& bestOps, long long& bestCost) { vector<vector<int>> h = H; int pr=0, pc=0, load=0; long long cost=0; vector<string> ops; ops.reserve(50000); while (true) { bool any = false; for (int i=0;i<N;i++) for (int j=0;j<N;j++) if (h[i][j]!=0) { any=true; break; } if (!any && load==0) break; int tr=-1, tc=-1; if (load == 0) { double bestScore = 1e18; for (int r=0;r<N;r++) for (int c=0;c<N;c++) if (h[r][c] > 0) { int dist = manhattan(pr,pc,r,c); double score = dist * 100.0; if (P.lookaheadPos) { int minNeg = 1000000; for (int nr=0;nr<N;nr++) for (int nc=0;nc<N;nc++) if (h[nr][nc] < 0) { minNeg = min(minNeg, manhattan(r,c,nr,nc)); } if (minNeg == 1000000) minNeg = 0; score += minNeg * (100.0 + h[r][c]) + h[r][c]; } if (P.noise > 0) { score += (rand() % (2*P.noise+1) - P.noise); } if (score < bestScore) { bestScore = score; tr=r; tc=c; } } } else { double bestScore = 1e18; for (int r=0;r<N;r++) for (int c=0;c<N;c++) { if (h[r][c] == 0) continue; bool isPos = h[r][c] > 0; if (isPos && !P.allowPosLoaded) continue; if (!isPos) { if (!P.partial && -h[r][c] > load) continue; } int dist = manhattan(pr,pc,r,c); double score; if (isPos) { score = (100.0 + load) * dist + P.posPenalty * h[r][c]; } else { int unloadAmt = P.partial ? min(load, -h[r][c]) : -h[r][c]; score = (100.0 + load) * dist - P.unloadWeight * unloadAmt; } if (P.noise > 0) { score += (rand() % (2*P.noise+1) - P.noise); } if (score < bestScore) { bestScore = score; tr=r; tc=c; } } if (tr == -1) { bestScore = 1e18; for (int r=0;r<N;r++) for (int c=0;c<N;c++) if (h[r][c] > 0) { int dist = manhattan(pr,pc,r,c); double score = (100.0 + load) * dist; if (P.noise > 0) score += (rand() % (2*P.noise+1) - P.noise); if (score < bestScore) { bestScore = score; tr=r; tc=c; } } } } if (tr == -1) break; moveTo(tr, tc, load, pr, pc, ops, cost); if (h[tr][tc] > 0) { int d = h[tr][tc]; h[tr][tc] = 0; load += d; cost += d; ops.push_back("+" + to_string(d)); } else if (h[tr][tc] < 0) { int d; if (P.partial) { d = min(load, -h[tr][tc]); } else { d = -h[tr][tc]; } h[tr][tc] += d; load -= d; cost += d; ops.push_back("-" + to_string(d)); } } if (ops.size() <= 100000 && cost < bestCost) { bestCost = cost; bestOps = ops; } } void runCycle(const vector<pair<int,int>>& cyc, vector<string>& bestOps, long long& bestCost) { int n = cyc.size(); long long bestLocalCost = LLONG_MAX; int bestStart = -1; for (int s=0; s<n; s++) { int load = 0; bool ok = true; long long sumLoad = 0; for (int i=0; i<n; i++) { int idx = (s+i)%n; int r = cyc[idx].first, c = cyc[idx].second; load += H[r][c]; if (load < 0) { ok = false; break; } if (i < n-1) sumLoad += load; } if (!ok) continue; int dist = manhattan(0,0,cyc[s].first,cyc[s].second); long long cost = (long long)baseCost + 100LL*dist + 100LL*(n-1) + sumLoad; if (cost < bestLocalCost) { bestLocalCost = cost; bestStart = s; } } if (bestStart == -1) return; vector<string> ops; ops.reserve(1000); int pr=0, pc=0; long long cost=0; int sr = cyc[bestStart].first, sc = cyc[bestStart].second; moveTo(sr, sc, 0, pr, pc, ops, cost); int load = 0; for (int i=0; i<n; i++) { int idx = (bestStart + i) % n; int r = cyc[idx].first, c = cyc[idx].second; if (H[r][c] > 0) { int d = H[r][c]; load += d; cost += d; ops.push_back("+" + to_string(d)); } else if (H[r][c] < 0) { int d = -H[r][c]; load -= d; cost += d; ops.push_back("-" + to_string(d)); } if (i < n-1) { int nidx = (bestStart + i + 1) % n; int nr = cyc[nidx].first, nc = cyc[nidx].second; moveTo(nr, nc, load, pr, pc, ops, cost); } } if (ops.size() <= 100000 && cost < bestCost) { bestCost = cost; bestOps = ops; } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> N; H.assign(N, vector<int>(N)); baseCost = 0; for (int i=0;i<N;i++) { for (int j=0;j<N;j++) { cin >> H[i][j]; baseCost += abs(H[i][j]); } } if (baseCost == 0) return 0; vector<string> bestOps; long long bestCost = LLONG_MAX; vector<pair<int,int>> cyc; for (int c=0;c<N;c++) cyc.push_back({0,c}); for (int r=1;r<=N-2;r++) { if (r%2==1) { for (int c=N-1;c>=1;c--) cyc.push_back({r,c}); } else { for (int c=1;c<=N-1;c++) cyc.push_back({r,c}); } } for (int c=N-1;c>=0;c--) cyc.push_back({N-1,c}); for (int r=N-2;r>=1;r--) cyc.push_back({r,0}); runCycle(cyc, bestOps, bestCost); vector<pair<int,int>> revCyc = cyc; reverse(revCyc.begin(), revCyc.end()); runCycle(revCyc, bestOps, bestCost); vector<Params> params; params.push_back({true, false, false, 0, 0, 0}); params.push_back({false, false, false, 0, 0, 0}); params.push_back({true, false, true, 0, 0, 0}); params.push_back({false, false, true, 0, 0, 0}); params.push_back({true, true, true, 0, 10, 10}); params.push_back({false, true, true, 0, 10, 10}); params.push_back({true, true, false, 0, 50, 20}); params.push_back({false, true, false, 0, 50, 20}); for (auto& p : params) { runGreedy(p, bestOps, bestCost); } srand(12345); for (int iter=0; iter<20; iter++) { Params p; p.partial = rand()%2; p.allowPosLoaded = rand()%2; p.lookaheadPos = false; p.noise = (rand()%5)*200; p.posPenalty = 5 + rand()%100; p.unloadWeight = 5 + rand()%100; runGreedy(p, bestOps, bestCost); } for (const string& op : bestOps) { cout << op << '\n'; } return 0; }
MiniMax M3.1 Flash · 采样 1 · 1010 行
#include <bits/stdc++.h> using namespace std; struct Task { int x, y; int delta; // Positive: soil to load, negative: soil to unload. }; struct Operation { char type; int amount; }; class Solver { public: int n, m, startX = 0, startY = 0; vector<vector<int>> height; vector<vector<int>> cellTask; vector<Task> tasks; vector<vector<int>> distMatrix; vector<int> startDist; vector<int> sourceTasks, sinkTasks; int baseCost = 0; mt19937 rng; Solver(int n, vector<vector<int>> h, uint32_t seed) : n(n), height(std::move(h)), rng(seed) { cellTask.assign(n, vector<int>(n, -1)); for (int x = 0; x < n; ++x) { for (int y = 0; y < n; ++y) { if (height[x][y] == 0) continue; int id = (int)tasks.size(); cellTask[x][y] = id; tasks.push_back({x, y, height[x][y]}); baseCost += abs(height[x][y]); if (height[x][y] > 0) sourceTasks.push_back(id); else sinkTasks.push_back(id); } } m = (int)tasks.size(); distMatrix.assign(m, vector<int>(m)); startDist.resize(m); for (int i = 0; i < m; ++i) { startDist[i] = abs(tasks[i].x) + abs(tasks[i].y); for (int j = 0; j < m; ++j) { distMatrix[i][j] = abs(tasks[i].x - tasks[j].x) + abs(tasks[i].y - tasks[j].y); } } } long long routeCost(const vector<int>& order) const { if ((int)order.size() != m) return (1LL << 60); int current = -1; int load = 0; long long cost = 0; for (int t : order) { int d = (current == -1 ? startDist[t] : distMatrix[current][t]); cost += 1LL * d * (100 + load); load += tasks[t].delta; if (load < 0) return (1LL << 60); current = t; } return cost; } vector<int> greedyOrder(double beta, double jitter, bool useResultingLoad) { vector<char> used(m, false); vector<int> order; order.reserve(m); int current = -1; int load = 0; for (int step = 0; step < m; ++step) { double bestScore = 1e100; int best = -1; for (int t = 0; t < m; ++t) { if (used[t]) continue; int newLoad = load + tasks[t].delta; if (newLoad < 0) continue; int d = (current == -1 ? startDist[t] : distMatrix[current][t]); double edgeLoad = useResultingLoad ? newLoad : load; double noise = jitter == 0.0 ? 0.0 : (double(rng()) / double(rng.max()) - 0.5) * 2.0 * jitter; double score = d * (100.0 + edgeLoad) + beta * newLoad + noise; if (best == -1 || score < bestScore || (score == bestScore && (rng() & 1))) { bestScore = score; best = t; } } if (best == -1) return {}; used[best] = true; order.push_back(best); load += tasks[best].delta; current = best; } return order; } vector<int> nearestOrder(const vector<int>& candidates) const { vector<char> used(m, false); vector<int> result; int current = -1; for (int k = 0; k < (int)candidates.size(); ++k) { int best = -1, bestDistance = INT_MAX; for (int t : candidates) { if (used[t]) continue; int d = (current == -1 ? startDist[t] : distMatrix[current][t]); if (d < bestDistance || (d == bestDistance && (rng() & 1))) { bestDistance = d; best = t; } } if (best == -1) break; used[best] = true; result.push_back(best); current = best; } return result; } vector<int> snakeOrder(bool rowWise) const { vector<int> order; if (rowWise) { for (int x = 0; x < n; ++x) { if (x & 1) { for (int y = n - 1; y >= 0; --y) if (cellTask[x][y] != -1) order.push_back(cellTask[x][y]); } else { for (int y = 0; y < n; ++y) if (cellTask[x][y] != -1) order.push_back(cellTask[x][y]); } } } else { for (int y = 0; y < n; ++y) { if (y & 1) { for (int x = n - 1; x >= 0; --x) if (cellTask[x][y] != -1) order.push_back(cellTask[x][y]); } else { for (int x = 0; x < n; ++x) if (cellTask[x][y] != -1) order.push_back(cellTask[x][y]); } } } return order; } vector<int> repairFeasible(const vector<int>& original) const { vector<int> order; vector<int> pending; vector<char> emitted(m, false); int load = 0; auto servicePending = [&]() { while (true) { int chosen = -1; for (int i = 0; i < (int)pending.size(); ++i) { int t = pending[i]; if (load + tasks[t].delta >= 0) { chosen = i; break; } } if (chosen == -1) break; int t = pending[chosen]; pending.erase(pending.begin() + chosen); emitted[t] = true; order.push_back(t); load += tasks[t].delta; } }; for (int t : original) { if (emitted[t]) continue; if (tasks[t].delta > 0) { emitted[t] = true; order.push_back(t); load += tasks[t].delta; servicePending(); } else if (load + tasks[t].delta >= 0) { emitted[t] = true; order.push_back(t); load += tasks[t].delta; } else { pending.push_back(t); } } for (int t : pending) { order.push_back(t); load += tasks[t].delta; } return order; } vector<int> beamOrder(int width = 80) { if (m == 0) return {}; struct Node { int parent = -1; int task = -1; int current = -1; int load = 0; long long cost = 0; array<uint64_t, 7> bits{}; }; struct Candidate { int parent; int task; int load; long long cost; double score; }; vector<int> nearestSink(m, 0); for (int t = 0; t < m; ++t) { int best = INT_MAX; for (int s : sinkTasks) { if (s == t) continue; best = min(best, distMatrix[t][s]); } nearestSink[t] = (best == INT_MAX ? 0 : best); } vector<vector<Node>> levels; levels.emplace_back(); for (int depth = 0; depth < m; ++depth) { vector<Candidate> candidates; candidates.reserve(levels.back().size() * (m - depth)); for (int p = 0; p < (int)levels.back().size(); ++p) { const Node& parent = levels.back()[p]; for (int t = 0; t < m; ++t) { if ((parent.bits[t >> 6] >> (t & 63)) & 1ULL) continue; int newLoad = parent.load + tasks[t].delta; if (newLoad < 0) continue; int d = (parent.current == -1 ? startDist[t] : distMatrix[parent.current][t]); long long newCost = parent.cost + 1LL * d * (100 + parent.load); double score = double(newCost) + double(newLoad) * nearestSink[t]; candidates.push_back({p, t, newLoad, newCost, score}); } } if (candidates.empty()) return {}; int poolSize = min((int)candidates.size(), width * 6); if (poolSize < (int)candidates.size()) { nth_element( candidates.begin(), candidates.begin() + poolSize, candidates.end(), [](const Candidate& a, const Candidate& b) { return a.score < b.score; } ); } candidates.resize(poolSize); sort(candidates.begin(), candidates.end(), [](const Candidate& a, const Candidate& b) { return a.score < b.score; }); vector<int> parentCount(levels.back().size(), 0); vector<Candidate> selected; selected.reserve(width); int maxPerParent = max(4, width / 4); for (const Candidate& c : candidates) { if (parentCount[c.parent] >= maxPerParent) continue; parentCount[c.parent]++; selected.push_back(c); if ((int)selected.size() == width) break; } if ((int)selected.size() < width) { for (const Candidate& c : candidates) { if ((int)selected.size() == width) break; bool already = false; for (const Candidate& s : selected) { if (s.parent == c.parent && s.task == c.task) { already = true; break; } } if (!already) selected.push_back(c); } } vector<Node> nextLevel; nextLevel.reserve(selected.size()); for (const Candidate& c : selected) { Node node; node.parent = c.parent; node.task = c.task; node.current = c.task; node.load = c.load; node.cost = c.cost; node.bits = levels.back()[c.parent].bits; node.bits[c.task >> 6] |= 1ULL << (c.task & 63); nextLevel.push_back(node); } levels.push_back(std::move(nextLevel)); } int bestIndex = 0; for (int i = 1; i < (int)levels.back().size(); ++i) { if (levels.back()[i].cost < levels.back()[bestIndex].cost) bestIndex = i; } vector<int> order; int index = bestIndex; for (int depth = m; depth >= 1; --depth) { order.push_back(levels[depth][index].task); index = levels[depth][index].parent; } reverse(order.begin(), order.end()); return order; } bool realizeOrder( const vector<int>& plan, int pathMode, bool earlySource, bool earlySink, vector<int>& extracted ) const { vector<char> processed(m, false); extracted.clear(); int x = 0, y = 0, load = 0; auto processCell = [&](bool forced) -> bool { int t = cellTask[x][y]; if (t == -1 || processed[t]) return true; if (tasks[t].delta > 0) { if (forced || earlySource) { load += tasks[t].delta; processed[t] = true; extracted.push_back(t); } } else { if (load + tasks[t].delta < 0) return forced; if (forced || earlySink) { load += tasks[t].delta; processed[t] = true; extracted.push_back(t); } } return true; }; if (!processCell(false)) return false; auto appendMonotone = [&](int tx, int ty, bool verticalFirst) { if (verticalFirst) { while (x != tx) { if (x < tx) ++x; else --x; } while (y != ty) { if (y < ty) ++y; else --y; } } else { while (y != ty) { if (y < ty) ++y; else --y; } while (x != tx) { if (x < tx) ++x; else --x; } } }; for (int target : plan) { if (processed[target]) continue; int tx = tasks[target].x; int ty = tasks[target].y; if (pathMode >= 2) { int via = -1; int minX = min(x, tx), maxX = max(x, tx); int minY = min(y, ty), maxY = max(y, ty); for (int t = 0; t < m; ++t) { if (processed[t] || t == target) continue; if (tasks[t].x < minX || tasks[t].x > maxX || tasks[t].y < minY || tasks[t].y > maxY) continue; if (pathMode == 2 && tasks[t].delta < 0) { via = t; break; } if (pathMode == 3 && tasks[t].delta > 0) { via = t; break; } } if (via != -1) { int vx = tasks[via].x, vy = tasks[via].y; appendMonotone(vx, vy, (pathMode & 1) != 0); if (!processCell(false)) return false; appendMonotone(tx, ty, (pathMode & 1) == 0); } else { appendMonotone(tx, ty, (pathMode & 1) != 0); } } else { appendMonotone(tx, ty, (pathMode & 1) != 0); } if (!processCell(true)) return false; } int count = 0; for (char c : processed) count += c; return count == m && load == 0; } struct AnnealResult { vector<int> order; long long cost; }; AnnealResult anneal( const vector<int>& initial, int iterations, double initialTemperature, double finalTemperature, vector<int>& globalBest, long long& globalBestCost ) { struct State { vector<int> order; vector<int> prefix; long long cost; }; State current; current.order = initial; current.prefix.assign(m + 1, 0); current.cost = routeCost(current.order); auto rebuild = [&](State& state) { state.prefix.assign(m + 1, 0); for (int i = 0; i < m; ++i) state.prefix[i + 1] = state.prefix[i] + tasks[state.order[i]].delta; state.cost = routeCost(state.order); }; rebuild(current); State runBest = current; if (current.cost < globalBestCost) { globalBestCost = current.cost; globalBest = current.order; } vector<int> segment; segment.reserve(m); uniform_real_distribution<double> uniform01(0.0, 1.0); for (int iteration = 0; iteration < iterations; ++iteration) { double progress = double(iteration) / double(iterations); double temperature = initialTemperature * pow(finalTemperature / initialTemperature, progress); int left = rng() % m; int right = left; int type = rng() % 100; auto randomOther = [&](int a) { if (rng() & 1) { int span = min(30, m - 1); int offset = 1 + rng() % span; int b = a + ((rng() & 1) ? offset : -offset); if (b < 0) b += m; if (b >= m) b -= m; return b; } return rng() % m; }; if (type < 24) { int i = rng() % (m - 1); int j = i + 1; left = i; right = j; segment.assign(current.order.begin() + i, current.order.begin() + j + 1); swap(segment.front(), segment.back()); } else if (type < 44) { int i = randomOther(left); int j = randomOther(i); if (i == j) continue; left = min(i, j); right = max(i, j); segment.assign(current.order.begin() + left, current.order.begin() + right + 1); swap(segment.front(), segment.back()); } else if (type < 69) { int from = rng() % m; int to = randomOther(from); if (from == to) continue; left = min(from, to); right = max(from, to); segment.clear(); if (from < to) { for (int i = from + 1; i <= to; ++i) segment.push_back(current.order[i]); segment.push_back(current.order[from]); } else { segment.push_back(current.order[from]); for (int i = to; i < from; ++i) segment.push_back(current.order[i]); } } else if (type < 84) { if (sourceTasks.empty() || sinkTasks.empty()) continue; int st = sourceTasks[rng() % sourceTasks.size()]; int kt = sinkTasks[rng() % sinkTasks.size()]; int si = -1, ki = -1; for (int i = 0; i < m; ++i) { if (current.order[i] == st) si = i; if (current.order[i] == kt) ki = i; } if (si < 0 || ki < 0 || si == ki) continue; left = min(si, ki); right = max(si, ki); segment.assign(current.order.begin() + left, current.order.begin() + right + 1); swap(segment.front(), segment.back()); } else if (type < 94) { int a = rng() % m; int b = a + 1 + rng() % (m - a - 1); int c = b + 1 + rng() % (m - b); left = a; right = c - 1; segment.clear(); for (int i = b; i < c; ++i) segment.push_back(current.order[i]); for (int i = a; i < b; ++i) segment.push_back(current.order[i]); } else { int i = rng() % m; int j = rng() % m; if (i == j) continue; left = min(i, j); right = max(i, j); segment.assign(current.order.begin() + left, current.order.begin() + right + 1); reverse(segment.begin(), segment.end()); } int i = left, j = right; long long oldCost = 0; long long newCost = 0; int firstDistance; if (i == 0) firstDistance = startDist[current.order[i]]; else firstDistance = distMatrix[current.order[i - 1]][current.order[i]]; oldCost = 1LL * firstDistance * (100 + current.prefix[i]); for (int k = i; k < j; ++k) { oldCost += 1LL * distMatrix[current.order[k]][current.order[k + 1]] * (100 + current.prefix[k]); } if (j + 1 < m) { oldCost += 1LL * distMatrix[current.order[j]][current.order[j + 1]] * (100 + current.prefix[j]); } int load = current.prefix[i]; for (int k = 0; k < (int)segment.size(); ++k) { int t = segment[k]; int d; if (k == 0) { d = (i == 0 ? startDist[t] : distMatrix[current.order[i - 1]][t]); } else { d = distMatrix[segment[k - 1]][t]; } newCost += 1LL * d * (100 + load); load += tasks[t].delta; if (load < 0) { newCost = (1LL << 60); break; } } if (newCost == (1LL << 60)) continue; if (j + 1 < m) { newCost += 1LL * distMatrix[segment.back()][current.order[j + 1]] * (100 + load); } long long delta = newCost - oldCost; bool accept = delta <= 0; if (!accept) { accept = uniform01(rng) < exp(-double(delta) / max(0.0001, temperature)); } if (!accept) continue; int newLoad = current.prefix[i]; for (int k = 0; k < (int)segment.size(); ++k) { int pos = i + k; current.order[pos] = segment[k]; newLoad += tasks[segment[k]].delta; current.prefix[pos] = newLoad; } current.cost += delta; if (current.cost < runBest.cost) { runBest = current; if (runBest.cost < globalBestCost) { globalBestCost = runBest.cost; globalBest = runBest.order; } } if ((iteration & 8191) == 8191 && current.cost > runBest.cost + 5000) { current = runBest; } } if (runBest.cost < globalBestCost) { globalBestCost = runBest.cost; globalBest = runBest.order; } return {runBest.order, runBest.cost}; } bool generatePartialPlan( double beta, int sourcePolicy, int automaticMode, bool verticalFirst, vector<Operation>& result, long long& resultCost ) const { vector<int> remaining(m); for (int i = 0; i < m; ++i) remaining[i] = tasks[i].delta; vector<Operation> operations; operations.reserve(20000); int x = 0, y = 0, load = 0; long long cost = 0; int remainingNonzero = m; auto nearestSinkDemand = [&](int source) { int best = INT_MAX; for (int t : sinkTasks) { if (remaining[t] >= 0) continue; int d = distMatrix[source][t]; if (d < best) best = d; } if (best == INT_MAX) return INT_MAX; for (int t : sinkTasks) { if (remaining[t] < 0 && distMatrix[source][t] == best) return -remaining[t]; } return INT_MAX; }; auto sourceAmount = [&](int t) { if (sourcePolicy == 0) return remaining[t]; int demand = nearestSinkDemand(t); if (demand == INT_MAX) return remaining[t]; return min(remaining[t], demand); }; auto processCell = [&](bool forced) { int t = cellTask[x][y]; if (t == -1 || remaining[t] == 0) return; if (remaining[t] > 0) { if (forced || (automaticMode & 1)) { int amount = sourceAmount(t); if (amount <= 0) return; remaining[t] -= amount; load += amount; cost += amount; operations.push_back({'+', amount}); --remainingNonzero; } } else { int amount = min(load, -remaining[t]); if (amount <= 0) return; if (forced || (automaticMode & 2)) { remaining[t] += amount; load -= amount; cost += amount; operations.push_back({'-', amount}); if (remaining[t] == 0) --remainingNonzero; } } }; for (int iteration = 0; iteration < 2500 && remainingNonzero > 0; ++iteration) { int target = -1; double bestScore = 1e100; for (int t = 0; t < m; ++t) { if (remaining[t] == 0) continue; int amount, resultLoad; if (remaining[t] > 0) { amount = sourceAmount(t); if (amount <= 0) continue; resultLoad = load + amount; } else { if (load == 0) continue; amount = min(load, -remaining[t]); resultLoad = load - amount; } int d = abs(x - tasks[t].x) + abs(y - tasks[t].y); double score = d * (100.0 + load) + beta * resultLoad; if (target == -1 || score < bestScore || (score == bestScore && (rng() & 1))) { bestScore = score; target = t; } } if (target == -1) return false; int tx = tasks[target].x; int ty = tasks[target].y; auto moveVertical = [&]() { while (x != tx) { if (x < tx) { ++x; operations.push_back({'D', 0}); } else { --x; operations.push_back({'U', 0}); } cost += 100 + load; processCell(false); } }; auto moveHorizontal = [&]() { while (y != ty) { if (y < ty) { ++y; operations.push_back({'R', 0}); } else { --y; operations.push_back({'L', 0}); } cost += 100 + load; processCell(false); } }; if (verticalFirst) { moveVertical(); moveHorizontal(); } else { moveHorizontal(); moveVertical(); } processCell(true); if (operations.size() > 100000) return false; } if (remainingNonzero != 0 || load != 0) return false; result = std::move(operations); resultCost = cost; return true; } vector<Operation> makeFullPlan(const vector<int>& order) const { vector<Operation> operations; operations.reserve(order.size() * 8); int x = 0, y = 0; for (int t : order) { while (x < tasks[t].x) { ++x; operations.push_back({'D', 0}); } while (x > tasks[t].x) { --x; operations.push_back({'U', 0}); } while (y < tasks[t].y) { ++y; operations.push_back({'R', 0}); } while (y > tasks[t].y) { --y; operations.push_back({'L', 0}); } if (tasks[t].delta > 0) operations.push_back({'+', tasks[t].delta}); else operations.push_back({'-', -tasks[t].delta}); } return operations; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<vector<int>> height(N, vector<int>(N)); for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) cin >> height[i][j]; Solver solver(N, std::move(height), 712367821ULL); if (solver.m == 0) return 0; vector<pair<vector<int>, long long>> candidates; auto addCandidate = [&](const vector<int>& order) { if ((int)order.size() != solver.m) return; long long cost = solver.routeCost(order); if (cost >= (1LL << 60)) return; candidates.push_back({order, cost}); }; const vector<double> betas = {0.0, 1.0, 2.0, 5.0, 10.0, 20.0}; const vector<double> jitters = {0.0, 50.0}; for (double beta : betas) { for (double jitter : jitters) { addCandidate(solver.greedyOrder(beta, jitter, false)); addCandidate(solver.greedyOrder(beta, jitter, true)); } } vector<int> allSources = solver.sourceTasks; vector<int> allSinks = solver.sinkTasks; vector<int> sourceFirst = solver.nearestOrder(allSources); vector<int> sinkPart = solver.nearestOrder(allSinks); sourceFirst.insert(sourceFirst.end(), sinkPart.begin(), sinkPart.end()); addCandidate(sourceFirst); addCandidate(solver.repairFeasible(solver.snakeOrder(true))); addCandidate(solver.repairFeasible(solver.snakeOrder(false))); vector<int> beam = solver.beamOrder(80); addCandidate(beam); sort(candidates.begin(), candidates.end(), [](const auto& a, const auto& b) { return a.second < b.second; }); for (int i = 0; i < min(4, (int)candidates.size()); ++i) { vector<int> extracted; for (int mode = 0; mode < 4; ++mode) { if (solver.realizeOrder( candidates[i].first, mode, mode == 1 || mode == 3, mode == 2 || mode == 3, extracted)) { addCandidate(extracted); } } } sort(candidates.begin(), candidates.end(), [](const auto& a, const auto& b) { return a.second < b.second; }); vector<int> globalBest = candidates.front().first; long long globalBestCost = candidates.front().second; vector<int> starts; for (int i = 0; i < min(4, (int)candidates.size()); ++i) starts.push_back(candidates[i].first); if (!beam.empty()) { bool exists = false; for (const auto& order : starts) if (order == beam) exists = true; if (!exists && starts.size() < 5) starts.push_back(beam); } for (const auto& order : starts) { solver.anneal(order, 80000, 1400.0, 2.0, globalBest, globalBestCost); } solver.anneal(globalBest, 180000, 600.0, 1.0, globalBest, globalBestCost); vector<int> extracted; for (int mode = 0; mode < 4; ++mode) { if (solver.realizeOrder( globalBest, mode, mode == 1 || mode == 3, mode == 2 || mode == 3, extracted)) { long long cost = solver.routeCost(extracted); if (cost < globalBestCost) { globalBestCost = cost; globalBest = extracted; } } } if (globalBestCost < (1LL << 60)) { solver.anneal(globalBest, 60000, 350.0, 1.0, globalBest, globalBestCost); } vector<Operation> fullOperations = solver.makeFullPlan(globalBest); long long fullCost = globalBestCost + solver.baseCost; vector<Operation> partialOperations; long long partialCost = (1LL << 60); const vector<double> partialBetas = {0.0, 0.7, 1.5, 3.0, 6.0, 10.0}; for (double beta : partialBetas) { for (int policy = 0; policy < 2; ++policy) { for (int automatic = 0; automatic < 4; ++automatic) { vector<Operation> operations; long long cost; if (solver.generatePartialPlan( beta, policy, automatic, (rng() & 1) != 0, operations, cost) && cost < partialCost) { partialCost = cost; partialOperations = std::move(operations); } } } } const vector<Operation>* answer = &fullOperations; if (partialCost < fullCost) answer = &partialOperations; string output; output.reserve(answer->size() * 10); for (const Operation& op : *answer) { if (op.type == '+' || op.type == '-') { output.push_back(op.type); output += to_string(op.amount); } else { output.push_back(op.type); } output.push_back('\n'); } cout << output; return 0; }