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;
}
發佈了44 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章