24h購物| | PChome| 登入
2011-12-16 15:25:17| 人氣2,509| 回應0 | 上一篇 | 下一篇

[UVA] 1266 - Magic Square

推薦 0 收藏 0 轉貼0 訂閱站台

If you have good observations skills, you may found that building a Magic Square is simple. A Magic Square
has only an odd number N of rows and columns. For this problem you could expect the values to be
3 N 15 . A Magic Square is created by integer numbers in the range from 1 to N2 , with a peculiar
property, the ``sum of the numbers" in each row, column and diagonal is the same value.
For example the case for n = 3 is:
M. Square Rows Columns Diagonals
8 1 6 8+1+6 = 15 8+3+4 = 15 8+5+2 = 15
3 5 7 3+5+7 = 15 1+5+9 = 15 4+5+6 = 15
4 9 2 4+9+2 = 15 6+7+2 = 15
Hint: Imagine that the square is rounded. That is, the last row is connected with the first row and the last
column is connected with the first column. As shown in the examples, the starting point is the center of the
first row and observe how the numbers are placed following diagonals. There is only one more thing to
observe, what happens when you find a cell that is already in use.
Input
A file with several lines, each line has the value of n .
Output
For each input line, print N and the sum in the first line, followed by the magic square. To see a nice looking
square, take into account the maximum length in characters of N2 and print each number with the maximum
length preceded by one space or blank character. Print one line between squares.
Sample Input
3
5
Sample Output
n=3, sum=15
8 1 6
3 5 7
4 9 2
n=5, sum=65
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9






作法 : 魔方陣, 做法來自 wiki

#include<stdio.h>
#include<string.h>
int main() {
    int n, i, j;
    while(scanf("%d", &n) == 1) {
        printf("n = %d, sum = %d\n", n, n*(n*n+1)/2);
        int map[15][15], x = 0, y = n/2;
        memset(map, 0, sizeof(map));
        for(i = 1; i <= n*n; i++) {
            if(map[x][y]) {
                x += 2, y--;
                if(x >= n)    x -= n;
                if(y < 0)     y += n;
                map[x][y] = i;
            } else
                map[x][y] = i;
            x--, y++;            
            if(x < 0)    x += n;
            if(y >= n)    y -= n;
            
        }
        for(i = 0; i < n; i++, puts(""))
            for(j = 0; j < n; j++)
                printf("%3d", map[i][j]);
    }
    return 0;
}

台長: Morris
人氣(2,509) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 1121 - Subsequence
此分類上一篇:[UVA] 1185 - Big Number

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文