习题7-11(uva-12569)

#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 = 1e6;
struct Node {
	Node() :robot(0), stone(0) {}
	Node(int a, int b) :robot(a), stone(b) {}
	int robot;//机器人位置
	int stone;//移动物标记
}node[maxm], res[maxm];

int vis[1 << maxn][maxn],n,m,s,t,before[maxm],cnt[maxm];
vector<int> g[maxn];


void printAns(int cur) {
	if (cur == 0) return;
	printAns(before[cur]);
	cout << res[cur].robot << " " << res[cur].stone << endl;
}

void bfs()
{
	int head = 0, tail = 1,over = (t - 1);

	memset(vis, 0, sizeof(vis));
	vis[node[0].stone][node[0].robot] = 1;

	before[0] = -1;
	cnt[0] = 0;

	Node cur;
	while (head < tail) {
		cur = node[head];
		if (cur.robot == over) {
			cout << cnt[head] << endl;
			printAns(head);
			return;
		}
		for (int i = 0; i < n; i++) {
			//检测当前二进制位是否有可以移动的对象
			if (!((1 << i) & cur.stone)) continue;
			for (int j = 0; j < g[i].size(); j++) {
				int a = g[i][j];
				//移动的位置是否是空位
				if(((1 << a) & cur.stone)) continue;
				//尝试添加到末尾
				Node& next = node[tail];
				next = cur;
				//如果是移动机器人 
				if (next.robot == i) next.robot = a;
				//更新 从 i 移动到 a
				next.stone = (next.stone & ~(1 << i)) | (1 << a);
				//是否访问过
				if(vis[next.stone][next.robot]) continue;

				vis[next.stone][next.robot] = 1;

				//记录前驱
				before[tail] = head;
				//记录行动轨迹
				res[tail] = Node(i+1, a+1);
				//记录长度
				cnt[tail] = cnt[head] + 1;

				++tail;
			}
		}
		++head;
	}
}
int main()
{
	int cnt, kcase = 0,temp,a,b;
	cin >> cnt;
	while (cnt--)
	{
		cin >> n >> m >> s >> t;
		//记录机器人位置
		node[0].robot =  (s - 1);
		//机器人和障碍物都是可以移动的
		node[0].stone = 1 << (s - 1);

		for (int i = 0; i < m; i++) {
			//添加障碍物
			cin >> temp;
			node[0].stone |= 1 << (temp - 1);
		}
		for (int i = 0; i < maxn; i++) g[i].clear();

		for (int i = 1; i < n; i++) {
			cin >> a >> b;
			g[a-1].push_back(b-1);
			g[b-1].push_back(a-1);
		}

		cout << "Case " << ++kcase << ": ";
		bfs();
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值