集装箱装载(贪心)

手动实现的快排,时间复杂度O(nlogn)

#include<iostream>
#include<algorithm>

using namespace std;

int sum = 0;
struct goods
{
	int weight;
	int no;
};

void QuickSort(goods truck[], int low, int high)
{
	if (low >= high) return;
	int i = low, j = high;
	goods temp = truck[low];
	while (i < j)
	{
		while (i < j && temp.weight <= truck[j].weight) --j;
		if (i < j)
		{
			truck[i] = truck[j];
			++i;
		}
		while (i < j && temp.weight >= truck[i].weight) ++i;
		if (i < j)
		{
			truck[j] = truck[i];
			--j;
		}
		truck[i] = temp;
		QuickSort(truck, low, i - 1);
		QuickSort(truck, i + 1, high);
	}
}

void greedy(goods truck[],int x[],int n,int c)
{
	for (int i = 0; i < n; i++)
		x[i] = 0;

	for (int i = 0; i < n; i++)
	{
		if (truck[i].weight > c)
			break;
		c -= truck[i].weight;
		x[truck[i].no] = 1;
		sum += truck[i].weight;
	}

}

int main()
{
	int n,c;
	cin >> n >> c;
	goods* truck = (goods*)malloc(sizeof(goods) * n);
	int* x = new int[n];
	for (int i = 0; i < n; i++)
	{
		int w;
		cin >> w;
		truck[i].weight = w;
		truck[i].no = i;
	}

	QuickSort(truck, 0, n - 1);

	greedy(truck, x, n, c);
	cout << "最大价值为:" << sum << endl;
	cout << "装入集装箱编号:" << endl;
	for (int i = 0; i < n; i++)
	{
		if (x[i] == 1)
			cout << i << " ";
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值