Problem 37: 拯救ice-cream
Time Limit:1 Ms| Memory Limit:128 MB
Difficulty:3
Description
天好热……Tina顶着那炎炎的烈日,向Ice-cream home走去……
可是……停电了……
冰淇淋们躺在Ice-cream home的冰柜里,慢慢地……慢慢地……融化…………
你说,她能赶在冰淇淋融化完之前赶到Ice-cream home去吗?
给你一张坐标图,s为Tina的初始位置,m为Ice-cream home的位置,‘.’为路面,Tina在上面,每单位时间可以移动一格;‘#’为草地,Tina在上面,每两单位时间可以移动一格(建议不要模仿—毕竟Tina还小);‘o’是障碍物,Tina不能在它上面行动。也就是说,Tina只能在路面或草地上行走,必须绕过障碍物,并到达冰淇淋店。但是…………不保证到达时,冰淇淋还未融化,所以……就请聪明的你……选择最佳的方案啦…………如果,Tina到的时候,冰淇淋已经融化完了,那她可是会哭的。
可是……停电了……
冰淇淋们躺在Ice-cream home的冰柜里,慢慢地……慢慢地……融化…………
你说,她能赶在冰淇淋融化完之前赶到Ice-cream home去吗?
给你一张坐标图,s为Tina的初始位置,m为Ice-cream home的位置,‘.’为路面,Tina在上面,每单位时间可以移动一格;‘#’为草地,Tina在上面,每两单位时间可以移动一格(建议不要模仿—毕竟Tina还小);‘o’是障碍物,Tina不能在它上面行动。也就是说,Tina只能在路面或草地上行走,必须绕过障碍物,并到达冰淇淋店。但是…………不保证到达时,冰淇淋还未融化,所以……就请聪明的你……选择最佳的方案啦…………如果,Tina到的时候,冰淇淋已经融化完了,那她可是会哭的。
Input
依次输入冰淇淋的融化时间t(0<t<1000),坐标图的长x,宽y(5<=x,y<=25){太长打起来好累……},和整张坐标图。
Output
判断按照最优方案是否可以赶在冰淇淋融化之前到达冰淇淋店(注:当T=最优方案所用时间,则判断为未赶到),如赶到,输出所用时间;如未赶到,输出Tina的哭声——“55555”(不包括引号)。
Sample Input
11
10
8
......s...
..........
#ooooooo.o
#.........
#.........
#.........
#.....m...
#.........
10
8
......s...
..........
#ooooooo.o
#.........
#.........
#.........
#.....m...
#.........
Sample Output
10
思路: 优先级队列+广搜, 较简单, 注意优先级队列的使用,运算符>的重载(与sort、qsort的重载正好相反), 就当个模板用吧~
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
#define MAX 30
using namespace std;
struct pos
{
int x;
int y;
int step;
// friend bool operator<(const pos &a, const pos &b) //和放在外面是一样的
// {
// return a.step > b.step;
// }
};
bool operator<(const pos &a, const pos &b)
{
return a.step > b.step;
}
pos sp, ep;
char map[MAX][MAX];
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}, m, n, ti;
int bfs()
{
priority_queue<pos> q;
pos temp, t;
temp = sp;
temp.step = 0;
q.push(temp);
while(!q.empty())
{
temp = q.top();
q.pop();
if(temp.step >= ti)
{
continue;
}
if(temp.x == ep.x && temp.y == ep.y && temp.step < ti)
{
return temp.step;
}
for(int i = 0; i < 4; i++)
{
t.x = temp.x + dir[i][0];
t.y = temp.y + dir[i][1];
if(t.x >= 0 && t.x < n && t.y >= 0 && t.y < m && map[t.x][t.y] != 'o')
{
if(map[t.x][t.y] == '.')
{
t.step = temp.step + 1;
map[t.x][t.y] = 'o';
q.push(t);
}
else if(map[t.x][t.y] == '#')
{
t.step = temp.step + 2;
map[t.x][t.y] = 'o';
q.push(t);
}
else if(map[t.x][t.y] == 'm')
{
t.step = temp.step + 1;
map[t.x][t.y] = 'o';
q.push(t);
}
}
}
}
return -1;
}
int main()
{
scanf("%d%d%d", &ti, &m, &n);
int ans;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
cin>>map[i][j];
if(map[i][j] == 's')
{
sp.x = i;
sp.y = j;
}
if(map[i][j] == 'm')
{
ep.x = i;
ep.y = j;
}
}
}
ans = bfs();
if(ans == -1)
{
printf("55555\n");
}
else
{
printf("%d\n", ans);
}
return 0;
}