Cod sursa(job #2107355)

Utilizator DryCookerDordea Dragos DryCooker Data 17 ianuarie 2018 06:27:42
Problema Problema rucsacului Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <fstream>
#include <algorithm>

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