跳到正文

个人记录

01背包的多项式玄妙解法

hicode_002约 3 分钟
原文
文章信息与版本

文章信息

发布
2022年8月12日
收录
2026年8月12日
更新
2026年11月13日
篇幅
约 3 分钟
获赞
4

版本

  1. v1当前

显然01背包dp的复杂度是 O(nV)O(nV) 的

但是V最大可以是 2n2^n 级别的,因此可以证明还是NPH问题

但是我们可以使用一些近似算法,比如随机化。

使用模拟退火或其他通用随机化方法并不优秀,因为01背包可能有很多峰。

但是考虑部分背包问题可以贪心求解,而01背包贪心求解不一定正确,因为物品不可分割,导致贪心可能会导致对剩余放不下的空间的浪费。

但是如果我们可以肯定的是这个贪心解离真实解差距不会太大,因此我们考虑在按照部分背包基础上贪心的排序,然后随机的交换几个物品,然后再按贪心的方法计算价值,反复上述操作,并且取每一次操作中的最优值作为答案

这样的话#9过不去。(比标准答案小 33)

但是我们可以把原来的数组排序后存下来,打乱后复原时不用再排序而是直接赋值,这样可以减小复杂度。

然后我们减小随机化次数,但是增大每次随机化时交换的个数,以避免陷入局部最优解。

然后每一次交换后都要计算价值,因为每一次交换都会使得序列无序程度增加,每一次计算价值能够避免序列打的太乱,找不到最优解。

然后使用梅森随机数,并且不要用取模生成随机数,这样不均匀。

代码: 可能需要多交几次。

C++
#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cctype>
#include<cfloat>
#include<climits>
#include<iomanip>
#include<sstream>
#include<fstream>
#include<cstdlib>
#include<stack>
#include<queue>
#include<deque>
#include<map>
#include<set>
#include<vector>
#include<ctime>
#include<random>
using namespace std;
struct bag{
	int v,w;
	double i;
	inline void autoi(){
		scanf("%d%d",&v,&w);
		i=1.0*w/v;
	}

}a[3000];
bag bb[3000];
inline bool cmp(bag x ,bag y){
	return x.i >y.i ;
}
mt19937 rnd(time(0));
int maxx=-1;int n,v;
inline int work(bag b[],int n,int v){
	int totalv=v,totalw=0;
	for(int i=0;i<n;++i){
		totalv-=b[i].v;
		if(totalv<0)break;
		else totalw+=b[i].w;
	}
	return totalw;
}
inline void mr(bag b[],int n){
	uniform_int_distribution<long long> dist(0,n-1);
	
	for(int i=0;i<200;++i){
		swap(b[dist(rnd)],b[dist(rnd)]);
		int c=work(bb,n,v);
		if(c>maxx)maxx=c;
	}
}

int main(){
	
	
	scanf("%d%d",&v,&n);
	for(int i=0;i<n;++i){
		a[i].autoi();
	}
	sort(a,a+n,cmp);
	for(int i=0;i<90000;++i){
		for(int j=0;j<n;++j){
			bb[j]=a[j];
		}
		mr(bb,n);
	}
	printf("%d\n",maxx);
	
	//cout<<rand()<<" "<<rand()<<endl;
}