堆优化版Dijkstra()算法 最短路
无向图记得要建两条边,边数x2
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 2510, M = 6210 * 2;
typedef pair<int,int> PII;
int n,m,rs,rt;
int h[N],e[M],w[M],ne[M],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;
dist[rs]=0;
heap.push({0,rs});
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!=-1;i=ne[i])
{
int j=e[i];
if(dist[j] > distance + w[i])
{
dist[j] = distance + w[i];
heap.push({dist[j],j});
}
}
}
return dist[rt];
}
int main()
{
memset(h,-1,sizeof h);
cin>>n>>m>>rs>>rt;
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c),add(b,a,c); // 无向图建两条边
}
cout<<dijkstra();
return 0;
}
spfa
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 2510, M = 6210 * 2; // 无向图,边数开2倍
int n,m,rs,rt;
int h[N],e[M],w[M],ne[M],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++;
}
void spfa()
{
memset(dist,0x3f,sizeof dist);
dist[rs]=0;
queue<int> q;
q.push(rs);
st[rs]=true;
while(q.size())
{
int t=q.front();
q.pop();
st[t]=false; // 出队
for(int i=h[t];i!=-1;i=ne[i])
{
int j=e[i];
if(dist[j] > dist[t] + w[i])
{
dist[j]=dist[t] + w[i];
if(!st[j])
{
q.push(j);
st[j]=true;
}
}
}
}
}
int main()
{
cin>>n>>m>>rs>>rt;
memset(h,-1,sizeof h);
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c),add(b,a,c); // 无向图记得建两条边
}
spfa();
cout<<dist[rt];
return 0;
}