题解SP13076[Silkar]
原题传送门
本题是一道双倍经验。
可以使用 BFS 搜索两遍:
- 搜索洪水到每个格子的时间。
- 搜索潘特到每个格子的时间并判断能否经过。
由于广搜搜到即最短,则一搜到终点就输出即可。
我用的是 STL 的 queue 与 pair ,基本上是模板题。
上代码:
#include<cstdio>
#include<queue>
#include<utility>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
const int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
int tm[50][50],r,c,ttt=1e9;
pair<int,int>stt,shlt;
bool vsd[50][50];
char mp[50][50];
queue<pair<pair<int,int>,int> >q;
int main()
{
memset(vsd,false,sizeof(vsd));
memset(tm,0x3f3f3f,sizeof(tm));
scanf("%d%d",&r,&c);
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
{
scanf(" %c",&mp[i][j]);
switch(mp[i][j])
{
case '*':q.push(make_pair(make_pair(i,j),0));break;
case 'S':stt=make_pair(i,j);break;
case 'D':shlt=make_pair(i,j);break;
}
}
while(!q.empty())
{
pair<pair<int,int>,int>qk=q.front();
q.pop();
for(int k=0;k<4;k++)
{
int xk=qk.first.first+dx[k],yk=qk.first.second+dy[k],tk=qk.second+1;
if(xk>=0&&xk<r&&yk>=0&&yk<c&&mp[xk][yk]=='.'&&!vsd[xk][yk])
{
vsd[xk][yk]=true;
tm[xk][yk]=min(tm[xk][yk],tk);
q.push(make_pair(make_pair(xk,yk),tk));
}
}
}
memset(vsd,false,sizeof(vsd));
q.push(make_pair(stt,0));
while(!q.empty())
{
pair<pair<int,int>,int>qk=q.front();
q.pop();
for(int k=0;k<4;k++)
{
int xk=qk.first.first+dx[k],yk=qk.first.second+dy[k],tk=qk.second+1;
if(make_pair(xk,yk)==shlt)
ttt=min(ttt,tk);
if(xk>=0&&xk<r&&yk>=0&&yk<c&&mp[xk][yk]=='.'&&!vsd[xk][yk]&&tk<tm[xk][yk])
{
vsd[xk][yk]=true;
q.push(make_pair(make_pair(xk,yk),tk));
}
}
}
if(ttt==1e9)
printf("KAKTUS");
else
printf("%d",ttt);
return 0;
}
其中有几个要注意的点:
- 要讲初始时间设为一个很大的数而不是 0 。
- switch 语句后要加 break !!!
- 保存后要标记,避免重复搜索导致 TLE 。
- 要将队列中的保存下来后再弹出,且要在循环前先弹出,否则可能把刚加入的弹出。
- 能否取等要注意。
- 走到 D 后不能直接输出。
望点赞