大家好,又见面了,我是你们的朋友全栈君。
十分基础的Dijkstra算法
详见代码
#define maxn 100000
#define maxm 100000
using namespace std;
const int INF=999999999;
struct HeapNode
{
int d,u;
bool operator < (const HeapNode& rhs) const
{
return d>rhs.d;
}
};
struct Edge
{
int from,to,dist;
Edge(int u,int v,int d):from(u),to(v),dist(d) {}
};
struct Dijkstra
{
int n,m;
vector<Edge> edges;
vector<int> G[maxn];
bool done[maxn];//是否用过(永久标号)
int d[maxn];//s到各个点的距离 (dist)
int p[maxn];//最短路上的一条边 (path)
void init(int n)
{
this->n=n;
for(int i=0;i<n;i++)
{
G[i].clear();
}
edges.clear();
}
void AddEdge(int from,int to,int dist)
{
edges.push_back(Edge(from,to,dist));
m=edges.size();
G[from].push_back(m-1);
}
void dijkstra(int s)
{
priority_queue<HeapNode> Q;
for(int i=0;i<n;i++)
{
d[i]=INF;
}
d[s]=0;
memset(done,0,sizeof(done));
Q.push((HeapNode){0,s});
while(!Q.empty())
{
HeapNode x=Q.top();
Q.pop();
int u=x.u;
if(done[n])
{
continue;
}
done[u]=true;
for(int i=0;i<G[u].size();i++)
{
Edge& e=edges[G[u][i]];
if(d[e.to]>d[u]+e.dist)
{
d[e.to]=d[u]+e.dist;
p[e.to]=G[u][i];
Q.push((HeapNode){d[e.to],e.to});
}
}
}
}
};
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/139191.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有