【UVA 437】The Tower of Babylon(记忆化搜索写法)

【题目链接】:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=378

【题意】

给你n个方形;
由3个属性,长宽高决定;
你可以任意摆放这个方形(即把哪一面朝下方);
然后每种方形都有无限个;
一个方形能够摆在另外一个方形上面,当且仅当这个方形的长和宽都严格大于另外一个方形的长和宽(即changi>changj && kuani>kuanj);
问你这n个方形最多能叠多高;

【题解】

把每个方形的3种摆法都取出来;
(即取3个属性中的某一个属性出来作为高,另外两个作为宽和长);
然后如果某一个方形x可以放到另外一个方形y的上面;
则连一条有向边x指向y;
然后问题就能转化为一个有向无环图上的最长路了;
起点不一定
也即一条最长链
写个记忆化搜索就好;
f[x]=max(f[x],f[y]+h[x]),(x,y)Eh[x]x

【Number Of WA

1

【反思】

忘记初始化+忘记输出Case

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)
#define Open() freopen("D:\rush.txt","r",stdin)
#define Close() ios::sync_with_stdio(0)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 30;

struct abc{
    LL c,k,g;
};

int n,b[4],nn;
LL dp[N*3+100];
abc a[N*3+100];
vector <int> G[N*3+100];

LL dfs(int x){
    if (dp[x]!=-1) return dp[x];
    LL &ans = dp[x];
    ans = a[x].g;
    int len = G[x].size();
    rep1(i,0,len-1){
        int y = G[x][i];
        ans = max(ans,dfs(y) + a[x].g);
    }
    return dp[x];
}

int main()
{
    //Open();
    int kk = 0;
    while (~scanf("%d",&n) && n){
        kk++;
        ms(dp,-1);
        nn = 0;
        rep1(i,1,N*3) G[i].clear();
        rep1(i,1,n){
            rep1(j,1,3)
                scanf("%d",&b[j]);
            sort(b+1,b+1+3);
            rep1(j,1,3){
                nn++;
                rep2(k,3,1)
                    if (k!=j){
                        a[nn].c = b[k];
                        break;
                    }
                rep1(k,1,3)
                    if (k!=j){
                        a[nn].k = b[k];
                        break;
                    }
                a[nn].g = b[j];
            }
        }
        n = nn;
        rep1(i,1,n)
            rep1(j,1,n)
                if (a[i].c > a[j].c && a[i].k > a[j].k)
                    G[i].pb(j);
        LL d = 0;
        rep1(i,1,n)
            d = max(d,dfs(i));
        printf("Case %d: maximum height = ",kk);
        printf("%lld
",d);
    }
    return 0;
}

原文地址:https://www.cnblogs.com/AWCXV/p/7626212.html