Nerde Nolzda

UVa10696: f91

簡單的以附於頁尾的程式計算,會發現當 n <= 100f91(n) = 91。由於就算如此運算時間仍不甚理想,故使用了一些 I/O 優化,才能用 0.000 sec 完成。
Using the simple program at the end of this page, you’ll find out that f91(n) = 91 if n <= 100. The execution time, however, is still quite high when this is applied. Thus, I used some I/O optimizations to make the execution time 0.000 seconds.

UVa Link

#include <iostream>

static inline int fast_atoi(const char *p, unsigned int len) {
  int res = 0;
  switch (len) {
    case 7: res += (*p++ & 15) * 1000000;
    case 6: res += (*p++ & 15) * 100000;
    case 5: res += (*p++ & 15) * 10000;
    case 4: res += (*p++ & 15) * 1000;
    case 3: res += (*p++ & 15) * 100;
    case 2: res += (*p++ & 15) * 10;
    case 1: res += (*p & 15);
  }
  return res;
}

bool getInt(int *res) {
  char numBuf[11], tmp;
  unsigned int i = 0;
  while (true) {
    static char buf[1 << 20], *p = buf, *end = buf;
    if (p == end) {
      if ((end = buf + fread(buf, 1, 1 << 20, stdin)) == buf) break;
      p = buf;
    }
    tmp = *p++;
    if ((unsigned)(tmp - '0') > 10u && i) break;
    numBuf[i++] = tmp;
  }
  if (!i) return false;
  *res = fast_atoi(numBuf, i);
  return true;
}

static inline int intLen(int n) {
  if (n >= 1000000) return 7;
  if (n >= 100000) return 6;
  if (n >= 10000) return 5;
  if (n >= 1000) return 4;
  if (n >= 100) return 3;
  if (n >= 10) return 2;
  return 1;
}

static inline void itoa(int n, char *dst) {
  int len = intLen(n);
  dst[len] = '\0';
  switch (len) {
    case 7: dst[6] = n % 10 + '0'; n /= 10;
    case 6: dst[5] = n % 10 + '0'; n /= 10;
    case 5: dst[4] = n % 10 + '0'; n /= 10;
    case 4: dst[3] = n % 10 + '0'; n /= 10;
    case 3: dst[2] = n % 10 + '0'; n /= 10;
    case 2: dst[1] = n % 10 + '0'; n /= 10;
    case 1: dst[0] = n % 10 + '0';
  }
}

int main() {
  int n;
  while (getInt(&n) && n) {
    char numStr[11];
    fputs("f91(", stdout);
    itoa(n, numStr);
    fputs(numStr, stdout);
    if (n > 100) {
      fputs(") = ", stdout);
      itoa(n - 10, numStr);
      fputs(numStr, stdout);
      putchar('\n');
    } else {
      fputs(") = 91\n", stdout);
    }
  }
}

Calculating f91(n) for n <=100

#include <iostream>

int f91(int n) {
  if (n > 100) return n - 10;
  return f91(f91(n + 11));
}

int main() {
  std::cout << "int arr[] = {";
  for (int i = 0; i <= 100; i++) {
    std::cout << f91(i) << ", ";
  }
  std::cout << "};";
}

Related Posts

0 comments

Post a comment

Send an email to comment@nerde.pw.