1. 程式人生 > >poj 2893 M × N Puzzle(M*N數碼解的判定,使用逆序對)

poj 2893 M × N Puzzle(M*N數碼解的判定,使用逆序對)

連結:http://poj.org/problem?id=2893 M × N Puzzle Time Limit: 4000MS Memory Limit: 131072K Total Submissions: 4681 Accepted: 1269 Description

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:

1 6 2 4 0 3 7 5 9 10 8 11 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:

1 2 3 4 5 6 7 8 9 10 11 0 The following steps solve the puzzle given above.

START

1 6 2 4 0 3 7 5 9 10 8 11 DOWN ⇒

1 0 2 4 6 3 7 5 9 10 8 11 LEFT ⇒ 1 2 0 4 6 3 7 5 9 10 8 11 UP ⇒

1 2 3 4 6 0 7 5 9 10 8 11 …

RIGHT ⇒

1 2 3 4 0 6 7 5 9 10 8 11 UP ⇒

1 2 3 4 5 6 7 0 9 10 8 11 UP ⇒ 1 2 3 4 5 6 7 8 9 10 0 11 LEFT ⇒

1 2 3 4 5 6 7 8 9 10 11 0 GOAL

Given an M × N puzzle, you are to determine whether it can be solved.

Input

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

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

Sample Input

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 Sample Output

YES NO

題意:m*n大小的奇數碼有解判定 題解: 當N為奇數時,上下每交換一次逆序數改變偶次數,左右交換不變,目標逆序數為0,所以只要起始逆序數為偶數就行(劃到終點也為偶數,即目標局面的逆序數為偶數) 當N為偶數時,上下每交換一次逆序數改變奇次數,左右交換不變,目標逆序數為0,所以當0那一行離最低行(0最後在最低行)的行距+逆序對數為偶數就行(即兩者奇偶性相同)

#include<cstdio> 
#include<iostream>
#define ll long long
#define fo(i,j,n) for(register int i=j; i<=n; ++i)
using namespace std;
const int maxn = 1e6+5;
int n,m,N;
int a[maxn],buf[maxn],cnt;
inline void merge(int L,int R,int mid){
	int i=L,j=mid+1;
	fo(k,L,R){
		if(j>R || i<=mid&&a[i]<a[j])buf[k]=a[i++];
		else buf[k]=a[j++],cnt+=mid-i+1;
	}
	fo(k,L,R)a[k]=buf[k];
}
void MergeSort(int L,int R){
	if(L>=R)return;
	int mid = (L+R)>>1;
	MergeSort(L,mid);
	MergeSort(mid+1,R);
	merge(L,R,mid);
}
int main(){
	while(scanf("%d%d",&m,&n)&&(n||m)){
		N = m*n;
		int x,linex=0,k=0;
		fo(i,1,m)fo(j,1,n){
			scanf("%d",&x);
			if(x==0)linex=m-i;
			else a[++k]=x;
		}
		cnt = 0;
		MergeSort(1,k);
	//	fo(i,1,k)cout<<a[i]<<" ";
	
		if(n&1){ // 每行變換偶對 
			if(cnt&1)puts("NO");
			else puts("YES");
		}else{ // 每行變換奇對 
			if((linex^cnt)&1) puts("NO"); // 奇的話,^ 0,1為1 
			else puts("YES");
		} 

	}
	return 0;
}