Pagini recente » Cod sursa (job #2330101) | Cod sursa (job #928601) | Cod sursa (job #3188252) | Cod sursa (job #264306) | Cod sursa (job #463163)
Cod sursa(job #463163)
#include <stdio.h>
#include <stdlib.h>
#include "include/heap.h"
#define infile "gutui.in"
#define outfile "gutui.out"
int NMAX = 100000;
int N, H, U;
typedef struct{
int height;
int weight;
} fruit;
int compare_h_fruit(void* A, void* B, void* context)
{
fruit *a = A;
fruit *b = B;
if (a->height < b->height)
return -1;
if (a->height > b->height)
return 1;
if (a->weight < b->weight)
return -1;
if (a->weight > b->weight)
return 1;
return 0;
}
int compare_w_fruit(void* A, void* B, void* context)
{
fruit *a = A;
fruit *b = B;
if (a->weight < b->weight)
return 1;
if (a->weight > b->weight)
return -1;
if (a->height < b->height)
return -1;
if (a->height > b->height)
return 1;
return 0;
}
int sum(fruit *fr)
{
int i, s = 0;
for (i = 0; i < N; i++)
s += fr[i].weight;
return s;
}
int solve(fruit* fruits)
{
if (U == 0)
return sum(fruits);
/* Create a heap and add all values from fruits in it */
heap_t fr, fr_weight;
fr = heap_new(N);
fr_weight = heap_new(N);
int i;
for (i = 0; i< N; i++)
heap_insert(fr, &fruits[i], compare_h_fruit, NULL);
/* Set starting possition height */
int hight_limit = (H%U)? U%H-U : 0;
int picked_weight = 0;
while ((!heap_is_empty(fr) || !heap_is_empty(fr_weight)) && hight_limit <= H)
{
while ((!heap_is_empty(fr)) && ((((fruit*)heap_get_min_key(fr))->height) <= hight_limit))
{
heap_insert(fr_weight, (fruit*)heap_get_min_key(fr), compare_w_fruit, NULL);
heap_remove_min_key(fr, compare_h_fruit, NULL);
}
if (!heap_is_empty(fr_weight))
{
picked_weight += ((fruit*)heap_get_min_key(fr_weight))->weight;
heap_remove_min_key(fr_weight, compare_w_fruit, NULL);
}
hight_limit += U;
}
return picked_weight;
}
int main()
{
FILE *fin, *fout;
/* Try opening files */
if (!(fin = fopen(infile, "r")))
{
fprintf(stderr, "Could not open input file.\n");
return -1;
}
if (!(fout = fopen(outfile, "w")))
{
fprintf(stderr, "Could not open output file.\n");
return -1;
}
int i, weight;
fscanf(fin, "%d %d %d", &N, &H, &U);
if (N>NMAX)
{
fprintf(stderr, "Count size out of bounds.\n");
return 1;
}
fruit* quinces;
quinces = (fruit*) malloc(N*sizeof(fruit));
for (i = 0; i < N; i++)
fscanf(fin, "%d %d", &quinces[i].height, &quinces[i].weight);
weight = solve(quinces);
fprintf(fout, "%d\n", weight);
/* Close files and free memory */
free(quinces);
fclose(fin);
fclose(fout);
return 0;
}