原题:http://poj.org/problem?id=2893
题解:
n*m的数码问题有一个结论:
1.假如m是奇数,那么上下交换会改变(m-1)也就是偶数次逆序数,左右交换(空格和左右交换)不改变逆序数,因此逆序数的奇偶性不变,此时两状态的奇偶性一致即有解
2.假如m是偶数,上下交换会改变奇数次逆序数,左右交换不改变逆序数,因此逆序数奇偶性会因上下交换而改变,此时逆序数之差和两个局面下空格所在行数之差 的奇偶性相同即有解。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1000 * 1000 + 7;
int num[maxn], sto[maxn];
long long ans; //ans 记得开longlong
void merge(int l, int r) {
if (l >= r) 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 &&num[i] <= num[j]) sto[k] = num[i++];
else {
sto[k] = num[j++];
ans += mid - i + 1;
}
}
for (int k = l; k <= r; k++) num[k] = sto[k];
}
int main() {
int n, m;
while (scanf("%d %d", &n, &m) , n&&m) {
int ind = 0,flag_n;
ans = 0;
for (register int i = 1; i <= n; i++) {
for (register int j = 1; j <= m; j++) {
int inp;
scanf("%d", &inp);
if (inp != 0) {
num[++ind] = inp;
}
else flag_n = n - i;
}
}
merge(1, ind);
if (m & 1) flag_n = 0; //假如m是奇数
if ((flag_n+ans)%2==0) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}