AcWing 847. 图中点的层次(同dijkstra求最短路II)
原题链接
简单
作者:
jiaoyp
,
2025-04-01 10:39:51
· 江苏
,
所有人可见
,
阅读 3
#include <bits/stdc++.h>
using namespace std;
const int N = 1E5 + 10;
int h[N], e[N], ne[N], idx;
int d[N];
int st[N];
int n, m;
typedef pair<int, int> PII;
priority_queue<PII, vector<PII>, greater<PII>> q;
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
memset(d, 0x3f, sizeof d);
for(int i = 0; i < m; i ++)
{
int a, b;
cin >> a >> b;
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
q.push({0, 1});
st[1] = 1;
d[1] = 0;
while(q.size())
{
auto t = q.top();
q.pop();
int a = t.first, b = t.second;
st[b] = 0;
for(int i = h[b]; i != -1; i = ne[i])
{
int j = e[i];
if(!st[j] and d[j] > a + 1)
{
d[j] = a + 1;
q.push({d[j], j});
st[j] = 1;
}
}
}
if(d[n] == 0x3f3f3f3f)
cout << -1;
else
cout << d[n];
}