sgu139

题目:

139. Help Needed!

time limit per test: 0.25 sec. 
memory limit per test: 4096 KB

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 
                             5  6  7  8 
                             9 10 11 12 
                            13 14 15  0

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值