Cod sursa(job #2574463)

Utilizator hannahcrisHannah Cris hannahcris Data 5 martie 2020 22:39:01
Problema Problema rucsacului Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.23 kb
#include <bits/stdc++.h>
using namespace std;

struct Object {
    int weight;
    int price;

    Object(int _weight, int _price) : weight(_weight), price(_price) {}
};

class Task {
 public:
    void solve() {
        read_input();
        print_output(get_result());
    }

 private:
    int n, w;
    vector<Object> objs;

    void read_input() {
        ifstream fin("in");
        fin >> n >> w;
        for (int i = 0, weight, price; i < n; i++) {
            fin >> weight >> price;
            objs.push_back(Object(weight, price));
        }
        fin.close();
    }

void sortare(vector<Object> items, int n){
    
}

double add_in_backpack(vector<Object> items, int n, int w){
    int i, j;
    for(i = 0; i < n - 1; i++){
        for(j = i + 1; j < n; j++){
            if((double)(items[i].price/items[i].weight) <= (double)(items[j].price/items[j].weight)){
                swap(items[i], items[j]);
                 cout << items[i].price << "  " << items[i].weight << " : " 
             << ((double)items[i].price / items[i].weight) << endl; 
            }
        }
    }

    for(i = 0; i < n; i++){
        printf("%d %d\n", items[i].price, items[i].weight);
    }

    for (int i = 0; i < n; i++) 
    { 
        cout << items[i].price << "  " << items[i].weight << " : " 
             << ((double)items[i].price / items[i].weight) << endl; 
    } 

    int crtW = 0;
    double finalValue = 0;
    for(i = 0; i < n; i++){
        if(crtW + items[i].weight <= w){
            crtW += items[i].weight;
            finalValue += items[i].price;
        } else {
            int r = w - crtW;
            finalValue += items[i].price * ((double) r / items[i].weight);
            break;
        }
    }
    return finalValue;

}

    double get_result() {
        sortare(objs, n);
        return add_in_backpack(objs, n, w);
    }

    void print_output(double result) {
        ofstream fout("out");
        fout << setprecision(4) << fixed << result;
        fout.close();
    }
};

// Please always keep this simple main function!
int main() {
    // Allocate a Task object on heap in order to be able to
    // declare huge static-allocated data structures inside the class.
    Task *task = new Task();
    task->solve();
    delete task;
    return 0;
}