void backIssue() { float Weight[7] = { 35, 30, 60, 50, 40, 15, 20 }; float Value[7] = { 10, 40, 30, 50, 35, 40, 30 }; Node Array[7]; for (int i = 0; i < 7; i++) { Array[i].Weight = Weight[i]; Array[i].Value = Value[i]; Array[i].Mark = false; Array[i].Name = 65 + i; Array[i].value_weight = Value[i] / Weight[i]; } for (int i = 0; i < 7; i++) { printf("%0.5f ", Array[i].value_weight); } printf("\n"); float TotalWeight = 0; float TotalValue = 0; char Name[7] = { 0 }; int flag = 0, n = 0; float Max; while (TotalWeight <= 150) { for (int i = 0; i < 7; i++) { if (Array[i].value_weight > Max && Array[i].Mark == false) { Max = Array[i].value_weight; flag = i; } } if (TotalWeight + Array[flag].Weight > 150) { break; } TotalWeight += Array[flag].Weight; TotalValue += Array[flag].Value; Name[n++] = Array[flag].Name; Array[flag].Mark = true; Max = 0; } for (int i = 0; i <n; i++) { printf("%c", Name[i]); } printf("\n"); printf("Weight: %0.5f \n", TotalWeight); printf("Value: %0.5f \n", TotalValue); }
说明如果可以分割物品,可以将最后一个max 进行分割。
最优空间,时间选择问题 Code 2:
void meetingIssue() { int s[11] = { 1, 3, 0, 5, 3, 5, 6, 8, 8, 2, 12 }; int f[11] = { 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }; int task[11] = {0}; int Mask[11] = {0}; bool flag[11] = {0}; int max = 0; for (int i = 0; i < 11; i++) { task[i] = f[i] - s[i]; printf("%d ",task[i]); } printf("\n"); int index = 0,n= 0, Totaltime = 0; while (Totaltime <= 24) { for (int i = 0; i < 11; i++) { if (task[i]>max && flag[i] == false) { max = task[i]; index = i; } } if (Totaltime + max>24) { break; } Totaltime += max; flag[index] = true; Mask[n++] = index; max = 0; } for (int i = 0; i < n; i++) { printf("%d ", Mask[i]); } printf("\n"); printf("total time: %d \n", Totaltime); }