邻接矩阵
复杂度O(|V|²)
#include<bits/stdc++.h>
using namespace std;
const int MAX_V=2005;
const int INF=9999999;
int cost[MAX_V][MAX_V];//cost[u][v]表示边(u,v)的权值(不存在这条边时设为INF)
int d[MAX_V];//顶点s出发的最短距离
bool used[MAX_V];//已经使用过的图
int V;//顶点数
//求从起点s出发到各个顶点的最短距离
void dijkstra(int s){
fill(d,d+V,INF);
fill(used,used+V,false);
d[s]=0;
while(true){
int v=-1;
//从未使用过的顶点中,选择一个距离最小的顶点
for(int u=0;u<V;u++){
if(!used[u]&&(v==-1||d[u]<d[v])) v=u;
}
if(v==-1) break;
used[v]=true;
for(int u=0;u<V;u++){
d[u]=min(d[u],d[v]+cost[v][u]);
}
}
}
int main(){
int from,to,cst;
fill(cost[0],cost[0]+2005*2005,99999);
}
堆
O(|E|log|V|)
#include<bits/stdc++.h>
using namespace std;
struct edge{int to,cost;};
typedef pair<int,int> P;//first是最短距离,second是顶点的编号
const int MAX_V=2005;
const int INF=9999999;
int V,m;
vector<edge>G[MAX_V];
int d[MAX_V];
void dijkstra(int s){
//通过指定greater<p>参数,堆按照first从小到大的顺序取出值
priority_queue<P,vector<P>,greater<P>> que;
fill(d,d+V,INF);
d[s]=0;
que.push(P(0,s));
while(!que.empty()){
P p=que.top();que.pop();
int v=p.second;
if(d[v]<p.first) continue;
for(int i=0;i<G[v].size();i++){
edge e=G[v][i];
if(d[e.to]>d[v]+e.cost){
d[e.to]=d[v]+e.cost;
que.push(P(d[e.to],e.to));
}
}
}
mx1=0;
for(int i=1;i<=V;i++){
if(mx1<d[i]) mx1=d[i];
}
}
int main(){
cin>>V>>m;//V是顶点数 m是边的关系
int from,to,cost,ans=0;
edge in;
for(int i=0;i<m;i++){
scanf("%d%d%d",&from,&to,&cost);
in.to = to; in.cost = cost;
G[from].push_back(in);
// in.to = from; in.cost = cost; 无向边再加这两句
// G[to].push_back(in);
}
dijkstra(x);
}