题解:P10454 奇数码问题

· · 题解

这是 O(n^2) 的做法。目前除了打表哥外是最优解。

题目相当于判断两个排列的逆序对奇偶性是否一致(证明见其他题解)。

长度为 n 的排列逆序对奇偶性等于 n-c 的奇偶性 (c 表示置换环)。

考虑证明。见 patricky 的博客。

code:

#include<bits/stdc++.h>
using namespace std;
static char buf[100005],*pa(buf),*pb(buf);
#define gc (pa==pb and (pb=(pa=buf)+fread(buf,1,100000,stdin),pa==pb)?EOF:*pa++)
inline int read(){
    int x=0;
    char c=gc;
    for(;c<'0' or c>'9';c=gc)if(c==EOF)return 0;
    for(;c>='0' and c<='9';c=gc)
        x=x*10+c-'0';
    return x;
}
int a[250005];
char *op[2]={"TAK","NIE"};
int n;
signed main(){
    while(n=read()){
        int tot=0;
        for(int i=1;i<=n;i++)
            for(int j=1,x;j<=n;j++)
                if(x=read())a[++tot]=x;
        bool flg=n&1;
        for(int i=1;i<=tot;i++){
            if(a[i]){
                for(int j=a[i];j;tie(j,a[j])=tuple(a[j],0));
                flg^=1;
            }
        }
    //此时 flg 等于第一个排列的奇偶性。
        tot=0;
    flg^=n&1;
        for(int i=1;i<=n;i++)
            for(int j=1,x;j<=n;j++)
                if(x=read())a[++tot]=x;
        for(int i=1;i<=tot;i++){
            if(a[i]){
                for(int j=a[i];j;tie(j,a[j])=tuple(a[j],0));
                flg^=1;
            }
        }
    //从上一条注释到现在,flg 异或了第二个排列的奇偶性。
        puts(op[flg]);
    }
    return 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 0

会提取排列 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16 21 22 23 24 0。

也能做,不过不变量就不是排列去掉 0 的逆序对奇偶性了,而是蛇形排列(包括 0 的)逆序对奇偶性异或上 0 的行列位置之和的奇偶性。AC record。