解題思路
找出唯一符合提示位元的門上原數列。
對M+1個原數a,最右提示為a[M]≥a[M−1]。其餘提示位置j為abs(a[j+2]−a[j+1])≥a[j],j從0至M−2。
每個提示只依賴原數,不使用其他提示或前一步差值,因此可逐位置直接計算並比較。
所有M個位元相同的那行就是唯一答案;使用任意精度整數比較,最後保留該行數值順序。
時間 O(NM)次大整數減法比較,額外空間 O(M)個大整數;Python逐行讀取。
Step-by-step animation
題目原數列27 13 45 57 30的提示計算
步驟 1 / 3
步驟 1
原列27、13、45、57、30。
27
13
45
57
30
- 步驟
- 1
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
int main() {
int n, m;
cin >> n >> m;
vector<int> p(m);
for (int &x : p)
cin >> x;
while (n--) {
vector<cpp_int> a(m + 1);
for (auto &x : a)
cin >> x;
bool ok = (a[m] >= a[m - 1]) == p[m - 1];
for (int j = 0; j < m - 1; j++) {
cpp_int d = a[j + 2] - a[j + 1];
if (d < 0)
d = -d;
ok = ok && ((d >= a[j]) == p[j]);
}
if (ok) {
for (int j = 0; j <= m; j++)
cout << (j ? " " : "") << a[j];
cout << '\n';
}
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。