解題思路
將算式拆成數字陣列和運算子陣列。對每個區間同時記錄可得最小值與最大值,單一數字的兩者相同。
枚舉最後執行的運算子,把左右子區間的最小、最大端點兩兩運算,更新整區間的極值。加、減、乘在固定另一側時都是單調函數,因此矩形取值範圍的極值一定出現在端點組合;不必儲存所有結果。使用任意精度避免中間值溢位。
n個運算元需 O(n³) 次大整數運算、O(n²) 個大整數空間;位元成本隨中間值位數增加。
Step-by-step animation
教學示意(以步驟描述中的輸入為準)
步驟 1 / 3
示意6*3−9*3
中段3−9可為−6。
6
*
3
−
9
*
3
- 區間3−9
- −6
#include <bits/stdc++.h>
using namespace std;
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
int main() {
string s;
while (cin >> s) {
vector<cpp_int> a;
vector<char> op;
for (int i = 0; i < (int)s.size();) {
cpp_int x = 0;
while (i < (int)s.size() && isdigit(s[i]))
x = x * 10 + s[i++] - '0';
a.push_back(x);
if (i < (int)s.size())
op.push_back(s[i++]);
}
int n = a.size();
vector<vector<cpp_int>> lo(n, vector<cpp_int>(n)), hi = lo;
for (int i = 0; i < n; i++)
lo[i][i] = hi[i][i] = a[i];
for (int len = 2; len <= n; len++)
for (int l = 0; l + len <= n; l++) {
int r = l + len - 1;
bool first = true;
for (int k = l; k < r; k++)
for (cpp_int x : {lo[l][k], hi[l][k]})
for (cpp_int y : {lo[k + 1][r], hi[k + 1][r]}) {
cpp_int z;
if (op[k] == '+')
z = x + y;
else if (op[k] == '-')
z = x - y;
else
z = x * y;
if (first || z < lo[l][r])
lo[l][r] = z;
if (first || z > hi[l][r])
hi[l][r] = z;
first = false;
}
}
cout << hi[0][n - 1] << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。