.There are n items in the suitcase of a traveler. On boarding the flight, the airline company told him that his suitcase is over weight than the allowed capacity W and asked him deload some items and not to carry more than W. He knows weight of each item and knows the priority (like which item is the most, next most, etc.). Devise an algorithm to find out which items to be discarded based on priority so that he can carry max. weight W (assume the weight of the suitcase is ignored). Write a c/c++ program.
Answers
Answer:
#include <iostream>
#include <vector>
#include <algorithm>
struct Item {
int weight;
int priority;
};
bool compareByPriority(const Item &a, const Item &b) {
return a.priority > b.priority;
}
void findItemsToDiscard(std::vector<Item> &items, int W) {
sort(items.begin(), items.end(), compareByPriority);
int current_weight = 0;
for (int i = 0; i < items.size(); i++) {
if (current_weight + items[i].weight > W) {
std::cout << "Discarding item with weight " << items[i].weight << " and priority " << items[i].priority << std::endl;
} else {
current_weight += items[i].weight;
}
}
}
int main() {
std::vector<Item> items = {{10, 1}, {20, 2}, {30, 3}, {40, 4}};
int W = 60;
findItemsToDiscard(items, W);
return 0;
}
Explanation:
- Sort the items in descending order of their priority.
- Initialize a variable current_weight to keep track of the weight of items in the suitcase.
- Loop through the sorted items and add each item to the suitcase until current_weight + next_item_weight > W.
- Discard the item that was not added to the suitcase.
- Repeat steps 3-4 until all items have been considered.
More questions and answers
https://brainly.in/question/9599693?referrer=searchResults
https://brainly.in/question/6495944?referrer=searchResults
#SPJ1