題目鏈接
題意:給定一個三維的n數碼游戲,要求變換為按順序,並且最後一個位置是空格,問能否變換成功
思路:和二維的判定方法一樣,因為z軸移動,等於交換N^2 - 1次,y軸移動等於交換N - 1次,x軸移動不變,逆序對的奇偶性改變方式不變。
那麼n為偶數的時候,逆序對為偶數可以,為奇數不行
n為奇數時候,看空格位置的y軸和z軸分別要走的步數和逆序對的奇偶性相不相同,相同可以,不相同步行
代碼:
#include#include const int N = 1000005; typedef long long ll; int t, n, a[N], save[N], v; ll cal(int *a, int l, int r) { if (l >= r) return 0; int mid = (l + r) / 2; int sl = l, sr = r; ll ans = cal(a, l, mid) + cal(a, mid + 1, r); int tmp = mid; mid++; for (int i = l; i <= r; i++) { if (l <= tmp && mid <= r) { if (a[l] <= a[mid]) save[i] = a[l++]; else { ans += mid - i; save[i] = a[mid++]; } } else if (l <= tmp) save[i] = a[l++]; else if (mid <= r) save[i] = a[mid++]; } for (int i = sl; i <= sr; i++) a[i] = save[i]; return ans; } bool judge() { ll nx = cal(a, 0, n * n * n - 2); if (n&1) { if (nx&1) return false; } else { int z[3]; for (int i = 0; i < 3; i++) { z[i] = v % n; v /= n; } ll bu = 2 * n - 2 - z[2] - z[1]; if ((bu^nx)&1) return false; } return true; } int main() { scanf("%d", &t); while (t--) { scanf("%d", &n); int flag = 0; for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int now = n * n * k + n * i + j - flag; scanf("%d", &a[now]); if (a[now] == 0) { v = now; flag = 1; } } } } if (judge()) printf("Puzzle can be solved.\n"); else printf("Puzzle is unsolvable.\n"); } return 0; }