要循环找出解决方案?

时间:2013-12-10 20:16:59

标签: c++

问题: 一个人携带所有物品需要多少次?人每次都可以携带'carryWeight'千克体重。

我的解决方案:

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;
}

解决方案很简单,但如果你必须添加更多变量,那就变得复杂了。是否可以使用数组和一些循环来获得任意数量的变量的解决方案?

1 个答案:

答案 0 :(得分: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