a556中等運算式區間的最大與最小值
CPE:Camel trading (UVa 10700)
枚舉最外層運算符號,涵蓋所有加括號方式。
解題思路
先把運算式切成數字陣列與運算符號陣列,多位數必須整段解析。對每個數字區間 [l,r] 保存 mn、mx;單一數字的兩值就是它本身。任意括號結構最後都會在某個運算符號 k 合併左右兩段,因此枚舉 k 就涵蓋所有結構。
所有數字皆為正,+ 與 * 對兩個參數都單調,所以該切點的最小值由兩側最小值結合,最大值由兩側最大值結合。區間由短到長填寫,最後取整段兩值。最多12個數字,三次方 DP 足夠;C++用64位元,完整保留 The maximum and minimum are X and Y. 的句型。
Step-by-step animation
示意:運算式 1+2*3
步驟 1 / 3
單點區間
三個數字的最小最大分別為自身。
1..1:1
2..2:2
3..3:3
- 長度
- 1
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
vector<long long> a;
vector<char> op;
long long value = 0;
for (char c : s) {
if (isdigit(static_cast<unsigned char>(c)))
value = value * 10 + c - '0';
else {
a.push_back(value);
value = 0;
op.push_back(c);
}
}
a.push_back(value);
int n = a.size();
vector<vector<long long>> mn(n, vector<long long>(n)), mx = mn;
for (int i = 0; i < n; ++i)
mn[i][i] = mx[i][i] = a[i];
for (int len = 2; len <= n; ++len)
for (int l = 0; l + len <= n; ++l) {
int r = l + len - 1;
mn[l][r] = numeric_limits<long long>::max();
for (int k = l; k < r; ++k) {
long long low =
op[k] == '+' ? mn[l][k] + mn[k + 1][r] : mn[l][k] * mn[k + 1][r];
long long high =
op[k] == '+' ? mx[l][k] + mx[k + 1][r] : mx[l][k] * mx[k + 1][r];
mn[l][r] = min(mn[l][r], low);
mx[l][r] = max(mx[l][r], high);
}
}
cout << "The maximum and minimum are " << mx[0][n - 1] << " and " << mn[0][n - 1] << ".\n";
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。