2013-12-10 109 views
-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; 
} 

解決方法很簡單,但如果你要添加更多的變量,情況就變得複雜。是否可以使用數組和一些循環來獲得任意數量變量的解決方案?

+2

請說明問題。只需粘貼代碼並說「這很簡單」就可以刪除您的問題。 –

+3

這看起來像一個揹包問題。看看http://en.wikipedia.org/wiki/Knapsack_problem – aardvarkk

+0

我不明白你在問什麼......?我第二@aardvarkk – Plasmarob

回答

3

看來你問的是否可以使用數組來允許任意數量的「物品」被攜帶。答案是肯定的:

std::vector<int> item_weights; 
unsigned int item_count = 0; 
std::cout << "Enter item count: "; 
std::cin >> item_count; // I'll leave the error checking to you to implement 
for (unsigned int i = 0; i < item_count; ++i) 
{ 
    std::cout << "Enter weight for item " << (i + 1) << ": "; 
    unsigned int w = 0; 
    std::cin >> w; // again error checking should be added 
    item_weights.push_back(w); 
} 

// insert code to retrieve maximum weight that can be carried here 

unsigned int max_weight = std::max_element(item_weights.begin(), item_weights.end()); 
unsigned int total_weight = std::accumulate(item_weights.begin(), item_weights.end(), 0); 

// insert your code to determine the number of times it would take to carry all items here 
相關問題