题目:
139. Help Needed! time limit per test: 0.25 sec. Little Johnny likes puzzles a lot! Just a few days ago, he found out about the 'traditional' 4x4 puzzle. For this puzzle, you have all the numbers from 0 to 15 arranged in 4 rows and 4 columns. You are allowed to switch two adjacent elements (horizontally or vertically), only if one of them has the value 0. The purpose of the puzzle is to reach the following final state: 1 2 3 4 Given the initial state of the puzzle, you have to decide whether there exists a sequence of moves which brings the puzzle into the final state. Input The input will consist of 4 lines, each of them containing 4 integers, describing the initial state of the puzzle. Output For every initial state, you should print "YES" if the final state can be reached after several moves or "NO", if such a thing is impossible. Sample Input #1 1 2 3 4 5 6 7 8 9 10 11 0 13 14 15 12 Sample Output #1 YES Sample Input #2 2 1 3 4 5 6 7 8 9 10 11 12 0 13 14 15 Sample Output #2 NO |
题解:
令a等于空格到最后一格的最少移动次数,b等于每个偏离位置的数(包括空格)与它的位置交换的次数,a+b若为偶数,则有解,否则无解。因为每次移动一个数,空格的移动次数就加1或减1,交换次数同样加1或减1,和的奇偶性不变。
代码:
#include <cstdio>
#include <algorithm>
using namespace std;
int f[5][5] = {{0}}, sum = 0, findit = 1;
int main()
{
for (int i = 1; i <= 4; i++)
for (int j = 1; j <= 4; j++)
{
scanf("%d", &f[i][j]);
if (!f[i][j])
{
sum = 8 - i - j;
f[i][j] = 16;
}
}
while (findit > 0)
{
findit = 0;
for (int i = 1; i <= 4; i++)
for (int j = 1; j <= 4; j++)
if ((i - 1) * 4 + j != f[i][j])
{
swap(f[(f[i][j] - 1) / 4 + 1][(f[i][j] - 1) % 4 + 1], f[i][j]);
sum++;
findit = 1;
}
}
if (sum % 2 == 0) printf("YES\n");
else printf("NO\n");
return 0;
}
代码丑陋233