本文主要是介绍UVA 716 - Commedia dell' arte(三维N数码问题),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
UVA 716 - Commedia dell' arte
题目链接
题意:给定一个三维的n数码游戏,要求变换为按顺序,并且最后一个位置是空格,问能否变换成功
思路:和二维的判定方法一样,因为z轴移动,等于交换N^2 - 1次,y轴移动等于交换N - 1次,x轴移动不变,逆序对的奇偶性改变方式不变。
那么n为偶数的时候,逆序对为偶数可以,为奇数不行
n为奇数时候,看空格位置的y轴和z轴分别要走的步数和逆序对的奇偶性相不相同,相同可以,不相同步行
代码:
#include <cstdio>
#include <cstring>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;
}
这篇关于UVA 716 - Commedia dell' arte(三维N数码问题)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!