这是没有 log 的做法。
题目相当于判断两个排列的逆序对奇偶性是否一致(证明见其他题解)。
长度为 n 的排列逆序对奇偶性等于 n-c (c 表示置换环)。
排列的置换环是指将 i 向 p_i 连边后,会形成一个内向基环树森林,其中环的数量。
考虑证明。懒得证了,自己搜吧。
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=0;
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;
}
}
tot=0;
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;
}
}
puts(op[flg]);
}
return 0;
}说句闲话,其实这道题我一开始是想的蛇形排列,就是
1 2 3
6 5 4
7 8 0当作初始状态。
也能做,不过不变量就不是蛇形排列去掉 0 的逆序对奇偶性了,而是蛇形排列(包括 0 的)逆序对奇偶性异或上 0 的行列位置之和的奇偶性。record