类似于Prim算法
唯一区别为:mindist[]的意义变为了原点到其他点的距离
Dijkstra算法模版:
int Dijkstra(int s,int e)
{
int vex,addNode,tempMin;
intree[s] = true;
for(unsigned int i = 0;i < G[s].size();i++)
{
vex = G[s][i].vex;
mindist[vex] = Min(mindist[vex],G[s][i].weight);
}
mindist[s] = 0;
for(int nodeNum = 1;nodeNum <= n-1;nodeNum++)
{
tempMin = INF;
for(int i = 0;i < n;i++)
{
if(intree[i] == false && mindist[i] < tempMin)
{
tempMin = mindist[i];
addNode = i;
}
}
intree[addNode] = true;
for(unsigned int i = 0;i < G[addNode].size();i++)
{
vex = G[addNode][i].vex;
if(intree[vex] == false && mindist[addNode] + G[addNode][i].weight < mindist[vex])
mindist[vex] = mindist[addNode] + G[addNode][i].weight;
}
}
return mindist[e];
}
Dijkstra算法作用:
计算某一个节点到其他某一个节点的最短路径
例题HDU_1874:
#include <cstdio>
#include <vector>
#define Min(x,y) ( (x) < (y) ? (x) : (y) )
using namespace std;
struct Node
{
int vex,weight;
Node(int vex,int weight):vex(vex),weight(weight){}
};
const int maxn = 205;
const int maxm = 1005;
const int INF = 0xffffff;
int n,m;
vector<Node> G[maxn];
int mindist[maxn];
bool intree[maxn];
void Init()
{
for(int i = 0;i < n;i++)
{
G[i].clear();
mindist[i] = INF;
intree[i] = false;
}
return ;
}
int Dijkstra(int s,int e)
{
int vex,addNode,tempMin;
intree[s] = true;
for(unsigned int i = 0;i < G[s].size();i++)
{
vex = G[s][i].vex;
mindist[vex] = Min(mindist[vex],G[s][i].weight);
}
mindist[s] = 0;
for(int nodeNum = 1;nodeNum <= n-1;nodeNum++)
{
tempMin = INF;
for(int i = 0;i < n;i++)
{
if(intree[i] == false && mindist[i] < tempMin)
{
tempMin = mindist[i];
addNode = i;
}
}
intree[addNode] = true;
for(unsigned int i = 0;i < G[addNode].size();i++)
{
vex = G[addNode][i].vex;
if(intree[vex] == false && mindist[addNode] + G[addNode][i].weight < mindist[vex])
mindist[vex] = mindist[addNode] + G[addNode][i].weight;
}
}
return mindist[e];
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
Init();
int v1,v2,weight;
for(int i = 0;i < m;i++)
{
scanf("%d%d%d",&v1,&v2,&weight);
G[v1].push_back(Node(v2,weight));
G[v2].push_back(Node(v1,weight));
}
int s,e;
scanf("%d%d",&s,&e);
int ans = Dijkstra(s,e);
if(ans == INF) printf("%d\n",-1);
else printf("%d\n",ans);
}
return 0;
}