Cod sursa(job #2488021)

Utilizator arcoC. Nicolae arco Data 5 noiembrie 2019 23:43:50
Problema Energii Scor 5
Compilator c-64 Status done
Runda Arhiva de probleme Marime 1.41 kb
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

typedef unsigned int uint;

int solve(int n, int currentEnergy, int currentCost, int targetEnergy, int *energy, int *cost);

int main(void)
{
	FILE *fin = fopen("energii.in", "r");
	FILE *out = fopen("energii.out", "w");

	if(fin != NULL && out != NULL)
	{
		int g;
		int targetEnergy;

		fscanf(fin, "%d%*c%d%*c", &g, &targetEnergy);
		int *costs = malloc(sizeof(int) * g);
		int *energy = malloc(sizeof(int) * g);
		if(costs != NULL && energy != NULL) {
			int i = 0;
			for(; i < g; i++) {
				fscanf(fin, "%d%*c", &energy[i]);
				fscanf(fin, "%d%*c", &costs[i]);
			}

			int sol = solve(g - 1, 0, 0, targetEnergy, energy, costs);
			fprintf(out, "%d\n", sol != INT_MAX ? sol : -1);

			free(costs);
			free(energy);
		} else {
			printf("Failed to allocate memory\n");
		}

		fclose(fin);
		fclose(out);
	} else {
		printf("Error\n");
	}

	return 0;
}

int solve(int n, int currentEnergy, int currentCost, int targetEnergy, int *energy, int *cost)
{
	// printf("%d %d %d\n", n, currentEnergy, currentCost);
	if(n == 0) {
		return (currentEnergy >= targetEnergy) ? currentCost : INT_MAX;
	} else {
		int c1 = solve(n - 1, currentEnergy, currentCost, targetEnergy, energy, cost);
		int c2 = solve(n - 1, currentEnergy + energy[n], currentCost + cost[n], targetEnergy, energy, cost);

		return (c1 < c2) ? c1 : c2;		
	}
}