sgu139: Help Needed!

题目大意:对于给定的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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值