2021杭電多校賽第三場
阿新 • • 發佈:2021-08-05
Rise in Price
因為題目保證資料隨機,根據官方題解所說,我們只需要維護當前狀態最大的前幾個狀態,最終答案大概率就在這些狀態中,我們每次儲存從上次狀態轉移來的前\(100\)個最大狀態,不斷進行維護即可。
#include <bits/stdc++.h> using namespace std; #define int long long const int MAXN = 1e2 + 5; typedef pair<int, int> PII; vector<PII> dp[MAXN][MAXN]; // pair儲存每個狀態的鑽石個數和單價 int a[MAXN][MAXN], b[MAXN][MAXN]; int calc(PII p) { return p.first * p.second; } void solve(int x, int y, vector<PII> &X, vector<PII> &Y, vector<PII> &Z) { int i = 0, j = 0; while ((i < X.size() || j < Y.size()) && Z.size() < 100) { if (i < X.size() && j < Y.size()) { Z.push_back(calc(X[i]) > calc(Y[j]) ? X[i++] : Y[j++]); } else if (i < X.size()) { Z.push_back(X[i++]); } else if (j < Y.size()) { Z.push_back(Y[j++]); } } for (auto &it: Z) { it.first += a[x][y]; it.second += b[x][y]; } } bool cmp(PII lhs, PII rhs) { return lhs.first * lhs.second > rhs.first * rhs.second; } signed main(int argc, char *argv[]) { ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); int T; cin >> T; while (T--) { int n; cin >> n; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { cin >> a[i][j]; dp[i][j].clear(); // 多組資料記得初始化 } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { cin >> b[i][j]; } } dp[1][1].push_back({a[1][1], b[1][1]}); for (int i = 2; i <= n; ++i) { // 預處理第一行 auto it = dp[1][i - 1][0]; dp[1][i].push_back({it.first + a[1][i], it.second + b[1][i]}); } for (int i = 2; i <= n; ++i) { // 預處理第一列 auto it = dp[i - 1][1][0]; dp[i][1].push_back({it.first + a[i][1], it.second + b[i][1]}); } for (int i = 2; i <= n; ++i) { for (int j = 2; j <= n; ++j) { solve(i, j, dp[i - 1][j], dp[i][j - 1], dp[i][j]); sort(dp[i][j].begin(), dp[i][j].end(), cmp); } } int res = 0; for (auto it: dp[n][n]) { res = max(res, it.first * it.second); } cout << res << '\n'; } system("pause"); return 0; }