HDU 2612 Find a way

HDU 2612 Find a way

題目大意:
y和m要去肯德基聚餐,圖中有多個kfc,他們要選的那個kfc必須到彼此的所用時間之和最小,問最少需要多少時間。

題目思路:
將Y和M分開進行BFS,
然後根據二者到達KFC的時間總和,取用時最少的kfc
推薦與這題類似並且稍微複雜的題:UVA 11624

具體代碼:

#include<iostream>
#include<queue>
#include<cstdio>
#include<string>

using namespace std;

int step[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
int roads[205][205];
int cost_by_Y[205][205]; //表示Y到該處的時間
int cost_by_M[205][205];	//表示M到該處的時間
int visit[205][205];	
const int INF = 1e5;
int ans = INF;
int r, c;

void cmp_time()
{
	for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
		{
			if ( roads[i][j]==2) {
				if (cost_by_Y[i][j] + cost_by_M[i][j]<ans)	
				{
					ans = cost_by_Y[i][j] + cost_by_M[i][j];
				}
			}
		}
}
void bfs(int x, int y, int cost[][205])
{
	for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
			 cost[i][j]=INF,visit[i][j] = 0;//初始化
	queue<pair<int, int>> q;
	q.push(pair<int, int>(x, y));
	visit[x][y] = 1;
	cost[x][y] = 0;
	
	while (!q.empty())
	{
		pair<int, int> t = q.front();
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			int x = t.first, y = t.second;
			x += step[i][0], y += step[i][1];
			if (x >= 0 && x < r &&y >= 0 && y < c && !visit[x][y] && roads[x][y]) {
				visit[x][y] = 1;
				cost[x][y] = cost[t.first][t.second] + 1;
				q.push(pair<int, int>(x, y));
			}
		}
	}

}
int main()
{
	while (cin >> r >> c)
	{
		int x1, y1, x2, y2;
		for (int i = 0; i < r; i++)
		{
			string s;
			cin >> s;
			for (int j = 0; j < c; j++)
			{
				if (s[j] == '#')roads[i][j] = 0;
				else if (s[j] == '.')roads[i][j] = 1;
				else if (s[j] == '@')roads[i][j] = 2;
				else if (s[j] == 'Y') {
					roads[i][j] = 1;
					x1 = i, y1 = j;
				}
				else if(s[j]=='M'){
					roads[i][j] = 1;
					x2 = i, y2 = j;	
				}
			}
		}
		bfs(x1, y1, cost_by_Y);
		bfs(x2, y2, cost_by_M);
		cmp_time();
		printf("%d\n", ans * 11);
		ans = INF;
	}
	return 0;
}

發佈了69 篇原創文章 · 獲贊 34 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章