Cod sursa(job #65402)
#include <stdio.h>
#include <assert.h>
#include <string.h>
enum { max_cost = 10001, max_items = 1002, inf = 0x3F3F3F3F };
int items, wanted;
int item[max_items][2]; // [0] - energy; [1] - cost
int cost[max_items][max_cost]; //cost[i][j] = min cost of having j energy with items 0..i
int ans;
void go()
{
int i, j;
memset(cost, 0x3F, sizeof(cost));
cost[0][0] = 0;
for(i = 1; i <= items; i++) //1-based! subtract 1
{
for(j = 0; j < max_cost; j++)
{
cost[i][j] = cost[i - 1][j]; //don't use this item
if(j - item[i - 1][0] >= 0) //May Be Optimized (tm)
{
int tmp = cost[i - 1][ j - item[i - 1][0] ] + item[i - 1][1];
if(cost[i][j] > tmp)
cost[i][j] = tmp;
}
//if(cost[i][j] != inf)
// printf("cost items %d energy %d: %d\n", i, j, cost[i][j]);
assert(cost[i][j] >= 0 && cost[i][j] <= inf);
}
//printf("\n");
}
ans = inf;
for(i = wanted; i < max_cost; i++)
if(cost[items][i] < ans)
ans = cost[items][i];
if(ans == inf)
ans = -1; //not enough energy
printf("ans %d\n", ans);
}
int main()
{
int i;
FILE *f = fopen("energii.in", "r");
if(!f) return 1;
fscanf(f, "%d%d", &items, &wanted);
for(i = 0; i < items; i++)
fscanf(f, "%d%d", &item[i][0], &item[i][1]);
fclose(f);
f = fopen("energii.out", "w");
if(!f) return 1;
go();
fprintf(f, "%d\n", ans);
fclose(f);
return 0;
}