Pagini recente » Cod sursa (job #241847) | Cod sursa (job #2120318) | Cod sursa (job #823665) | Cod sursa (job #1870273) | Cod sursa (job #2107354)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <conio.h>
using namespace std;
ifstream fin("rucsac.in");
ofstream fout("rucsac.out");
struct elements {
int weight=0;
int price=0;
}arr[50];
void heap(int position, int contor){
int l = position * 2;
int r = position * 2 + 1;
int boss = position;
int aux;
if (l <= contor && arr[l].price>arr[boss].price)
boss = l;
if (r <= contor && arr[r].price>arr[boss].price)
boss = r;
if (boss != position) {
aux = arr[position].price;
arr[position].price = arr[boss].price;
arr[boss].price = aux;
aux = arr[position].weight;
arr[position].weight = arr[boss].weight;
arr[boss].weight = aux;
heap(boss, contor);
}
}
void heapsort(int size){
int aux;
for (int i = size / 2 - 1; i >= 0; i--)
heap(i, size);
for (int i = size - 1; i >= 0; i--) {
aux = arr[i].price;
arr[i].price = arr[0].price;
arr[0].price = aux;
aux = arr[i].weight;
arr[i].weight = arr[0].weight;
arr[0].weight = aux;
heap(0 , i - 1);
}
}
int backpack(int size, int G) {
elements total;
for (int i = size - 1; i >= 0; i--) {
if (total.weight + arr[i].weight <= G) {
total.weight += arr[i].weight;
total.price += arr[i].price;
}
if (total.weight == G)
break;
}
return total.price;
}
int main() {
int size, G;
fin >> size >> G;
for (int i = 0; i < size; i++) {
fin >> arr[i].weight >> arr[i].price;
}
heapsort(size);
fout << backpack(size, G);
_getch();
}