题意
有n种长方体,每种有无线个。要求选一些长方体摞成一个尽可能高的柱子,每个长方体底面的长宽严格小于它下方长方体底面的长和宽。
题解
这是一道DAG上的动态规划。如何分析题目,将其转化为DAG上的动态规划是该题的关键。但是,我不是很清楚具体的思维过程是什么。
其次,动态规划的关键是状态转移方程。代码如何实现要根据转态转移方程写。
AC代码
1.记忆化搜索
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 300;
const int INF = 0x3f3f3f3f;
struct pii{
int x,y,h;
pii(int x = 0, int y = 0, int h = 0):x(x), y(y), h(h){}
bool operator < (const pii rsh)const{
return (x<rsh.x && y<rsh.y) ||
(y<rsh.x && x<rsh.y);
}
};
bool G[maxn][maxn];
bool vis[maxn];
int dp[maxn];
int n;
vector<pii> ve;
int solve(int i){
if(vis[i]) return dp[i];
vis[i] = true;
dp[i] = ve[i].h;
for(int j = 0; j < 3*n; j++)
if(G[i][j]) dp[i] = max(dp[i], solve(j) + ve[i].h);
return dp[i];
}
int main(){
int kase = 0;
while(scanf("%d", &n) != EOF && n){
ve.clear();
int a, b, c;
for(int i = 0; i<n; i++){
scanf("%d%d%d", &a, &b, &c);
ve.push_back(pii(a,b,c));
ve.push_back(pii(b,c,a));
ve.push_back(pii(c,a,b));
}
memset(G, false, sizeof(G));
for(int i = 0, k = 3*n; i < k; i++){
for(int j = 0; j < k; j++){
if(ve[j] < ve[i]) G[i][j] = true;
}
}
memset(vis, false, sizeof(vis));
int mx = 0;
for(int i = 0; i<3*n; i++){
solve(i);
if(dp[i]>mx) mx = dp[i];
}
printf("Case %d: maximum height = %d\n", ++kase, mx);
}
}
2.递推
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 300;
const int INF = 0x3f3f3f3f;
struct pii{
int x,y,h;
pii(int x = 0, int y = 0, int h = 0):x(x), y(y), h(h){}
bool operator < (const pii rsh)const{
return (x<rsh.x && y<rsh.y) ||
(y<rsh.x && x<rsh.y);
}
};
bool G[maxn][maxn];
bool vis[maxn];
int dp[maxn];
int n;
vector<pii> ve;
int c[maxn];
int topo[maxn], t;
bool dfs(int u)
{
c[u] = -1; // 访问标志
for(int v = 0; v < 3*n; v++) if(G[v][u])
{
if(c[v] < 0) return false; // 存在环
else if(!c[v] && !dfs(v)) return false;
}
c[u] = 1;
topo[--t] = u;
return true;
}
bool toposort()
{
t = 3*n;
memset(c, 0, sizeof(c));
for(int u = 0; u < 3*n; u++) if(!c[u])
if(!dfs(u)) return false;
return true;
}
int main(){
int kase = 0;
while(scanf("%d", &n) != EOF && n){
ve.clear();
int a, b, c;
for(int i = 0; i<n; i++){
scanf("%d%d%d", &a, &b, &c);
ve.push_back(pii(a,b,c));
ve.push_back(pii(b,c,a));
ve.push_back(pii(c,a,b));
}
memset(G, false, sizeof(G));
for(int i = 0, k = 3*n; i < k; i++){
for(int j = 0; j < k; j++){
if(ve[j] < ve[i]) G[i][j] = true;
}
}
toposort();
int mx = 0;
for(int i = 0; i<3*n; i++){
dp[topo[i]] = ve[topo[i]].h;
for(int j = 0; j<3*n; j++)if(G[topo[i]][j])
dp[topo[i]] = max(dp[topo[i]], dp[j] + ve[topo[i]].h);
if(dp[topo[i]] > mx) mx = dp[topo[i]];
}
printf("Case %d: maximum height = %d\n", ++kase, mx);
}
}
本文探讨了一道经典的动态规划问题——长方体堆叠。目标是选择一系列长方体来构建最高的柱子,其中每个长方体的底面尺寸必须严格小于其下一层长方体的尺寸。通过构建有向无环图(DAG)并应用动态规划解决此问题,提供了两种实现方法:记忆化搜索和递推。
362

被折叠的 条评论
为什么被折叠?



