题目链接:https://www.nowcoder.com/acm/contest/105/F
刚开始以为直接用bfs就可以过了,但是不用优先队列的话只能过33.3%的样例,因为有的步数花费1秒,有的花费3秒,所以需要用优先队列取出花费时间最少的点,然后用了优先队列发现过了66.7%,然后看了别人的博客才知道,因为每个点放入队列里并不一定先走,也不一定是步数最少的点,所以在标记的时候,不应该在放入队列的时候标记,应该在取出队列的时候标记。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct Node{
int x,y,step;
bool operator < (const Node &a) const {
return step > a.step;
}
}S,E,Now,Next;
struct fun{
int Sx,Sy,Ex,Ey;
}Edge[1005];
char MAP[325][325];
int vis[325][325];
int dir[4][2] = {1,0,0,1,-1,0,0,-1};
int n,m,p;
bool in(int x,int y){
if(x >= 0 && y >= 0 && x < n && y < m && MAP[x][y] != '#' && vis[x][y] == 0){
return true;
}
return false;
}
int bfs(){
memset(vis,0,sizeof(vis));
priority_queue<Node> q;
S.step = 0;
q.push(S);
while(!q.empty()){
Now = q.top();
q.pop();
if(Now.x == E.x && Now.y == E.y){
return Now.step;
}
if(vis[Now.x][Now.y])continue;
vis[Now.x][Now.y] = 1;
for(int i=0;i<4;i++){
Next.x = Now.x + dir[i][0];
Next.y = Now.y + dir[i][1];
if(in(Next.x,Next.y)){
// vis[Next.x][Next.y] = 1;
Next.step = Now.step + 1;
q.push(Next);
}
}
for(int j=0;j<p;j++){
if(Now.x == Edge[j].Sx && Now.y == Edge[j].Sy){
Next.x = Edge[j].Ex;
Next.y = Edge[j].Ey;
if(in(Next.x,Next.y)){
// vis[Next.x][Next.y] = 1;
Next.step = Now.step + 3;
q.push(Next);
}
}
}
}
return -1;
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&p)){
for(int i=0;i<n;i++)scanf("%s",MAP[i]);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(MAP[i][j] == 'S'){
S.x = i;
S.y = j;
}
if(MAP[i][j] == 'T'){
E.x = i;
E.y = j;
}
}
}
for(int i=0;i<p;i++){
scanf("%d%d%d%d",&Edge[i].Sx,&Edge[i].Sy,&Edge[i].Ex,&Edge[i].Ey);
}
int temp = bfs();
printf("%d\n",temp);
}
return 0;
}