Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- #include <time.h>
- #define MAX(a, b) a > b ? a : b
- #define NMAX 15
- #define NMIN 5
- typedef struct {
- int weight, gain;
- } Item;
- int ksBktr(int n, int k, const Item items[]) {
- uint16_t state, lastState = (1 << n) - 1;
- int ans = 0;
- for (state = 0; state <= lastState; state++) {
- int weight = 0, gain = 0;
- for (int bit = 0; bit < NMAX; bit++) {
- Item item = items[bit];
- if ((state & (1 << bit)) && weight + item.weight <= k) {
- weight += item.weight;
- gain += item.gain;
- }
- }
- ans = MAX(ans, gain);
- }
- return ans;
- }
- double getSecs(clock_t start, clock_t end) {
- return ((double) (end - start)) / CLOCKS_PER_SEC;
- }
- int main() {
- //modify the input from here if you want
- const int k = 10;
- const Item items[NMAX + 1] = {{3,7},{3,4},{1,2},{1,9},{2,4},{1,5}};
- FILE *f = popen("gnuplot --slow", "w");
- if (f == NULL) {
- perror("popen error: ");
- exit(EXIT_FAILURE);
- }//*/
- fprintf(f, "plot '-'\n");
- clock_t start, end;
- for (int i = NMIN; i <= NMAX; i++) {//plot 5-15
- start = clock();
- int ans = ksBktr(i, k, items);
- end = clock();
- printf("n=%d: %d\n", i, ans);
- double secs = getSecs(start, end);
- fprintf(f, "%d %lf\n", i, secs);
- }
- fprintf(f, "e\n");
- fprintf(f, "set title \"time(n)\"\n");
- fprintf(f, "set xlabel \"n\"\n");
- fprintf(f, "set ylabel \"time\"\n");
- if (fflush(f) == EOF) {
- perror("");
- fclose(f);
- exit(-1);
- }
- puts("PRESS ENTER TO EXIT...");
- getchar();
- if (fclose(f) == EOF) {
- perror("");
- }//*/
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement