The Bookcase UVA

来源:互联网 发布:网络推手联系方式 编辑:程序博客网 时间:2024/06/05 08:06

动态规划的一道题目,按照紫书的思路,先将书按照高度进行排序,然后依次向各层放置,进行相应的更新,并且进行计算得出最后的结果即可,具体实现见如下代码:

#include<iostream>#include<vector>#include<string>#include<set>#include<stack>#include<queue>#include<map>#include<algorithm>#include<cmath>#include<iomanip>#include<cstring>#include<sstream>#include<cstdio>#include<deque>using namespace std;int Case;int N;struct Book{int h, w;};bool compare(const Book a, const Book b){if (a.h != b.h) return a.h > b.h;return a.w > b.w;}int dp[2][2110][2110];vector<Book> record;int width[100];void update(int &l, int r){if (l<0 || l>r) l = r;}int getHeight(int ind,int h){if (ind != 0) return 0;return h;}int main(){cin >> Case;while (Case--){record.clear();cin >> N;for (int i = 0; i < N; i++){Book book;cin >> book.h >> book.w;record.push_back(book);}sort(record.begin(), record.end(), compare);width[0] = 0;for (int i = 1; i <= N; i++){width[i] = width[i - 1] + record[i - 1].w;}int ind = 0;memset(dp, -1, sizeof(dp));dp[0][0][0] = 0;for (int i = 0; i < N; i++){for (int j = 0; j <= width[i + 1]; j++){for (int k = 0; k <= width[i + 1] - j; k++){dp[ind ^ 1][j][k] = -1;//第二层宽度为j,第三层宽度为k,第二层和第三层的高度之和}}for (int j = 0; j <= width[i + 1]; j++){for (int k = 0; k <= width[i + 1] - j; k++){if (dp[ind][j][k] >= 0){update(dp[ind ^ 1][j][k], dp[ind][j][k]);//firstupdate(dp[ind^1][j+record[i].w][k],dp[ind][j][k]+getHeight(j,record[i].h));//secondupdate(dp[ind ^ 1][j][k + record[i].w], dp[ind][j][k] + getHeight(k, record[i].h));}}}ind = ind ^ 1;}int ans = 1 << 30;for (int j = 1; j <= width[N]; j++){for (int k = 1; k <= width[N] - j; k++){if (dp[ind][j][k] >= 0){int w = max(max(j, k), width[N] - j - k);int h = record[0].h + dp[ind][j][k];ans = min(ans, w*h);}}}cout << ans << endl;}return 0;}

原创粉丝点击