2019 拖拉机
(Acwing 2019)[https://www.acwing.com/problem/content/2021/]
算法:bfs双端队列 —— 0/1边权的dijkstra,边权为1的push_back(),边权为0的时候push_front(),可以证明队列中前面的部分优于后面的部分。
图解

代码:
/*************************************************************************
> File Name: 2019.cpp
> Author: Ansary
> Created Time: 2022/3/3 14:24:47
************************************************************************/
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>
#include <deque>
using namespace std;
const int N = 1004;
#define pii pair<int, int>
#define x first
#define y second
int map[N][N];
int vis[N][N];
int dis[N][N];
int d[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
void bfs(int x, int y){
deque<pii> q;
q.push_front({x, y});
memset(dis, 0x3f3f3f3f, sizeof dis);
dis[x][y] = 0;
while(!q.empty()){
auto now = q.front();
q.pop_front();
if(vis[now.x][now.y] == 1)
continue;
vis[now.x][now.y] = 1;
for(int i = 0; i < 4; i++){
int nowx = now.x + d[i][0];
int nowy = now.y + d[i][1];
if(nowx < 0 || nowx > N - 2 || nowy < 0 || nowy > N - 2)
continue;
if(dis[nowx][nowy] > dis[now.x][now.y] + map[nowx][nowy]){
dis[nowx][nowy] = dis[now.x][now.y] + map[nowx][nowy];
if(map[nowx][nowy] == 1)
q.push_back(make_pair(nowx, nowy));
else
q.push_front(make_pair(nowx, nowy));
}
}
}
}
int main(){
int n, sx, sy;
cin >> n >> sx >> sy;
for(int i = 1; i <= n; i++){
int a, b;
cin >> a >> b;
map[a][b] = 1;
}
bfs(sx, sy);
cout << dis[0][0] << endl;
}

浙公网安备 33010602011771号