CF1520G 题解
yangzixiao330522 · · 个人记录
CF1520G
题意
给定一个
现在小D想要从
- 在任意两个相邻且参数均不为
-1 的格子间移动,花费为w ; - 在有传送门的两个格子
(i,j) 和(x,y) 间移动,花费为a_{ij}+a_{xy} 。
求小D所需的最小花费。
思路
这是一道经典的BFS题目
我们可以将它分成两种方案讨论:
- 普通情况
先用一个
将目前的位置压入队列,然后走到下一个位置,每次判断走的地方有没有出界或者进墙,再次压入走到的位置,可得:
dis_{nxtx,nxty,id} = dis_{nowx,nowy,id} + k
最后再将这个位置标记为访问过的点。
- 传送门情况
如果有传送门时,令
mn1 = min(dis_{i,j,1} + a_{i,j}, mn1)
mn1 = min(dis_{i,j,2} + a_{i,j}, mn1)
答案就是
代码
#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();
}
}