习题7-12(uva-1533)

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值