CSU - 1547 Rectangle —— DP(01背包)

时间:2021-02-11 04:44:13

题目链接:http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1547

题解:

关键是怎么处理长度为1的长方形。当长度为1的长方形的个数cnt>=2时,怎么把这些长方形分成两组,使得这两组的高度差最小,即最接近H/2。一开始用贪心做,结果wa了。因为贪心出来的不一定是最优,于是就想到了用dp。dp出H/2最大能够容纳的高度。然后再取 H-dp[H/2]。

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <sstream>
#include <algorithm>
using namespace std;
#define pb push_back
#define mp make_pair
#define ms(a, b) memset((a), (b), sizeof(a))
//#define LOCAL
#define eps 0.0000001
#define LNF (1<<60)
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int maxn = 100000+10;
const int mod = 1e9+7; int main()
{
#ifdef LOCAL
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif // LOCAL int t,n;
int a[105],dp[10005];
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int val,ty;
int ans = 0, cnt = 0, H = 0;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&ty,&val);
if(ty==1) H += val, a[++cnt] = val;
else ans += val;
}
memset(dp,0,sizeof(dp)); if(cnt==1)
ans += a[1]; else if(cnt>1)
{
for(int i = 1; i<=cnt; i++)
for(int j = H/2; j>0; j--)
if(j>=a[i])
dp[j] = max(dp[j],dp[j-a[i]]+a[i]); ans += H-dp[H/2];
}
printf("%d\n", ans);
}
return 0;
}