[UVA] The Morning after Halloween

题目:https://vjudge.net/problem/UVA-1601

#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<vector>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<queue>
#pragma warning(disable:4996)
using namespace std;
const int maxs = 20;
const int maxn = 150;
const int dx[] = { 0,0,-1,1,0 };
const int dy[] = { 1,-1,0,0,0 };

inline int ID(int a, int b, int c) {
	return (a << 16) | (b << 8) | c;
}

int s[3], t[3];
int deg[maxn], G[maxn][5];


inline bool ok(int a, int b, int a1, int b1)
{
	return a == b || (a1 == b && b1 == a);
}
int d[maxn][maxn][maxn];


int bfs()
{
	queue <int>q;
	memset(d, -1, sizeof(d));
	q.push(ID(s[0], s[1], s[2]));
	d[s[0]][s[1]][s[2]] = 0;
	while (!q.empty())
	{
		int n = q.front(); q.pop();
		int a = (n >> 16) & 0xff, b = (n >> 8) & 0xff, c = n & 0xff;
		if (a == t[0] && b == t[1] && c == t[2])return d[a][b][c];
		for (int i = 0; i < deg[a]; i++)
		{
			int na = G[a][i];
			for (int j = 0; j < deg[b]; j++)
			{
				int nb = G[b][j];

				if (ok(a, b, na, nb))continue;

				for (int k = 0; k < deg[c]; k++)
				{
					int nc = G[c][k];

					if (ok(a, c, na, nc))continue;
					if (ok(b, c, nb, nc))continue;

					if (d[na][nb][nc] != -1)continue;

					d[na][nb][nc] = d[a][b][c] + 1;
					q.push(ID(na, nb, nc));
				}
			}
		}
	}
	return -1;
}

int main()
{
	int h, w, n;
	while (scanf("%d%d%d\n", &w, &h, &n) == 3 && n)
	{
		char maze[20][20];
		for (int i = 0; i < h; i++)
			fgets(maze[i], 20, stdin);

		int cnt = 0, x[maxn], y[maxn], id[maxs][maxs];

		for (int i = 0; i < h; i++)
		{
			for (int j = 0; j < w; j++)
			{
				if (maze[i][j] != '#')
				{
					x[cnt] = i; y[cnt] = j;
					id[i][j] = cnt;
					if (islower(maze[i][j])) s[maze[i][j] - 'a'] = cnt;
					else if (isupper(maze[i][j])) t[maze[i][j] - 'A'] = cnt;
					cnt++;

				}
			}
		}


		for (int i = 0; i < cnt; i++)
		{
			deg[i] = 0;
			for (int j = 0; j < 5; j++)
			{
				int nx = x[i] + dx[j], ny = y[i] + dy[j];
				if (maze[nx][ny] != '#')
				{
					G[i][deg[i]++] = id[nx][ny];
			}
		}

		if (n <= 2) { deg[cnt] = 1; G[cnt][0] = cnt; s[2] = t[2] = cnt++; }
		if (n <= 1) { deg[cnt] = 1; G[cnt][0] = cnt; s[1] = t[1] = cnt++; }

		printf("%d\n", bfs());

	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值