Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <memory.h>
- #define MAXSTR 1000
- long longCompare(const void *a, const void *b) {
- return -1 * (*(long *) a - *(long *) b);
- }
- int read_input(char *filename, long **shelves, long **books, int *nShelves, int *nBooks, int *maxBooksWidth) {
- FILE *in = fopen(filename, "r");
- long tmp;
- char *shelves_width_s = malloc(MAXSTR * sizeof(char));
- int n = 0, N = 3;
- *shelves = malloc(N * sizeof(long));
- int k = 0, K = 3;
- *books = malloc(N * sizeof(long));
- // Read the shelves widths
- fgets(shelves_width_s, MAXSTR, in);
- char *tmpC = shelves_width_s;
- while ((tmp = strtol(tmpC, &tmpC, 10)) != 0) {
- if (n >= N) {
- N *= 2;
- *shelves = realloc(*shelves, N * sizeof(long));
- }
- *(*shelves + n++) = tmp;
- }
- *nShelves = n;
- //Read the books widths
- while (fscanf(in, "%ld %*s", &tmp) == 1) {
- if (k >= K) {
- K *= 2;
- *books = realloc(*books, K * sizeof(long));
- }
- *(*books + k++) = tmp;
- (*maxBooksWidth) += tmp;
- }
- *nBooks = k;
- free(shelves_width_s);
- }
- int solve(long *shelves, const long *books, int nShelves, int nBooks, int maxBooksWidth) {
- int currShelf = 0;
- int *markBooks = malloc(nBooks * sizeof(int));
- int *markShelves = malloc(nShelves * sizeof(int));
- long *shelvesCopy = malloc(nShelves * sizeof(long));
- memcpy(shelvesCopy, shelves, nShelves * sizeof(long));
- for (int k = 0; k < nBooks; k++)
- markBooks[k] = 0;
- for (int k = 0; k < nShelves; k++)
- markShelves[k] = 0;
- for (int i = 0; i < nShelves && maxBooksWidth != 0; i++) {
- for (int j = 0; j < nBooks && maxBooksWidth != 0; j++) {
- if (!markBooks[j] && shelvesCopy[i] >= books[j]) {
- currShelf = i;
- markShelves[i] = 1;
- shelvesCopy[i] -= books[j];
- maxBooksWidth -= books[j];
- markBooks[j] = 1;
- }
- }
- }
- if (maxBooksWidth == 0) {
- printf("Shelves to buy: %d\n", currShelf + 1);
- for (int i = 0; i <= currShelf; i++)
- printf("%ld ", shelves[i]);
- } else
- printf("Impossible\n");
- }
- int main() {
- long *shelves; //Contains the shelves width
- int nShelves;
- long *books; //Contains the books width
- int nBooks;
- int maxBooksWidth = 0;
- read_input("input.txt", &shelves, &books, &nShelves, &nBooks, &maxBooksWidth);
- qsort(shelves, nShelves, sizeof(long), longCompare);
- qsort(books, nBooks, sizeof(long), longCompare);
- solve(shelves, books, nShelves, nBooks, maxBooksWidth);
- return 0;
- }
Add Comment
Please, Sign In to add comment