【题目描述】
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;
}