1. 程式人生 > >HDU 1998 奇數階魔方【模擬填數/註意邊界和細節】

HDU 1998 奇數階魔方【模擬填數/註意邊界和細節】

display chm gif ret namespace gpo iostream div spring

奇數階魔方

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4861 Accepted Submission(s): 2770


Problem Description 一個 n 階方陣的元素是1,2,...,n^2,它的每行,每列和2條對角線上元素的和相等,這樣
的方陣叫魔方。n為奇數時我們有1種構造方法,叫做“右上方” ,例如下面給出n=3,5,7時
的魔方.
3
8 1 6
3 5 7
4 9 2
5
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
7
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
第1行中間的數總是1,最後1行中間的數是n^2,他的右邊是2,從這三個魔方,你可看出“右
上方”是何意。

Input 包含多組數據,首先輸入T,表示有T組數據.每組數據1行給出n(3<=n<=19)是奇數。

Output 對於每組數據,輸出n階魔方,每個數占4格,右對齊

Sample Input 2 3 5 Sample Output 8 1 6 3 5 7 4 9 2 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 Author Zhousc@ECJTU Source ECJTU 2008 Spring Contest 技術分享圖片
#include<iostream>
#include
<algorithm> #include<cstdio> #include<cstring> #include<set> #include<map> #include<sstream> #include<queue> #include<cmath> #include<list> #include<vector> #include<string> using namespace std; #define long long ll const double PI = acos(-1.0); const double eps = 1e-6; const int inf = 0x3f3f3f3f; const int N = 100005; int n, m, tot; int a[50][50]; int x, y; int main() { int t; cin >> t; while(t--) { memset(a, 0, sizeof(a)); cin >> n; tot = a[x=1][y=(n/2+1)] = 1; while(tot < n * n) //不等於和等於都可以AC 我TM??? { if( x - 1 <= 0 && y + 1 <= n) //1 最上層 { a[x=n][++y] = ++tot; //為什麽非要前增 我用後增完全不ojbk } else if(x - 1 >= 1 && y + 1 <= n && a[x-1][y+1] == 0 ) //normal { a[--x][++y] = ++tot; } else if(x - 1 >= 1 && y + 1 > n) //4 最右邊界 { a[--x][y=1] = ++tot; } else if( (x - 1 <= 0 && y + 1 > n) || ( x - 1 >= 1 && y + 1 <= n && a[x - 1][y + 1] ) ) //28 || 14 最右上角 { a[++x][y] = ++tot; } } for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { printf("%4d",a[i][j]); } cout<<endl; } } return 0; }
View Code

【註釋有幾個疑問,疑義相與析,誰與我來析呢?】

HDU 1998 奇數階魔方【模擬填數/註意邊界和細節】