模拟队列
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 100010;
int n, m;
int h[N], ne[N], e[N], idx;
int d[N];
int q[N]; // queue<int> q;
void add (int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
int bfs()
{
memset(d, -1, sizeof d);
d[1] = 0;
q[0] = 1; // q.push(1);
int hh = 0, tt = 0;
while(hh <= tt)
{
int t = q[hh ++ ]; // auto t = q.front(); q.pop();
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (d[j] == -1) // j点还没被扩展
{
d[j] = d[t] + 1;
q[ ++ tt] = j; // q,push(j);
}
}
}
return d[n];
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
while(m -- )
{
int a, b;
cin >> a >> b;
add(a, b);
}
cout << bfs() << endl;
return 0;
}
stl队列
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int N = 100010;
int n, m;
int h[N], ne[N], e[N], idx;
int d[N];
void add (int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
int bfs()
{
memset(d, -1, sizeof d);
queue<int> q;
d[1] = 0;
q.push(1);
while(q.size())
{
auto t = q.front();
q.pop();
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (d[j] == -1) // j点还没被扩展
{
d[j] = d[t] + 1;
q.push(j);
}
}
}
return d[n];
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
while(m -- )
{
int a, b;
cin >> a >> b;
add(a, b);
}
cout << bfs() << endl;
return 0;
}
我的笨蛋思路,堆优化版dijkstra(),边权都是1~
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int N = 1e6 + 10;
int n, m;
int h[N], ne[N], e[N], idx, w[N];
int dist[N];
bool st[N];
typedef pair<int, int> PII;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
int dijkstra()
{
memset(dist, 0x3f, sizeof dist);
priority_queue<PII, vector<PII>, greater<PII>> heap;
dist[1] = 0;
heap.push({0, 1});
while(heap.size())
{
auto t = heap.top();
heap.pop();
int ver = t.second;
st[ver] = true;
for (int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[ver] + 1) // !st[ver]
{
dist[j] = dist[ver] + 1;
heap.push({dist[j], j});
}
}
}
if (dist[n] == 0x3f3f3f3f) return -1;
else return dist[n];
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
memset(w, 1, sizeof w);
while(m -- )
{
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
}
cout << dijkstra() << endl;
return 0;
}