迪杰斯特拉算法
哈喽,大家好,我是赏月君,今天做一下图论的题目——迪杰斯特拉算法,废话少说,上题目。
题目描述
求最短路权值和。
输入
输入数据以下面的格式:
|V| |E| r
s0 t0 d0
s1 t1 d1
s|E|-1 t|E|-1 d|E|-1
其中IV|是图顶点的数量,|E|是图中的边的数量。 r是起点。
si和ti表示第i条边(有向)的源点和终点,di表示第i条边的权值。
1≤|V|≤100000
0≤di≤10000
0≤|E|≤500000
没有自环,没有并行边。
输出
c0
c1
.
.
c|V|-1
输出由|V|行组成。打印从源点r到每个顶点0,1,… 的最短路径的权值之和。如果没有从源点到终点的路径,则打印INF。
样例输入
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
样例输出
3
0
2
INF
题目思路
C++代码实现
#include<bits/stdc++.h>
using namespace std;
const int maxn=100010;
struct Edge{ //边
int to,cost;
Edge(int t,int c){
to=t;
cost=c;
}
};
vector<Edge> G[maxn]; //邻接表
int V,E,s,d[maxn];
bool vis[maxn];
struct HeapNode{ //优先队列节点
int d,u;
HeapNode(int uu,int dd){
u=uu;
d=dd;
}
bool operator <(const HeapNode& h) const{
return d>h.d;
}
};
void Dijkstra(){
memset(d,0x3f,sizeof(d));
memset(vis,0,sizeof(vis));
priority_queue<HeapNode> q;
d[s]=0;
q.push(HeapNode(s,0));
while(!q.empty()){
HeapNode top=q.top();
q.pop();
int to=top.u;
if(vis[to]){
continue;
}
vis[to]=1;
for(int i=0;i<G[to].size();i++){
Edge e=G[to][i];
if(d[to]+e.cost<d[e.to]){
d[e.to]=e.cost+d[to];
q.push(HeapNode(e.to,d[e.to]));
}
}
}
}
int main(){
scanf("%d%d%d",&V,&E,&s);
for(int i=0;i<E;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
G[a].push_back(Edge(b,c));
}
Dijkstra();
for(int i=0;i<V;i++){
if(d[i]==0x3f3f3f3f)
printf("INF\n");
else
printf("%d\n",d[i]);
}
}
OK,解决了。