手动实现的快排,时间复杂度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;
}