Pagini recente » Cod sursa (job #2489742) | Cod sursa (job #993758) | Cod sursa (job #2021312) | Cod sursa (job #2811529) | Cod sursa (job #2488020)
#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;
}
}