CSU - 1547 Rectangle —— DP(01背包)
2024-08-23 22:06:09
题目链接: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;
}
最新文章
- Git中三种文件状态及其转换
- Qt qmake 使用(含遗留问题)
- sort函数用法
- RSA非对称加密
- Android --ListView分页
- WebApi调试中遇到的一些问题
- 安装Ambari
- struct和typedef struct的用法
- 悼念传奇,约翰询问&;#183;纳什和他的妻子艾丽西亚致敬,创建一个传奇,爱数学
- git config and options core.bare hard
- Hadoop: LongWritable cannot be cast to org.apache.hadoop.io.IntWritable
- 【Python3之socket编程】
- F和弦大横按
- TIME_WAIT
- 事件委托在ios下面失效
- C#深入理解AutoResetEvent和ManualResetEvent
- go语言使用go-sciter创建桌面应用(四) 固定窗口大小
- Linux--安全加固01
- 查看压缩包内容tar -tf
- caffe 学习记录1及网络结构
热门文章
- OS | Process
- luogu P2066 机器分配
- ios构造和析构
- iOS -- xxxViewController进行pop时直接crash进main.m,EXC_BAD_ACCESS(code=1,address=0x20)
- iOS开发 ----- 加载动画之牛顿摆的实现
- 百科知识 epub文件如何打开
- POJ 3978(求素数)
- VC++ ADO 连接 mysql
- 配置Office Outlook 2013
- Java集合01----ArrayList的遍历方式及应用