算法竞赛入门经典第九章例题9-2 uva 437 巴比伦塔

题意:给n种砖块,每种可以随便用几次,每块有长宽高,要求把它们磊起来,求放在上面的砖块的长宽严格小于下面的砖块。

思路:考虑用dp 紫书上往前翻几页有详细的解法,DAG上的最长路问题,我用了n^2的记忆化搜索,以前用先排序再dp好像可以达到O(n)的效率。


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define maxn 1100
using namespace std;
int blocks[maxn][3];
int dp[maxn][3];
int cas = 1,n;
int dfs(int i,int j,int now_h,int now_w)
{
    int &ans = dp[i][j];
    if(ans > 0) return ans;
    ans = 0;
    for(int t = 0;t< n;t++){
        for(int k=0;k<3;k++){
            int h,w;
            if(k == 0) h = blocks[t][1],w =blocks[t][2];
            else if(k == 1) h = blocks[t][0],w =blocks[t][2];
            else h = blocks[t][0],w =blocks[t][1];

            if(h < now_h && w <now_w)
                ans = max(ans,dfs(t,k,h,w));
        }
    }
    ans+=blocks[i][j];
    return ans;

}

int main()
{

    while(~scanf("%d",&n) && n){
        memset(dp,0,sizeof dp);
        for(int i =0;i<n;i++){
            scanf("%d%d%d",&blocks[i][0],&blocks[i][1],&blocks[i][2]);
            sort(blocks[i],blocks[i]+3);
        }
        int ans = 0;
        for(int i = 0;i<n;i++){
            for(int j=0;j<3;j++){
                int h,w;
                if(j == 0) h = blocks[i][1],w =blocks[i][2];
                else if(j == 1) h = blocks[i][0],w =blocks[i][2];
                else h = blocks[i][0],w =blocks[i][1];
                
                ans=max(ans,dfs(i,j,h,w));
            }

        }
        printf("Case %d: maximum height = %d\n",cas++,ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值