成仙之路−> 算法基础课题解
思路:
1. n = 150000, m = 150000, 稀疏图,适合用邻接表
2. 每次取出堆中的一个点,这个点就是距离最小点,放入已确定最短路集合 st
3. 更新这个点能到达的所有点的距离
4. 不用担心重边,st会帮你过滤掉
完整代码(堆优化版Dijkstra)
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 150010, INF = 0x3f3f3f3f;
int n,m;
int h[N],e[N],w[N],ne[N],idx;
int dist[N];
bool st[N];
void add(int a,int b,int c)
{
e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
int dijkstra()
{
//初始化距离
memset(dist,0x3f,sizeof dist);
//建立小根堆,第一元素是距离,第二元素是点
priority_queue<PII,vector<PII>,greater<PII>> heap;
heap.push({0,1});
while(heap.size())
{
//每次取出距离最小点
auto t=heap.top();
heap.pop();
int ver=t.second,distance=t.first;
//如果已经出现过则continue,可防止重边
if(st[ver]) continue;
st[ver]=true;
//遍历这个点可以到达的所有点
for(int i=h[ver];~i;i=ne[i])
{
int j=e[i];
if(distance+w[i]<dist[j])
{
dist[j]=distance+w[i];
heap.push({dist[j],j});
}
}
}
if(dist[n]==INF) return -1;
return dist[n];
}
int main()
{
cin>>n>>m;
//初始化邻接表
memset(h,-1,sizeof h);
//建边
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
cout<<dijkstra()<<endl;
return 0;
}
/* 堆优化版Dijkstra */ #include <bits/stdc++.h> using namespace std; typedef pair<int, int> PII; const int N = 150010, INF = 0x3f3f3f3f; int n, m; int h[N], e[N], w[N], ne[N], idx; int dist[N]; bool st[N]; void add(int a, int b, int c) { e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++; } int dijkstra() { memset(dist, 0x3f, sizeof dist); dist[1] = 0; priority_queue<PII, vector<PII>, greater<PII>> heap; heap.push({0, 1}); while (heap.size()) { auto t = heap.top(); heap.pop(); int ver = t.second, distance = t.first; if (st[ver]) continue; st[ver] = true; for (int i = h[ver]; ~i; i = ne[i]) { int j = e[i]; if (distance + w[i] < dist[j]) { dist[j] = distance + w[i]; heap.push({dist[j], j}); } } } if (dist[n] == INF) return -1; return dist[n]; } int main() { cin >> n >> m; memset(h, -1, sizeof h); while (m--) { int a, b, c; cin >> a >> b >> c; add(a, b, c); } cout << dijkstra() << endl; return 0; }