题意:在迷宫中,王子Y想要到达公主C的位置,迷宫中有障碍#,收费站*,传送点P。对于收费站,输入给出所收费用cost;对于传送点,可以选择传送到任意其他的传送点,或者不传送。要求让路径花费最小,输出最小花费。
思路:优先队列BFS,访问到一个P点时把所有P点标记下并将所有P点附近的没被标记的点入队。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
#define maxc 5005
#define INF 0x7fffffff
char Maze[maxc][maxc];
int PX[maxc],PY[maxc];
bool Vis[maxc][maxc];
int Dir[4][2]={-1,0,0,1,1,0,0,-1};
int r,c,PCnt;
bool flag;
struct Node
{
int x,y,cost;
Node()
{}
Node(int x,int y,int cost)
{
this->x=x,this->y=y,this->cost=cost;
}
};
struct cmp
{
bool operator()(Node &a,Node &b)
{
return a.cost>b.cost;
}
};
bool Isbound(int i,int j)
{
return i<1||i>r||j<1||j>c;
}
void Init()
{
memset(Vis,false,sizeof(Vis));
PCnt=0;
flag=false;
}
int BFS(int sx,int sy)
{
priority_queue<Node,vector<Node>,cmp> q;
q.push(Node(sx,sy,0));
Vis[sx][sy]=true;
Node node;
int tx,ty,cost,i,j;
while(!q.empty())
{
node=q.top();
q.pop();
if(Maze[node.x][node.y]=='C')
return node.cost;
else if(Maze[node.x][node.y]=='*'||Maze[node.x][node.y]=='Y')
{
for(i=0;i<4;++i)
{
tx=node.x+Dir[i][0];
ty=node.y+Dir[i][1];
if(!Isbound(tx,ty)&&!Vis[tx][ty])
{
if(Maze[tx][ty]=='*')
q.push(Node(tx,ty,node.cost+1));
else
q.push(Node(tx,ty,node.cost));
Vis[tx][ty]=true;
}
}
}
else
{
// if(!flag) //节省50ms...
// {
for(i=0;i<PCnt;++i)
{
Vis[PX[i]][PY[i]]=true;
for(j=0;j<4;++j)
{
tx=PX[i]+Dir[j][0];
ty=PY[i]+Dir[j][1];
if(!Isbound(tx,ty)&&!Vis[tx][ty])
{
if(Maze[tx][ty]=='*')
q.push(Node(tx,ty,node.cost+1));
else if(Maze[tx][ty]=='C')
q.push(Node(tx,ty,node.cost));
Vis[tx][ty]=true;
}
}
}
// flag=true;
// }
}
}
return INF;
}
int main()
{
int i,j,b,sx,sy,ans;
while(scanf("%d %d %d",&r,&c,&b)!=EOF)
{
Init();
for(i=1;i<=r;++i)
{
getchar();
for(j=1;j<=c;++j)
{
scanf("%c",&Maze[i][j]);
if(Maze[i][j]=='Y')
sx=i,sy=j;
else if(Maze[i][j]=='#')
Vis[i][j]=true;
else if(Maze[i][j]=='P')
PX[PCnt]=i,PY[PCnt++]=j;
}
}
ans=BFS(sx,sy);
if(ans==INF)
printf("Damn teoy!\n");
else
printf("%d\n",ans*b);
}
return 0;
}