#最优装载--贪心
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int sum=0;
struct things
{
int w;
int num;
} thing[1000];
bool cmp(things a,things b)
{
if (a.w<b.w)
return true;
else
return false;
}
void loading(int x[],things thing[],int n,int c)
{
sort(thing+1,thing+n+1,cmp);
for(int i=1;i<=n;i++)
{
if(thing[i].w<=c)
{
x[thing[i].num]=1;
c=c-thing[i].w;
sum=sum+thing[i].w;
}
else
x[thing[i].num]=0;
}
}
int main()
{
int n;
int c;
int x[1000];
memset(x,0,sizeof(x));
cout<<"输入物品的个数和轮船的容量"<<endl;
cin>>n>>c;
cout<<"输入物品的质量"<<endl;
for(int i=1; i<=n; i++)
{
cin>>thing[i].w;
thing[i].num=i;
}
loading(x,thing,n,c);
cout<<"输出总价值为"<<sum<<endl;
for(int i=1; i<=n; i++)
cout<<x[i]<<" ";
cout<<endl;
return 0;
}
测试数据
10 100
20
20
5
25
28
10
3
4
8
9
总值79
1110011111