DAG上的DP
DAG是有向无环图
而DAG的dp主要是利用一些问题的二元关系构造DAG图建模,转化成在图上求最长/短路的问题
https://www.luogu.com.cn/problem/UVA437
Code
点击查看代码
#include <bits/stdc++.h>
using namespace std;
// typedef long long ll;
#define int long long
typedef unsigned long long ull;
#define rep(i, a, n) for (int i = a; i <= n; i++)
#define req(i, n, a) for (int i = n; i >= a; i--)
typedef pair<int, int> pa;
int mod = 998244353;
const int MAXN = 0x3f3f3f3f;
const int maxn = 2e5 + 10;
int n, x[40], y[40], z[40];
int dp[40][4];
//dp[i][j]是在以第i个砖为底,j式的所能堆塔的最大高度
int dfs(int k, int f) {
//dp最大的dp[k][f]
if (dp[k][f]) return dp[k][f];
int data1, data2;
if (f == 1) data1 = y[k], data2 = z[k];
if (f == 2) data1 = x[k], data2 = z[k];
if (f == 3) data1 = x[k], data2 = y[k];
for (int i = 1; i <= n; i++) {
if ((data1 > y[i] && data2 > z[i]) || (data2 > y[i] && data1 > z[i])) {
dp[k][f] = max(dp[k][f], dfs(i, 1) + x[i]);
}
if ((data1 > x[i] && data2 > z[i]) || (data2 > x[i] && data1 > z[i])) {
dp[k][f] = max(dp[k][f], dfs(i, 2) + y[i]);
}
if ((data1 > x[i] && data2 > y[i]) || (data2 > x[i] && data1 > y[i])) {
dp[k][f] = max(dp[k][f], dfs(i, 3) + z[i]);
}
}
return dp[k][f];
}
void solve() {
int cnt = 0;
while (++cnt) {
cin >> n;
if (!n) break;
for (int i = 1; i <= n; i++) {
cin >> x[i] >> y[i] >> z[i];
}
int high = 0;
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; i++) {
high = max(high, dfs(i, 1) + x[i]);
high = max(high, dfs(i, 2) + y[i]);
high = max(high, dfs(i, 3) + z[i]);
}
cout << "Case " << cnt << ": maximum height = " << high << '\n';
}
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int TT = 1;
// cin >> T;
while (TT--) {
solve();
}
#ifdef local
std::cout << endl, system("pause");
#endif
return 0;
}
// cout << fixed << setprecision(2) <<
// priority_queue<pa, vector<pa>, greater<pa>>qx;
// priority_queue<int, vector<int>, less<int>>qd;
// struct node {
// int id, f;
// bool operator<(const node& x) const { return id > x.id; }
// };priority_queue<node> q;