Just an Old Puzzle(规律)HDU

You are given a 4 × 4 grid, which consists of 15 number cells and an empty cell.
All numbers are unique and ranged from 1 to 15.
In this board, the cells which are adjacent with the empty cell can move to the empty cell.
Your task is to make the input grid to the target grid shown in the figure below.
In the following example (sample input), you can get the target grid in two moves.

InputThe first line contains an integer T (1 <= T <= 10^5) denoting the number of test cases.
Each test case consists of four lines each containing four space-separated integers, denoting the input grid. 0 indicates the empty cell.OutputFor each test case, you have to print the answer in one line.
If you can’t get the target grid within 120 moves, then print 'No', else print 'Yes'.Sample Input

2
1 2 3 4
5 6 7 8
9 10 0 12
13 14 11 15
1 2 3 4
5 6 7 8
9 10 11 12
13 15 14 0

Sample Output

Yes
No
 
题意:应该很好理解
分析:奇数码游戏两个局面可达,当且仅当两个局面下的网格中的数一次写成一行n*n-1个元素的序列后(不考虑空格),逆序数个数的奇偶数相同。结论还可以扩展到
n为偶数的情况下,此时两个局面可达,当且仅当写成序列后,逆序对数之差和两个局面下空格所在的行数之差奇偶性相同。总而言之,n*m数码问题的有解性判定,可以转化为归并排序求逆序对来解决。
 
AC代码:
 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<algorithm>
 5 using namespace std;
 6 const int maxn = 1e5+10;
 7 #define LL long long
 8 #define INF 0x3f3f3f3f
 9 int T,n;
10 int a[20];
11 
12 int main(){
13     scanf("%d",&T);
14     while(T--){
15         int res,ans=0;
16         for(int i=1;i<=16;i++){
17             scanf("%d",&a[i]);
18             if(!a[i]) res=i/4+(i%4?1:0);
19             else{
20                 for(int j=1;j<i;j++){
21                     if(!a[j]) continue;
22                     else if(a[j]>a[i]) ans++;
23                 }
24             }
25         }
26         if((4-res)%2==ans%2) printf("Yes
");
27         else printf("No
");
28     }
29 
30 
31     return 0;
32 }
有些目标看似很遥远,但只要付出足够多的努力,这一切总有可能实现!
原文地址:https://www.cnblogs.com/Bravewtz/p/11360165.html