题解
将这个拼图展开,可以发现:0左右移动不改变序列的逆序对数,上下移动改变的逆序对数和列数的奇偶性相反。
因此当列数是奇数时可以直接根据原序列逆序对数是不是偶数判断,列数是偶数时由于0上下移动引起对数的变化的奇偶性只和它始态行和终态行之间的距离有关,因此只需判断原序列逆序对数和这个距离的奇偶性是否相同即可。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using namespace std;
typedef long long ll;
int read(){
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar(); }
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
int n, m, a[1000005], b[1000005], dis;
ll ans;
void init(){
int cnt = 0;
for(int i = 0; i < n; ++i)
for(int j = 0; j < m; ++j){
a[cnt++] = read();
if(a[cnt - 1] == 0)
cnt--, dis = n - 1 - i;
}
}
void Merge(int ls, int rs, int re){
int lp = ls, rp = rs, tp = ls;
while(lp < rs && rp < re){
if(a[lp] <= a[rp]) b[tp++] = a[lp++];
else b[tp++] = a[rp++], ans += 1ll * (rs - lp);
}
while(lp < rs) b[tp++] = a[lp++];
while(rp < re) b[tp++] = a[rp++];
memcpy(a + ls, b + ls, sizeof(int) * (re - ls));
}
void ms(int l, int r){
int len = r - l, mid = (r + l) >> 1;
if(len == 1) return ;
ms(l, mid), ms(mid, r);
Merge(l, mid, r);
}
void solve(){
ans = 0;
ms(0, n * m - 1);
if(m & 1)
printf("%s\n", (ans % 2) ? "NO" : "YES");
else
printf("%s\n", (ans % 2 == dis % 2) ? "YES" : "NO");
}
int main(){
while(n = read(), m = read()){
init();
solve();
}
return 0;
}