完整程序:
#include<bits/stdc++.h>
using namespace std;
// 最優裝載問題貪心
struct load {
int index; //集裝箱編號
int w; //集裝箱重量
}box[1001];
//排序因子(按集裝箱的重量升序):
bool cmp (load a, load b) {
if (a.w<b.w) return true;
else return false;
}
int main(){
int c,n;
int x[1000];
while (scanf("%d%d", &c, &n)!=EOF)
{
memset(box, 0, sizeof(box));
memset(x, 0, sizeof(x));
for (int i=1; i<=n; i++)
{
scanf("%d", &box[i].w);
box[i].index = i;
}
//按集裝箱的重量升序排序
stable_sort(box, box+n+1, cmp);
if (box[1].w>c) {
printf("No answer!\n");
continue;
}
//貪心算法的實現,重量最輕者先裝載
int i;
for (i=1; i<=n && box[i].w<=c; i++)
{
x[box[i].index] = 1;
c -= box[i].w;
}
//輸出裝載的集裝箱數量
printf("%d\n", i-1);
//輸出裝載的集裝箱編號
for (i=1; i<=n; i++)
if (x[i]) printf("%d ", i);
printf("\n");
}
return 0;
}