观察样例一,不难发现只有 时构造才是正确的。
考虑对于一个构造好的棋盘写 是很容易的,这可以在 的时间解决。路径最大值仅需枚举向下走的那一列即可。然后实际最大值就是白走后路径分开的左下部分和右上部分的最大值。
然后考虑随机化,将 -1 的位置填入随机值。如果直接在 至 间随机化,对于样例一这种根本过不了。所以令原棋盘最大值为 ,则只在 至 间随机化,然后实测就有大概 的概率 AC。主要是第 20 个点有点悬。
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 200005;
int n;
int a[2][MAXN];
bool fixed_cell[2][MAXN];
vector<pair<int,int>> mutable_pos;
// 检查当前棋盘是否满足要求
bool check() {
// 前缀和(1‑indexed)
vector<long long> pre1(n + 1, 0), pre2(n + 1, 0);
for (int i = 1; i <= n; ++i) {
pre1[i] = pre1[i - 1] + a[0][i - 1];
pre2[i] = pre2[i - 1] + a[1][i - 1];
}
// D[k] = sum_{1..k} a1 - sum_{1..k-1} a2
vector<long long> D(n + 1);
long long maxD = -1e18;
for (int k = 1; k <= n; ++k) {
D[k] = pre1[k] - pre2[k - 1];
if (D[k] > maxD) maxD = D[k];
}
// 最大 D 必须唯一
int best_k = -1, cnt = 0;
for (int k = 1; k <= n; ++k) {
if (D[k] == maxD) {
++cnt;
best_k = k;
}
}
if (cnt != 1) return false;
// 计算空对不同 k 的最大收益 V(k)
long long minV = 1e18;
for (int k = 1; k <= n; ++k) {
long long left = (k - 1 >= 1) ? pre2[k - 1] : 0;
long long right = (k + 1 <= n) ? (pre1[n] - pre1[k]) : 0;
long long Vk = max(left, right);
if (Vk < minV) minV = Vk;
}
// 最优 k* 对应的空收益
long long Vstar = max(
(best_k - 1 >= 1) ? pre2[best_k - 1] : 0,
(best_k + 1 <= n) ? (pre1[n] - pre1[best_k]) : 0
);
// 存在另一个 k 使得空收益更小
return Vstar > minV;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
int maxn = 2;
for (int i = 0; i < 2; ++i)
for (int j = 0; j < n; ++j) {
cin >> a[i][j];
maxn = max(maxn, a[i][j]);
if (a[i][j] == -1) {
fixed_cell[i][j] = false;
mutable_pos.emplace_back(i, j);
} else {
fixed_cell[i][j] = true;
}
}
// n = 1 时只有一条路径,不可能满足条件
if (n == 1) {
cout << -1 << '\n';
return 0;
}
// 没有可修改格子,直接检查原棋盘
if (mutable_pos.empty()) {
if (check()) {
for (int i = 0; i < 2; ++i)
for (int j = 0; j < n; ++j)
cout << a[i][j] << " \n"[j == n - 1];
} else {
cout << -1 << '\n';
}
return 0;
}
// 随机填充尝试
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
uniform_int_distribution<int> val_dist(1, min(maxn, 1000000000)); // 直接使用 [1, 1e9]
auto start_time = chrono::steady_clock::now();
while (1) {
// 超时保护
auto now = chrono::steady_clock::now();
if (chrono::duration<double>(now - start_time).count() > 0.95) break;
for (auto &p : mutable_pos)
a[p.first][p.second] = val_dist(rng);
if (check()) {
for (int i = 0; i < 2; ++i)
for (int j = 0; j < n; ++j)
cout << a[i][j] << " \n"[j == n - 1];
return 0;
}
}
cout << -1 << '\n';
return 0;
}链接。代码由 AI 编写完成。