走路
6 6 1 3 2 6 3 6 3 2 6 4 4 5
Sample Output
1<=n,m<1000
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <cstring> #include <string> #include <queue> using namespace std; const int N = 1e5 + 10; int h[N], n, m, tot; int a, b; struct node { int v, c, ne; } e[N]; void add(int u, int v, int c) { tot++; e[tot] = (node) { v, c, h[u] }; h[u] = tot; } int ff, rr, d[N], v[N], zz, l; queue<int>q; void spfa() { q.push(1); v[1] = 1; memset(d, 24, sizeof(d)); d[1] = 0; while (!q.empty()) { ff = q.front(); q.pop(); v[ff] = 0; for (int i = h[ff]; i; i = e[i].ne) { rr = e[i].v; if (d[rr] > d[ff] + e[i].c) { d[rr] = d[ff] + e[i].c; if (!v[rr]) v[rr] = 1, q.push(rr); } } } } int main() { scanf("%d%d", &n, &m); for (int i = 1, k; i <= m; ++i) { scanf("%d%d", &a, &b); add(a, b, 1); } spfa(); cout << d[n]; return 0; }
还是一道最短路模板题,此为SPFA代码