sgu139:Help Needed!

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
作者这题参考的是八数码那道题的逆序数解法,详见http://wenku.baidu.com/link?url=9ogPCdO5kxx1OUEL_8YVMrShzPsNZtLNtJU1u7a1w8-WSziH7hEEG19p2ClOclGIyUjKN5PQ8OsvwJ5JOS28_trigTI4GxbCCN574frjy97
我们可以把0当作16。
每次横向或移动时,逆序数奇偶性改变,到(4,4)的曼哈顿距离奇偶性也变化,所以总和的奇偶性不变。
而目标状态的总和为偶数,因此若初始状态的总和为奇数,无解;否则有解。
#include <cstdio>
#include <cstring>
using namespace std;
int A[16] = {0};
int main()
{
  int dis = 0, calc = 0;
  for(int i = 0; i < 4; ++i)
    for(int j = 0; j < 4; ++j)
    {
      scanf("%d", &A[i*4+j]);
      if(A[i*4+j] == 0)
      {
        dis = 6-i-j;
	    A[i*4+j] = 16;
	  }
    }
  for(int i = 0; i < 16; ++i)
    for(int j = i+1; j < 16; ++j)
      if(A[j] < A[i]) calc++;
  if((dis+calc)&1) puts("NO");
  else puts("YES");
  return 0;	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值