题目传送门
题目大意
伟大的人类创造了 3 种传送门,3 种传送门有着不同的传送效果,一个迷宫里除了墙有且只有这 3 种门可以方便移动。
题目思路
看到“传送”一格,且看到第三种门算作 2 步,立马可以想到迪杰斯特拉算法,每一种门对应者建不同边,边使用邻接表和数对存储,就可以当成一个很板子的单源最短路问题对待。
题目坑点
优先队列数对要记得步数在前,端点在后。而且,进迷宫也是一步喵。
题目代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=1.2e3+7;
using P=pair<int,int>;
char a[N][N];
int n,dis[N*N];
vector<P> G[N*N];
priority_queue <P,vector<P>,greater<P>> q;
int dx[100]={0,0,0,1,-1,0,0,2,-2,1,1,-1,-1};
int dy[100]={0,1,-1,0,0,2,-2,0,0,1,-1,1,-1};
bool check(int x,int y) {return x>=1&&x<=n&&y>=1&&y<=n&&a[x][y]!='*';}
void init() {
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cin>>a[i][j];
for(int x=1;x<=n;x++) {
for(int y=1;y<=n;y++) {
int pos1=(x-1)*n+y;
if(a[x][y]=='A') {
for(int op=1;op<=4;op++) {
int xx=x+dx[op];
int yy=y+dy[op];
int pos2=(xx-1)*n+yy;
if(check(xx,yy)) {
G[pos1].push_back({1,pos2});
}
}
}
else if(a[x][y]=='B') {
for(int op=5;op<=8;op++) {
int xx=x+dx[op];
int yy=y+dy[op];
int pos2=(xx-1)*n+yy;
if(check(xx,yy)) {
G[pos1].push_back({1,pos2});
}
}
}
else if(a[x][y]=='C') {
for(int op=9;op<=12;op++) {
int xx=x+dx[op];
int yy=y+dy[op];
int pos2=(xx-1)*n+yy;
if(check(xx,yy)) {
G[pos1].push_back({2,pos2});
}
}
}
}
}
}
int dij(int s) {
memset(dis,0x3f,sizeof(dis));
q.push({0,s});
dis[s]=0;
while(!q.empty()) {
auto t=q.top();
q.pop();
int u=t.second,uw=t.first;
for(auto nxt:G[u]) {
int v=nxt.second,vw=nxt.first;
if(uw+vw<dis[v]) {
dis[v]=uw+vw;
q.push({dis[v],v});
}
}
}
return dis[n*n];
}
signed main() {
cin>>n;
init();
int ans=min({dij(1),dij(n),dij((n-1)*n+1)});
if(ans!=4557430888798830399) cout<<ans+1;
else cout<<"No answer";
}题目总结
有时题目不一定只有一种解法喵,多想想别的思路。