奇数码问题
给定奇数版, 和两种状态A B
问能否有解使板A 变为板 B
例:
1 2 3
0 4 6
7 5 81 2 3
4 5 6
7 8 0
解: 将板A, B化为一维向量,
转化为逆序对问题
首先去掉位0
有 1.空格的左右移动不影响整个串的顺序
2.空格的上下移动必有等价与 swap(s[i], s[i - n - 1]) / swap(s[i], s[i + n - 1])
因为n - 1 为偶数, 所以逆序对的改变只能为偶数
由以上推导, 若A, B向量的 逆序对奇 偶性相同, 则必定可以转换得解
/*
Zeolim - An AC a day keeps the bug away
*/
//pragma GCC optimize(2)
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <sstream>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
const int MAXN = 1e6 + 10;
int arr[MAXN];
int brr[MAXN];
int revnum = 0;
void mergesort(int *arr, int fst, int lst, int *brr)
{
if(lst - fst > 1)
{
int mid = fst + (lst - fst) / 2;
int p = fst, q = mid, i = fst;
mergesort(arr, fst, mid, brr);
mergesort(arr, mid, lst, brr);
while(p < mid || q < lst)
{
if(q >= lst || (p < mid && arr[p] <= arr[q]))
{
brr[i++] = arr[p++];
}
else
{
brr[i++] = arr[q++];
revnum += mid - p;
}
}
for(i = fst; i < lst; i++)
arr[i] = brr[i];
}
}
int main()
{
//ios::sync_with_stdio(false);
//cin.tie(0); cout.tie(0);
//freopen("D://test.in", "r", stdin);
//freopen("D://test.out", "w", stdout);
int n;
while(cin >> n)
{
for(int i = 0, j = 0, y; i < n * n; ++i)
{
cin >> y;
if(y)
arr[j++] = y;
}
revnum = 0;
mergesort(arr, 0, n * n - 1, brr);
int ra = revnum;
for(int i = 0, j = 0, y; i < n * n; ++i)
{
cin >> y;
if(y)
arr[j++] = y;
}
revnum = 0;
mergesort(arr, 0, n * n - 1, brr);
int rb = revnum;
if((ra & 1) && (rb & 1) || (!(ra & 1) && !(rb & 1)))
cout<<"TAK\n";
else
cout<<"NIE\n";
}
return 0;
}