codeup26704_装载问题

codeup26704_装载问题

时空限制    1000ms/128MB

题目描述

    有一批共n个集装箱要装上艘载重量为c的轮船,其中集装箱i的重量为wi。找出一种最优装载方案,将轮船尽可能装满,即在装载体积不受限制的情况下,将尽可能重的集装箱装上轮船。

输入格式

    由文件load.in给出输入数据。第一行有2个正整数n和c。n是集装箱数,c是轮船的载重量。接下来的1行中有n个正整数,表示集装箱的重量。

输出格式

    将计算出的最大装载重量输出到文件load.out。

输入样例

5 10

7 2 6 5 4

输出样例

 10

代码

#include<iostream>
#include<cstdlib>
using namespace std;
const int N = 10005;
int n,c,w[N],sum,ans;
bool used[N];

void search(int i,int tot){
	if (i>n) return;	//搜索完
	if (tot>c) return;	//搜索和大于轮船载重量
	if (tot==c) { cout<<c<<endl; exit(0); }	//搜索和等于轮船载重量
	if (tot>ans) ans=tot;	//搜索和小于轮船载重量,先存搜索和,再继续搜索
	for (int j=i; j<=n; j++)
		if (!used[j]){
			used[j] = true;
			search(i+1,tot+w[j]);
			used[j] = false;
		}
}

int main(){
	cin>>n>>c;
	for (int i=1; i<=n; i++){
		cin>>w[i];
		sum+=w[i];
	}
	if (sum<=c) ans=sum;
	else search(1,0);
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/WDAJSNHC/article/details/81302197