LA 3637 - The Bookcase(DP)

题目链接:点击打开链接

思路:用d[i][j][k]表示前i个, 已经占据了第一层j厚度,第二层k厚度的最小高度。 转移即可。 这题卡常数挺恶心的, 要加点恶心的优化。

细节参见代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <bitset>
#include <cstdlib>
#include <cmath>
#include <set>
#include <list>
#include <deque>
#include <map>
#include <queue>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
typedef long double ld;
const double eps = 1e-6;
const double PI = acos(-1);
const int mod = 1000000000 + 7;
const int INF = 0x3f3f3f3f;
// & 0x7FFFFFFF
const int seed = 131;
const ll INF64 = ll(1e18);
const int maxn = 77;
int T,n,m,d[maxn][maxn*30][maxn*30],sum[maxn];
struct node {
    int h, w;
    bool operator < (const node& rhs) const {
        return h > rhs.h;
    }
}a[maxn];
int main() {
    scanf("%d",&T);
    while(T--) {
        scanf("%d",&n);
        int maxw = 0;
        for(int i = 1; i <= n; i++) {
            scanf("%d%d", &a[i].h, &a[i].w);
            maxw += a[i].w;
        }
        sort(a+1, a+n+1);
        for(int i = 1; i <= n; i++) {
            sum[i] = sum[i-1] + a[i].w;
        }
        for(int i = 0; i <= n; i++) {
            for(int j = 0; j <= maxw/2; j++) {
                for(int k = 0; k <= maxw/2; k++) d[i][j][k] = INF;
            }
        }
        d[0][0][0] = 0;
        for(int i = 0; i < n; i++) {
            for(int j = 0; j <= maxw/2; j++) {
                for(int k = 0; k <= maxw/2; k++) {
                    int& ans = d[i][j][k];
                    if(ans == INF) continue;
                    if(j == 0) d[i+1][j+a[i+1].w][k] = min(d[i+1][j+a[i+1].w][k], ans + a[i+1].h);
                    else d[i+1][j+a[i+1].w][k] = min(d[i+1][j+a[i+1].w][k], ans);

                    if(k == 0) d[i+1][j][k+a[i+1].w] = min(d[i+1][j][k+a[i+1].w], ans + a[i+1].h);
                    else d[i+1][j][k+a[i+1].w] = min(d[i+1][j][k+a[i+1].w], ans);

                    if(j + k == sum[i]) d[i+1][j][k] = min(d[i+1][j][k], ans + a[i+1].h);
                    else d[i+1][j][k] = min(d[i+1][j][k], ans);

                }
            }
        }
        int ans = INF;
        for(int i = 1; i <= maxw/2; i++) {
            for(int j = 1; j <= maxw/2; j++) {
                int h = d[n][i][j];
                int w = max(i, max(j, maxw - i - j));
                if(maxw - i - j == 0) continue;
                if(d[n][i][j] >= INF) continue;
                ans = min(ans, h*w);
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}


你可能感兴趣的:(dp,ACM-ICPC,la)