## Number Spiral [題目連結](https://cses.fi/problemset/task/1071) 題目定義了一種二維陣列(如下圖),給定一整數 $t$ 代表有接下來有幾組座標  接下來有 $t$ 行,每一行都有兩個數字 $y、x$,請輸出 陣列$[y][x]$ --- 題目標籤 : 陣列、判斷 本題提示 : 這題的陣列有幾個規律可以去找,其中有一個規律是可以透過一個位置推測出與其相近位置的值 解題思路 : 這題可以把數字拆成多個組別來看,$1$ 自己一組,$2、3、4$ 一組,$5、6、7、8、9$ 一組 也就是從左上往右下分組,這樣分組的好處就是組別最中間的值位置都在 $(i,\ i)$ 反過來說,只要我們知道 $(i,\ i)$ 的值,就可以推出整個組別的值 接下來觀察 $(i,\ i)$ 的值,$1、3、7、13、21$ 這是 $2$ 的等比級數和 $+1$,我是從相鄰差值看出來的 所以 $(i,\ i)$ 的值是可以透過 $i$ 快速計算的,接下來要看如何從 $(i,\ i)$ 推到其他位置 $3、2$ 是往上,$7、9$ 也是往上,兩者往上的值一個是增加一個是減少,其實也有規律 那就是看現在是第幾行(直行橫列),如果是奇數行就增加,偶數行就減少,往左走也是同理可推 ```cpp= #include<bits/stdc++.h> using namespace std ; typedef long long LL ; int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0) ; int t, y, x ; cin >> t ; LL ans = 0 ; for (int i=0;i<t;i++) { cin >> y >> x ; if (y > x) { ans = 1 + (LL)(y-1)*y ; // A[y][y] if (y % 2) // 奇數行 ans -= (y-x) ; else // 偶數行 ans += (y-x) ; } else { ans = 1 + (LL)(x-1)*x ; // A[x][x] if (x % 2) // 奇數行 ans += (x-y) ; else // 偶數行 ans -= (x-y) ; } cout << ans << '\n' ; } return 0 ; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up