HDU 2579 - Dating with girls(2)

传送门HDU 2579 - Dating with girls(2)


看到这题我就想到了UVa 10047 - The Monocycle


只是上一题更复杂一点。

也是用优先队列。

这时候的状态比一般的状态还要多一个,即秒数,所以要开一个三维数组。


A了之后看了很多解题报告,都是直接用队列,但是个人感觉不太靠谱。原因和上面提到的那题一样。


#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int dir[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

struct POINT
{
	friend bool operator< (const POINT &a, const POINT &b)
	{
		return a.sec > b.sec;
	}
	int x, y;
	int sec;
};

priority_queue<POINT> qu;
POINT start, target;
char maze[110][110];
int ans, row, col, k, vis[110][110][12];

bool BFS();

int main()
{
	//freopen("input.txt", "r", stdin);
	int i, j, T;
	scanf("%d", &T);
	while (T--)
	{
		memset(vis, 0, sizeof(vis));
		scanf("%d%d%d%*c", &row, &col, &k);
		for (i = 0; i < row; i++)
			gets(maze[i]);
		for (i = 0; i < row; i++)
			for (j = 0; j < col; j++)
			{
				if (maze[i][j] == 'Y')
					start.x = i, start.y = j;
				if (maze[i][j] == 'G')
					target.x = i, target.y = j;
			}
		bool flag = BFS();
		if (!flag)
			printf("Please give me another chance!\n");
		else
			printf("%d\n", ans);
	}
	return 0;
}

bool BFS()
{
	while (!qu.empty())
		qu.pop();
	start.sec = 0;
	qu.push(start);
	vis[start.x][start.y][0] = 1;
	while (!qu.empty())
	{
		POINT cur = qu.top();
		qu.pop();
		for (int i = 0; i < 4; i++)
		{
			POINT temp;
			bool inFlag = false;
			int dx = cur.x + dir[i][0];
			int dy = cur.y + dir[i][1];
			int ds = cur.sec + 1;
			if (dx >= 0 && dx < row && dy >= 0 && dy < col)	//如果没越界
			{
				temp.x = dx, temp.y = dy, temp.sec = ds;
				if (maze[dx][dy] == '#')	//如果是‘#’,只有在倍数的情况下,且没有被访问过,可以进。
				{
					if (ds % k == 0)
					{
						if (!vis[dx][dy][ds % k])
						{
							inFlag = true;
							qu.push(temp);
							vis[dx][dy][ds % k] = 1;
						}
					}
				}
				else	//如果不是墙
					if (!vis[dx][dy][ds % k])	//if three states are different, push into the queue
					{
						inFlag = true;
						qu.push(temp);
						vis[dx][dy][ds % k] = 1;
					}
				if (inFlag)
					if (temp.x == target.x && temp.y == target.y)
					{
						ans = temp.sec;
						return true;
					}
			}
		}
	}
	return false;
}



你可能感兴趣的:(ACM,HDU)