1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #include <bits/stdc++.h> using namespace std; using PII = pair<int, int>; const int N = 100001; int n, m, x, y, dist[N]; vector<PII> g[N]; priority_queue<PII, vector<PII>, greater<PII>> q; int main() { scanf("%d%d", &n, &m); while (m--) { scanf("%d%d", &x, &y); g[x].emplace_back(y, 0); g[y].emplace_back(x, 1); } memset(dist, 0x3f, sizeof(dist)); q.emplace(0, 1); dist[1] = 0; while (q.size()) { auto p = q.top(); q.pop(); int d = p.first, u = p.second; for (auto &x : g[u]) { int v = x.first, w = x.second; if (dist[v] > d + w) { dist[v] = d + w; q.emplace(dist[v], v); } } } printf("%d\n", dist[n] == 0x3f3f3f3f ? -1 : dist[n]); return 0; }
|