Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <sstream>
- #include <iomanip>
- #include <algorithm>
- #include <cstdio>
- #define SIZE 100
- #define TAB 8
- using namespace std;
- struct item {
- int ID;
- int weight;
- int value;
- double wm;
- double taken;
- };
- bool comp(struct item X, struct item Y) {
- return X.wm > Y.wm;
- }
- double fillUpKnapsack(struct item A[], int numberOfItems, int W) {
- int remainingSpace = W;
- double cost = 0.0;
- for (int i = 0; i < numberOfItems && remainingSpace; i++) {
- if (A[i].weight <= remainingSpace) {
- cost += A[i].value;
- A[i].taken = 1.0;
- remainingSpace -= A[i].weight;
- }
- else {
- cost += 1.0 * A[i].value / A[i].weight * remainingSpace;
- A[i].taken = 1.0 * remainingSpace / A[i].weight;
- remainingSpace = 0;
- }
- }
- return cost;
- }
- void printItems(struct item A[], int numberOfItems) {
- cout << setw(TAB) << "ID";
- cout << setw(TAB) << "Value";
- cout << setw(TAB) << "Weight";
- cout << setw(TAB) << "V/W";
- cout << setw(TAB) << "Taken";
- cout << endl;
- for (int i = 0; i < numberOfItems; i++) {
- cout << setw(TAB) << A[i].ID;
- cout << setw(TAB) << A[i].value;
- cout << setw(TAB) << A[i].weight;
- cout << setw(TAB) << A[i].wm;
- cout << setw(TAB) << A[i].taken;
- cout << endl;
- }
- cout << endl;
- }
- int main() {
- freopen("input.txt", "r", stdin);
- string line;
- int W;
- cout << "Weight of Knapsack: ";
- getline(cin, line);
- stringstream(line) >> W;
- cout << "Items' Values and Weights: ";
- getline(cin, line);
- istringstream iss(line);
- struct item A[SIZE];
- int numberOfItems;
- for (numberOfItems = 0; iss >> line; numberOfItems++) {
- A[numberOfItems].ID = numberOfItems + 1;
- stringstream(line) >> A[numberOfItems].value;
- iss >> line;
- stringstream(line) >> A[numberOfItems].weight;
- A[numberOfItems].wm = 1.0 * A[numberOfItems].value / A[numberOfItems].weight;
- A[numberOfItems].taken = 0.0;
- }
- sort(A, A + numberOfItems, comp);
- double cost = fillUpKnapsack(A, numberOfItems, W);
- cout << "Maximum Cost: " << cost << endl;
- printItems(A, numberOfItems);
- return 0;
- }
- /*
- SAMPLE INPUT:
- 5
- 10 4 15 5 6 1 14 2
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement