Just an Old Puzzle
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 645 Accepted Submission(s): 411
Problem Description
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.
Input
The 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.
Output
For 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
题意解析:
题意就是给出一个华容道,让你判断能不能在120步之内将这个华容道变成标准形式:
解题分析:
很容易,其实就要判断这个4x4的华容道有没有解,也就是它能不能弄成标准形式,就可以了;
因为4x4的华容道,最难的情况下好像也就是需要八十多步就可以完成;
判断有没有解的方法是:
令n1 = 空白格当前所在行与标准形式中空白格所在行的差值;
令n2 = 将15个数字排成一列以后,整个序列的逆序对的个数;
如果n1和n2都为奇数或者都为偶数的话,就是有解,否则无解;
代码篇:
#include <iostream>
using namespace std;
int main()
{
int t, a[16];
cin >> t;
while(t--)
{
int sum1 = 0, sum2 = 0, index;
for(int i = 0; i < 16; i++)
{
cin >> a[i];
if(a[i] == 0)
index = i + 1;
}
for(int i = 0; i < 16; i++)
{
for(int j = i; j < 16; j++)
{
if(a[i] > a[j] && a[i] != 0 && a[j] != 0) ///判断逆序对的个数
sum1++;
}
}
sum2 = index / 4 + 1; ///判断行号差值
if(index % 4 == 0)
sum2 --;
sum2 = 4 - sum2;
if(sum1 % 2 == 0 && sum2 % 2 == 0)
cout << "Yes" << endl;
else if(sum1 % 2 == 1 && sum2 % 2 == 1)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}
OVER!