-1
問題: 一個人攜帶所有物品需要多少次?每次可以攜帶'carryWeight'公斤的重量。For循環找出解決方案?
我的解決辦法:
int main()
{
int a = 40; // 1st item weight
int b = 35; // 2nd item weight
int c = 20; // 3rd item weight
int maxItemWeight = a; // Max weight item.
int times; // Times to carry all the items
int carryWeight; //How much weight a person can carry at once
cin >> carryWeight;
if (maxItemWeight > carryWeight)
cout << "It's impossible to carry all the items " << endl;
else {
if((a + b + c) <= carryWeight)
times = 1;
else if ((a+b) <=carryWeight && (a+c) <=carryWeight && (b+c) <=carryWeight)
times = 2;
else
times = 3;
cout << "Times to carry all the items: " << carryWeight << endl;
}
return 0;
}
解決方法很簡單,但如果你要添加更多的變量,情況就變得複雜。是否可以使用數組和一些循環來獲得任意數量變量的解決方案?
請說明問題。只需粘貼代碼並說「這很簡單」就可以刪除您的問題。 –
這看起來像一個揹包問題。看看http://en.wikipedia.org/wiki/Knapsack_problem – aardvarkk
我不明白你在問什麼......?我第二@aardvarkk – Plasmarob