完全背包和多重背包的混合 F - The Fewest Coins
2024-10-09 01:44:31
http://poj.org/problem?id=3260
这个题目有点小难,我开始没什么头绪,感觉很乱。
后来看了题解,感觉豁然开朗。
题目大意:就是这个人去买东西,东西的价格是T,这个人拥有的纸币和数量。让你求这个人买东西的纸币量加上老板找给他的纸币量最少是多少。
这个老板用于这个人拥有的纸币种类,数量是无限。
思路:
思路就是这个人看成多重背包,老板看成完全背包,f1[i] 表示这个人花了 i 的钱用的最少的纸币。f2[i] 表示老板凑出 i 的钱用的最少的纸币。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <vector>
#include <algorithm>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 2e5 + ;
int N, V;
int weight[maxn], num[maxn];
int f1[maxn], f2[maxn], V1;
void zeroonepack(int weight, int val, int f[]) {
for (int i = V; i >= weight; i--) {
f[i] = min(f[i], f[i - weight] + val);
}
} void completepack(int weight, int val, int f[]) {
for (int i = weight; i <= V; i++) {
f[i] = min(f[i], f[i - weight] + val);
}
} void multiplepack(int weight, int val, int count, int f[]) {
if (count*weight >= V) completepack(weight, val, f);
else {
int t = ;
while (t < count) {
zeroonepack(weight*t, val*t, f);
count -= t;
t *= ;
}
zeroonepack(count*weight, count*val, f);
}
} int main() {
while (scanf("%d%d", &N, &V1) != EOF) {
int max_val = ;
for (int i = ; i <= N; i++) {
scanf("%d", &weight[i]);
max_val = max(max_val, weight[i]);
}
for (int i = ; i <= N; i++) scanf("%d", &num[i]);
V = max_val * max_val + V1 + ;
memset(f1, inf, sizeof(f1));
memset(f2, inf, sizeof(f2));
f1[] = , f2[] = ;
for (int i = ; i <= N; i++) {
multiplepack(weight[i], , num[i], f1);//顾客
}
for (int i = ; i <= N; i++) {
completepack(weight[i], , f2);
}
//printf("v=%d v1=%d\n", V, V1);
int ans = inf;
for (int i = ; i <= V - V1; i++) {
if (f1[V1 + i] != inf && f2[i] != inf) {
ans = min(f1[V1 + i] + f2[i], ans);
}
}
if (ans != inf) printf("%d\n", ans);
else printf("-1\n");
}
return ;
}
最新文章
- easycwmp的编译
- numberOfRowsInSection方法什么时候调用
- 对象的比较与排序:IComparable和IComparer接口
- class文件概述
- [转]C++11 多线程
- arcgis desktop按ctrl键后地图乱移的解决办法
- 如何自适应网页的协议(http/https/……)
- Hadoop入门实践之从WordCount程序说起
- Google protobuf安装
- Spring中Bean实例的生命周期及其行为
- 用Jquery 仿VS 样式的 导航栏插件
- 动态规划(斜率优化):BZOJ 3675 [Apio2014]序列分割
- Linux常用的系统监控shell脚本
- Quartz.NET学习系列
- AngularJS -- Bootstrap(启动器)
- css盒子居中定位问题
- Xamarin Essentials教程获取路径文件系统FileSystem
- odp.net连接方式,部署问题总结
- Python中操作HTTP请求的urllib模块详解
- multi-threads JavaEE 容器