CF1520G
题意
给定一个 的网格,每个格子 都有一个整数参数 , 表示这个格子不能通过;否则,这个格子可以通过,若 则表示这个格子内有一个传送门。
现在小D想要从 移动到到 ,它可以以如下两种方式移动:
- 在任意两个相邻且参数均不为的格子间移动,花费为 ;
- 在有传送门的两个格子 和 间移动,花费为 。
求小D所需的最小花费。
思路
这是一道经典的BFS题目
我们可以将它分成两种方案讨论:
- 普通情况
先用一个 数组来储存走到 时的花费,用 数组来储存访问过的点。
将目前的位置压入队列,然后走到下一个位置,每次判断走的地方有没有出界或者进墙,再次压入走到的位置,可得:
最后再将这个位置标记为访问过的点。
- 传送门情况
如果有传送门时,令 为起点走到此处的花费和传送的花费, 为终点走到此处的花费和传送的花费:
答案就是 和 的最小值。
代码
#include <bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int maxn = 2e6 + 5;
int a[2005][2005];
ll dis[2005][2005][3], vis[2005][2005][3];
const ll INF = 1e18;
int n,m ,k;
int dx[4] = {0,0,-1,1};
int dy[4] = {1,-1,0,0};
bool check(int x, int y, int id) {
if (x < 1 || y < 1 || x > n || y > m) return false;
if (vis[x][y][id]) return false;
if (a[x][y] == -1) return false;
return true;
}
void bfs(int x, int y, int id) {
queue<pair<int,int> > q;
q.push({x, y});
dis[x][y][id] = 0;
vis[x][y][id] = true;
while (!q.empty()) {
int nowx = q.front().first, nowy = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int nxtx = nowx + dx[i], nxty = nowy + dy[i];
if (check(nxtx, nxty, id)) {
q.push({nxtx, nxty});
dis[nxtx][nxty][id] = dis[nowx][nowy][id] + k;
vis[nxtx][nxty][id] = true;
}
}
}
}
void solve(){
cin >> n >> m >> k;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++){
cin >> a[i][j];
dis[i][j][1] = dis[i][j][2] = INF;
}
}
bfs(1,1,1);
bfs(n,m,2);
ll mn1 = INF, mn2 = INF, ans = dis[n][m][1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (a[i][j] > 0) {
mn1 = min(dis[i][j][1] + a[i][j], mn1);
mn2 = min(dis[i][j][2] + a[i][j], mn2);
}
}
}
ans = min(ans, mn1 + mn2);
if (ans == INF) cout << -1 << endl;
else cout << ans << endl;
}
int main() {
ios::sync_with_stdio(0);
int T = 1;
// cin >> T;
while(T--) {
solve();
}
}