P2370 yyy2015c01 的 U 盘 (dp,01背包,二分,排序)

博客内容讲述了如何在限制容量s的情况下,根据物品的重量w和价值v,选择能装下最多价值的物品,同时使得接口尽可能小。通过先对物品重量进行排序,然后使用二分法来确定最佳选择,以达到目标价值p的同时,接口最小化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

Sloution

在容量s的情况下,装下尽量多的v,(这个v的条件,是其w要小于接口),达到p的情况下,接口尽可能小。

不难发现,v越小,接口越小,所以可以二分

但是,其实,可以先排序,对w,用w从小到大去考虑,
再去考虑当前f[s]是否到p (我没有想到)

二分:

#include <iostream>
#include <cstring>
#include <vector>
#include <map>
#include <string>
#include <deque>
#include<algorithm>
#include<cmath>
#define ll long long
#define PII pair<int, int>
#define _for(i, a, b) for (int i = a; i < b; i++)
#define for_(i, b, a) for (int i = b; i >= a; i--)
#define ms(a,b) memset(a, b, sizeof a)
#define gcd(a, b) __gcd(a, b)
#define lcm(a, b) a / gcd(a, b) * b
using namespace std;

const int N = 1100;
int w[N], v[N];//大小,价值

int f[N];

int n, p, s;//希望最小价值 p,硬盘大小s

bool check(int x){
	ms(f, 0);
	_for(i,0,n){
		if(w[i]<=x)
		for_(j, s, w[i])
			f[j] = max(f[j], f[j - w[i]] + v[i]);
	}

	if(f[s]<p)
		return 0;
	else
		return 1;
}

int main()
{//freopen("in.txt", "r", stdin);
	cin >> n >> p >> s;
	_for(i, 0, n) cin >> w[i] >> v[i];

	_for(i,0,n){  
		for_(j, s, w[i])
			f[j] = max(f[j], f[j - w[i]] + v[i]);
	}
	//cout << f[s];
	if(f[s]<p){
		cout << "No Solution!";
		return 0;
	}

	int l = 0, r = 1e6 + 10;

	while(l<r){
		int mid = (l + r) >> 1;
		if(check(mid))
			r = mid;
		else
			l = mid + 1;
	}

	cout << l;
}

先排序:

也很好想
在考虑第i个物品的时候
f[s]表示前i个物品的最大价值
若 前 i-1 不满足,前 i个满足
那么说明,装了 i 之后,达到 p的要求
这时候的 接口最小

#include <iostream>
#include <cstring>
#include <vector>
#include <map>
#include <string>
#include <deque>
#include<algorithm>
#include<cmath>
#include<unordered_map>
#include<queue>
#define ll long long
#define PII pair<int, int>
#define _for(i, a, b) for (int i = a; i < b; i++)
#define for_(i, b, a) for (int i = b; i >= a; i--)
#define ms(a,b) memset(a, b, sizeof a)
#define gcd(a, b) __gcd(a, b)
#define lcm(a, b) a / gcd(a, b) * b
using namespace std;

int n, p, s;//文件总数,希望最小价值 p ,硬盘大小

PII wu[1100];

int f[1100];

int main(){
//freopen("in.txt", "r", stdin);
    cin >> n >> p >> s;

    _for(i, 0, n) cin >> wu[i].first >> wu[i].second;
    sort(wu, wu + n);
   
    int ff = 1;
    _for(i,0,n){
        for_(j, s, wu[i].first)
            f[j] = max(f[j], f[j - wu[i].first] + wu[i].second);

        if(f[s]>=p){
           ff = 0;
           cout << wu[i].first<<endl;
           break;
        }    
    }

    if(ff)
        cout << "No Solution!";
}
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值