Dijkstra原理
構建圖上的節點
struct node{
int to;//終點
int w;//權重
}
構造圖
//假設n個頂點,m條邊,源點爲x;
struct node g[N];
for(int i=0;i<m;i++){
int s,e,w;
struct node edge;
cin>>s>>e>>w;
edge.to = e;
edge.w = w;
g[s].push_back(edge);
//二維的,g[s]爲一個向量,向量中每個元素爲一條從s出發的邊,
}
求解單源最短路
初始化
int d[N] = {0};//d[i]表示源點s到點i的最短路徑長度
for(int i=1;i<=n;i++){
d[i] = Inf; //初始化最短路徑均爲無窮大
}
d[x] =0; //源點最短路徑爲0
for(int i=0;i<g[x].size();i++){//訪問以x爲源點的各邊
int to = g[x][i].to; //從x爲源點的邊的終點序號
int w = g[x][i].w;
d[to] = w;
}
int used[N]={0};
used[x] =1;
求解單源最短路
int k = n;//n個頂點,循環n-1次。
while(k--){
int minn = Inf;
int ind = -1;
for(int i=1;i<=n;i++){//求出離遠點最近的點的索引
if(used[i]==0&&d[i]<minn){
minn =d[i];
ind = i;
}
}
used[ind] =1; //將已找到的離遠點最近的標記位已訪問。
for(int i=0;i<vc[ind].size();i++){ //更新ind相連的邊到源點的最短距離。
int to = vc[ind][i].to;
int w = vc[ind][i].w;
if(d[to]>(d[ind]+w)){
d[to]=(d[ind]+w);
}
}
}
例題
poj3269
#include<iostream>
#include<algorithm>
#include<list>
#include<string.h>
#include<math.h>
#include<vector>
#include<stdio.h>
using namespace std;
#define N 1005
const int Inf =999999;
int n,m,x;
int total[N]={0};
struct path{
int to;
int len;
};
void dis(vector<path> vc[]){
int used[N] ={0};
int d[N]={0};
for(int i=1;i<=n;i++){
d[i]=Inf;
}
d[x] = 0;
used[x] = 1;
for(int i=0;i<vc[x].size();i++){
d[vc[x][i].to] = vc[x][i].len;
}
int k = n;
while(k--){
int minn = Inf;
int ind = -1;
for(int i=1;i<=n;i++){
if(used[i]==0&&d[i]<minn){
minn =d[i];
ind = i;
}
}
used[ind] =1;
for(int i=0;i<vc[ind].size();i++){
if(d[vc[ind][i].to]>(d[ind]+vc[ind][i].len)){
d[vc[ind][i].to]=(d[ind]+vc[ind][i].len);
}
}
}
for(int i=1;i<=n;i++){
total[i]+=d[i];
}
}
int main()
{
cin>>n>>m>>x;
vector<path> vc[N];
vector<path> vc2[N];
for(int i=0;i<m;i++){
struct path p1,p2;
int s,e,w;
cin>>s>>e>>w;
p1.to=e;
p1.len=w;
vc[s].push_back(p1);
p2.to=s;
p2.len=w;
vc2[e].push_back(p2);
}
int d1[N]={0};
dis(vc);
dis(vc2);
int maxx=-1;
for(int i=1;i<=n;i++){
if(i!=x&&maxx<total[i]){
maxx = total[i];
}
}
cout<<maxx<<endl;
return 0;
}