Sunday, October 12, 2014

10038 - Jolly Jumpers

This is another crazy problem.

It's supposed to be straight forward, but I kept getting run time errors.

My algorithm was to create a list of checks. Whenever a difference was calculated, the checks array element with index equal to the difference was set to 1. Then once all the differences were calculated, and all the checks were marked, I verified if all check elements with indices from 1 up to n-1 were marked with 1. If all were marked with 1, then the sequence is jolly.

I thought the run time error was because I was marking a checks element that is out of bounds. So I tried increasing my checks array from 3000 to 4000. But still the run time error existed. Then I realized that if the private key was n = 3000, then the input line would be more than 3000 characters long. This meant that my usual way of getting the line from the input would not longer work.

Usually, I use this code to get input from the user:
fgets(line, 100, stdin)

But since the input line can be more than 3000 characters long, I changed the code to:
fgets(line, 1000000, stdin)

When I did this, the run time error disappeared.

Here's the code:

#include "stdio.h"
#include "string.h"
#include "stdlib.h"

int main() {
  char line[1000000];
  int n, i, x, j, diff, is_jolly;
  int arr[4000];
  int checks[4000];
  char *pch;

  while (fgets(line, 1000000, stdin)) {
    pch = strtok(line, " \t\n");
    n = atoi(pch);

    if (n == 1) {
      printf("Jolly\n");
      continue;
    }

    for (i = 0; i < n; i += 1) {
      pch = strtok(NULL, " \t\n");
      x = atoi(pch);
      arr[i] = x;
    }

//    printf("arr: ");
//    for (i = 0; i < n; i += 1) {
//      printf("%d ", arr[i]);
//    }
//    printf("\n");

    j = n - 1;
    for (i = 1; i <= j; i += 1) {
      checks[i] = 0;
    }

//    printf("checks: ");
//    for (i = 1; i <= j; i += 1) {
//      printf("%d ", checks[i]);
//    }
//    printf("\n");

    for (i = 1; i <= j; i += 1) {
      diff = arr[i] - arr[i - 1];
      
      if (diff < 0) {
        diff = -1 * diff;
      }

//      printf("diff = %d\n", diff);

      if (diff <= 3000) {
        checks[diff] = 1;
      }
    }

//    printf("diff: ");
//    for (i = 1; i <= j; i += 1) {
//      printf("%d ", checks[i]);
//    }
//    printf("\n");

    is_jolly = 1;
    for (i = 1; i <= j; i += 1) {
      if (checks[i] != 1) {
        is_jolly = 0;
        break;
      }
    }

    if (is_jolly) {
      printf("Jolly\n");
    }
    else {
      printf("Not jolly\n");
    }
  }
}

No comments:

Post a Comment