#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
const int maxn = 15, maxm = 6, maxc = 65536, flag[maxn][maxm] ={
{-1,-1,-1,-1,2,3},{-1,1,-1,3,4,5},{1,-1,2,-1,5,6},
{-1,2,-1,5,7,8},{2,3,4,6,8,9},{3,-1,5,-1,9,10},
{-1,4,-1,8,11,12},{4,5,7,9,12,13},{5,6,8,10,13,14},
{6,-1,9,-1,14,15},{-1,7,-1,12,-1,-1},{7,8,11,13,-1,-1},
{8,9,12,14,-1,-1},{9,10,13,15,-1,-1},{10,-1,14,-1,-1,-1}
};
struct Node
{
int state;
int path[20][2];
int nstep;
int cnt;
}q[maxc];
int vis[1 << maxn],n,ans;
bool bfs(int start)
{
Node before,cur;
q[0].cnt = 1;
q[0].nstep = 0;
q[0].state = start;
int front = 0, tail = 1,temp;
while (front < tail) {
before = q[front];
for (int i = 0; i < maxn; i++) {
if(! (before.state & (1 << i)) ) continue;
for (int j = 0; j < 6; j++) {
temp = i,cur = before;
if(flag[i][j] == -1 || !(cur.state & (1 << (flag[i][j] - 1)))) continue;
while (temp >= 0 && (cur.state & (1 << temp))) {
cur.state ^= (1 << temp);
temp = flag[temp][j] - 1;
cur.cnt++;
}
if (temp < 0) continue;
cur.state |= (1 << temp);
if(vis[cur.state]) continue;
cur.nstep = before.nstep + 1;
cur.path[cur.nstep][0] = i;
cur.path[cur.nstep][1] = temp;
cur.cnt--;
if (cur.cnt == 14 && cur.state & (1 << (n - 1))) {
cout << cur.nstep << endl << cur.path[1][0] + 1 << " " << cur.path[1][1] + 1;
for (int k = 2; k <= cur.nstep; k++)
cout << " " << cur.path[k][0] + 1 << " " << cur.path[k][1] + 1;
cout << endl;
return true;
}
vis[cur.state] = 1;
q[tail] = cur;
++tail;
}
}
++front;
}
return false;
}
int main()
{
int t;
cin >> t;
while (t--) {
cin >> n;
memset(vis, 0, sizeof(vis));
int state = ((1 << 15) - 1) ^ (1 << (n - 1));
vis[state] = 1;
if (!bfs(state)) cout << "IMPOSSIBLE" << endl;
}
return 0;
}
习题7-12(uva-1533)
最新推荐文章于 2021-04-05 14:15:13 发布