POJ - 2893 M × N Puzzle【归并排序】

【题目描述】
The Eight Puzzle, among other sliding-tile puzzles, is one of the famous problems in artificial intelligence. Along with chess, tic-tac-toe and backgammon, it has been used to study search algorithms.

The Eight Puzzle can be generalized into an M × N Puzzle where at least one of M and N is odd. The puzzle is constructed with MN − 1 sliding tiles with each a number from 1 to MN − 1 on it packed into a M by N frame with one tile missing. For example, with M = 4 and N = 3, a puzzle may look like:
在这里插入图片描述
Let’s call missing tile 0. The only legal operation is to exchange 0 and the tile with which it shares an edge. The goal of the puzzle is to find a sequence of legal operations that makes it look like:
在这里插入图片描述
The following steps solve the puzzle given above.
在这里插入图片描述
Given an M × N puzzle, you are to determine whether it can be solved.

【输入】
The input consists of multiple test cases. Each test case starts with a line containing M and N (2 ≤ M, N ≤ 999). This line is followed by M lines containing N numbers each describing an M × N puzzle.

The input ends with a pair of zeroes which should not be processed.

【输出】
Output one line for each test case containing a single word YES if the puzzle can be solved and NO otherwise.

【样例输入】
3 3
1 0 3
4 2 5
7 8 6
4 3
1 2 5
4 6 9
11 8 10
3 7 0
0 0

【样例输出】
YES
NO

题目链接:https://vjudge.net/problem/POJ-2893

n*m数码有解性判定自行百度,归并排序求逆序对判断

代码如下:

#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
static const int MAXN=999*999;
int a[MAXN+10],b[MAXN+10];
ll cnt;
void merge(int l,int r)
{
    if(r-l<1)
        return;
    int mid=(l+r)>>1;
    merge(l,mid);
    merge(mid+1,r);
    int i=l,j=mid+1;
    for(int k=l;k<=r;k++)
        if(j>r || i<=mid && a[i]<=a[j])
            b[k]=a[i++];
        else
        {
            b[k]=a[j++];
            cnt+=mid-i+1;
        }
    for(int k=l;k<=r;k++)
        a[k]=b[k];
}
int main()
{
    // std::ios::sync_with_stdio(false);
    // std::cin.tie(0),cout.tie(0);
    int n,m;
    while(cin>>n>>m && !(n==0 && m==0))
    {
        int tmp=0,line=0;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
            {
                // cin>>a[(i-1)*m+j-tmp];
                scanf("%d",&a[(i-1)*m+j-tmp]);
                if(a[(i-1)*m+j-tmp]==0)
                {
                    tmp=1;
                    line=i;
                }
            }
        cnt=0;
        merge(1,n*m-1);
        if(m%2==0 && cnt%2==(n-line)%2 || m%2 && cnt%2==0)
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值