使用优先权队列,每次选出距离值最小的顶点编号,对每条路径进行松弛
CodeForce20C 单向队列的简化spfa算法居然会超时,最后还是用了dijistra。
基础题。
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <queue>
#include <stack>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pii;
const int maxn=100050;
struct Edge
{
int u;
int v;
int w;
Edge(int from,int to,int weight)
{
u=from;
v=to;
w=weight;
}
};
vector<Edge> edge;
vector<int> G[maxn];
int n,m;
ll d[maxn],vis[maxn],pre[maxn],path[maxn];
int init()
{
for(int i=0;i<=n;i++)
G[i].clear();
edge.clear();
}
void dijistra(int s)
{
priority_queue<pii,vector<pii>,greater<pii> > pq;
memset(d,0x3f,sizeof(d));
memset(vis,0,sizeof(vis));
memset(pre,-1,sizeof(pre));
d[s]=0;
pq.push(pii(d[s],s));
while(!pq.empty())
{
pii e=pq.top();pq.pop();
int u=e.second;
if(vis[u]) continue;
vis[u]=1;
for(int i=0;i<G[u].size();i++)
{
Edge &e=edge[G[u][i]];
if(d[e.v]>d[e.u]+e.w)
{
d[e.v]=(ll)d[e.u]+e.w;
pre[e.v]=e.u;
pq.push(pii(d[e.v],e.v));
}
}
}
}
int main()
{
int u,v,w;
scanf("%d%d",&n,&m);
init();
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&u,&v,&w);
edge.push_back(Edge(u,v,w));
edge.push_back(Edge(v,u,w));
ll m=edge.size();
G[u].push_back(m-2);
G[v].push_back(m-1);
}
dijistra(1);
int k=n;
int nc=0;
path[nc++]=k;
while(pre[k]!=-1)
{
path[nc++]=pre[k];
k=pre[k];
}
if(k==1)
{
for(int i=nc-1;i>=0;i--)
printf("%lld ",path[i]);
}
else
printf("-1");
cout<<endl;
return 0;
}
基础不扎实,算法还是不熟。还有bellman_ford算法自己也还没有真正掌握。
本文介绍了一个基于Dijkstra算法实现的最短路径查找程序。通过使用优先级队列优化了算法效率,并提供了完整的C++代码实现及解析。文章还讨论了算法优化及Bellman-Ford算法的学习。
1682

被折叠的 条评论
为什么被折叠?



