题目大意:对于给定的16数码问题,判断是否存在解。
分析:当我们把给定的棋盘看做一个排列,0看做16。可以证明当排列的逆序对+16到目标格子的距离为偶数时有解。
代码如下:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read()
{
int x = 0, f = 1, t = getchar();
while(t < '0' || t > '9') {
if(t == '-') f = -1;
t = getchar();
}
while(t >= '0' && t <= '9') {
x = (x<<1) + (x<<3) + t - '0';
t = getchar();
}
return x * f;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int A[17] = {0}, cnt;
for(int i = 0; i < 4; ++i)
for(int j = 0; j < 4; ++j)
if((A[i*4+j] = read()) == 0)
cnt = 6-i-j, A[i*4+j] = 16;
for(int i = 0; i < 16; ++i)
for(int j = i+1; j < 16; ++j)
cnt += (A[i] > A[j]);
if(cnt & 1) puts("NO"); else puts("YES");
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}