#关于为什么要说这道题
TNND,在luogu上提交了6次才过
qwq,细节真的太重要了
#
##题目意思呢其实也挺好懂,一个起点,一个终点,可以用传送门,输出最短路
##因为每次移动距离都是w,实际上就是看看哪个先到达,哪个近,然后用BFS话还挺好做的
首先思路就是看下能不能直达,用ans存下
然后分别找下距离两个点最近的传送门,加起来与ans比较下,取小就行
#废话不多说,直接上AC代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<map>
#include<queue>
#include<vector>
#define endl "\n"
using namespace std;
typedef long long ll;
typedef vector<int> VI;
typedef vector<int,int>VII;
typedef pair<int,int> PII;
typedef double db;
const ll MOD = 998244353;
const ll inf = 0x3f3f3f3f3f3f3f3f;
const int maxn = 2005;
ll mp[maxn][maxn],vis[maxn][maxn];
int n,m;
ll w,ans;
struct point{
int x;
int y;//所在坐标及到达的距离
ll step;//到这个点最短路
bool operator<(const point&a)const{return step>a.step;}定义排序
}p;
ll dx[] = {1,0,0,-1};
ll dy[] = {0,1,-1,0};
priority_queue<point>v;
// ll gcd(ll a,ll b){ return b ? gcd(b,a%b):a;}
void BFS(int sx,int sy){
queue<point>q;//申请队列
memset(vis,0,sizeof(vis));//一定要初始化!!!qwq
p.x = sx;
p.y = sy;
p.step = 0;
q.push(p);
vis[sx][sy] = 1;
while(!q.empty()){
int x = q.front().x;
int y = q.front().y;
ll step = q.front().step;
q.pop();
if(x == n && y == m)ans = min(ans,step);因为改动后的BFS这里并没有返回,所以直达的ans取小
if(mp[x][y]>0){
p.x = x;
p.y = y;
p.step = step+mp[x][y];
v.push(p);//可以到达的传送门
}
for(int i = 0;i<4;i++){
int tx = x+dx[i];
int ty = y+dy[i];
if( vis[tx][ty] )continue;
if(mp[tx][ty]!=-1 && tx<=n&&tx>=1&&ty<=m&&ty>=1){
p.x = tx;
p.y = ty;
p.step = step+w;
q.push(p);
vis[tx][ty] = 1;
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
// memset(mp,-1,sizeof(mp));
cin >> n >> m >> w;
for(int i = 1;i<=n;i++)
for(int j = 1;j<=m;j++)
cin >> mp[i][j];
// cin >> sx >> sy >> ex >> ey;//起终点
BFS(n,m);
ll a1 = -1;
if(!v.empty())a1 = v.top().step;//离(n,m)最近的传送门在优先队列里面就是第一个了
while(!v.empty())v.pop();清空v
ans = inf;//是否能直接到达
BFS(1,1);
// cout << ans << endl;
ll a2 = -1;
if(!v.empty()){
a2 = v.top().step;//离(1,1)最近的传送门
}
// cout << a1 << endl;
// cout << a2 << end;
// cout << ans << endl;
ll res = a1+a2;
if(a1!=-1 && a2!=-1){
if(ans != inf)res = min(ans,res);
cout << res << endl;
}
else if(ans != inf)cout << ans << endl;
else cout << -1 << endl;
return 0;
}
其实注释已经很详细了,回头来看这道题其实还蛮简单的,但我还是不够细心,错了好多次,qwq,因此写下来提醒我自己,如果有任何不正之处,还请各位雅正。