问题:给定某源结点 s∈V,确定该源点到所有结点 v∈V 的最短路径δ(s,v) 。
如果图中所有边 w(u,v) 均是非负的,则所有最短路径长度一定存在。
思路: 贪心
1. 维护一个结点集合 S ,源点 s 到集合中的结点的最短路径长度已经确定
2. 不断将集合 V-S 中当前距离源点 s 最近的结点 v 添加到集合 S 中。
3. 更新源点到与结点 v 相邻的那些结点的路径估计。
/*************************************************************************
> File Name: Dijkstra.cpp
> Author: hepan
> Mail: 1171602076@qq.com
> Created Time: 2014年11月08日 星期六 10时38分10秒
************************************************************************/
/*
* 1 2 2
* 3 2 4
* 1 4 5
* 2 5 2
* 3 6 3
* 5 6 3
*/
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
#define N 6
#define M 6
#define MAXN 100
vector<int> G[MAXN];
//边
struct Edge
{
int start;
int end;
int value;
}E[N+1];
struct Vertex
{
int d;
int s;
int p;
Vertex(){};
Vertex(int a,int b,int c) {d=a;s=b;p=c;};
bool operator<(const Vertex& a) const //运算符重载
{
return d>a.d;
}
}V[M+1];
void Initialize_Single_Source(int s)
{
int i;
for(i=1;i<=N;i++)
{
V[i].d=0x7fffffff;
V[i].p=-1;
}
V[s].d=0;
}
void Relax(int u,int v,int w)
{
if(V[u].d !=0x7fffffff &&V[v].d>V[u].d+w)
{
V[v].d=V[u].d+w;
V[v].p=u;
}
}
void print()
{
int i;
for(i=1;i<=N;i++)
cout<<V[i].d<<' ';
cout<<endl;
for(i=1;i<=N;i++)
cout<<V[i].p<<' ';
cout<<endl;
}
void Dijkstra(int s)
{
Initialize_Single_Source(s);
priority_queue<Vertex> Q;
Q.push(Vertex(V[s].d,s,V[s].p));
//cout<<!Q.empty()<<endl;
while(!Q.empty())
{
Vertex m=Q.top();
Q.pop();
s=m.s;
//cout<<"s:"<<s<<' '<<"size:"<<G[s].size()<<endl;
for(int i=0;i<G[s].size();i++)
{
int x=G[s][i];
int u=E[x].start;int v=E[x].end;int w=E[x].value;
//cout<<V[v].d<<' '<<V[u].d<<' '<<w<<endl;
if(V[u].d !=0x7fffffff &&V[v].d>V[u].d+w)
{
V[v].d=V[u].d+w;
V[v].p=u;
Q.push(Vertex(V[v].d,v,u));
}
}
print();
//cout<<!Q.empty()<<endl;
}
//print(V);
}
int main()
{
for(int i=1;i<=M;i++)
{
cin>>E[i].start>>E[i].end>>E[i].value;
G[E[i].start].push_back(i);
}
/*for(int i=1;i<N;i++){
cout<<i<<' '<<G[i].size()<<' ';
for(int j=0;j<G[i].size();j++)
cout<<G[i][j]<<' ';
cout<<endl;
}
cout<<endl;*/
Dijkstra(1);
return 0;
}