天天看點

Educational Codeforces Round 16 Magic Odd Square

C. Magic Odd Square time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output

Find an n × n matrix with different numbers from1 to n2, so the sum in each row, column and both main diagonals are odd.

Input

The only line contains odd integer n (1 ≤ n ≤ 49).

Output

Print n lines withn integers. All the integers should be different and from1 to n2. The sum in each row, column and both main diagonals should be odd.

Examples Input

1
      

Output

1
      

Input

3
      

Output

2 1 4
3 5 7
6 9 8

      
題意:給出一個奇數n,你輸出一個n*n的矩陣,要求每行每列對角線和為奇數。      
題解:剛開始沒看到輸入的是奇數,就在網上學n階幻方,後來發現了, 我n階幻方也快學完了,。。。。後面有大神代碼,感覺不是一個世界(兩個世界。。。)      
代碼:      
#include <cstdio>//奇次幻方寫法
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <algorithm>
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define mem(a) memset(a, 0, sizeof(a))
#define eps 1e-5
#define M 100005
#define LL longlong
using namespace std;
int a[2510][2510];
int n,k,nn;
void print()
{
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=n; j++)
        {
            if(j!=1)
                printf(" %d",a[i][j]);
            else
                printf("%d",a[i][j]);
        }
        printf("\n");
    }
}
void dfs(int x,int y)
{
    if(k==n*n+1)
        return ;
    int fx=x-1>=1?x-1:n;
    int fy=y+1>n?1:y+1;
    if(a[fx][fy]==0)
    {
        a[fx][fy]=k++;
        dfs(fx,fy);
    }
    else
    {
        a[x+1][y]=k++;
        dfs(x+1,y);
    }
}
void solo1()
{
    k=1;
    int mid=(n+1)>>1;
    a[1][mid]=k++;
    dfs(1,mid);
}
int main()
{
    scanf("%d",&n);
    for(int i=1; i<=n; i++)
        for(int j=1; j<=n; j++)
            a[i][j]=0;
        solo1();
            print();
    return 0;
}
           
大神代碼:      
#include<bits/stdc++.h>
using namespace std;

int n;

int main(){
	cin >> n;
	int od = -1, ev = 0, mid = n/2 + 1;
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= n; j++){
			if(abs(i - mid) + abs(j - mid) < mid) printf("%d ", od += 2);
			else printf("%d ", ev += 2);	
		}
		puts("");
	}
	return 0;
}