2013年8月7日

UVa 1266 - Magic Square

#include <stdio.h>

int main() {
  int n, first = 1;
  while (scanf("%d", &n) == 1) {
    if (!first) {
      puts("");
    }
    first = 0;
    int i, r = 0, c = n >> 1, sq[99][99] = {};
    for (i = 1; i <= n * n; i++) {
      sq[r][c] = i;
      int nr = (r + n - 1) % n, nc = (c + 1) % n;
      if (sq[nr][nc]) {
        nr = (r + 1) % n;
        nc = c;
      }
      r = nr;
      c = nc;
    }
    int sum = 0;
    for (c = 0; c < n; c++) {
      sum += sq[0][c];
    }
    printf("n=%d, sum=%d\n", n, sum);
    int maxLen = 1;
    i = n * n;
    while (i) {
      i /= 10;
      maxLen++;
    }
    for (r = 0; r < n; r++) {
      for (c = 0; c < n; c++) {
        printf("%*d%s", maxLen, sq[r][c], c == n - 1 ? "\n" : "");
      }
    }
  }
  return 0;
}

沒有留言:

張貼留言