邻接表:稀疏图
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 100010;
int h[N], e[N], ne[N], w[N], idx;//邻接表
int d[N];
bool st[N];
int n, m;
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], h[a] = idx, w[idx] = c;
idx++;
}
int dijkstra()
{
d[1] = 0;
for (int i = 0; i < n - 1; i++) {
int t = -1;
for (int j = 1; j <= n; j++) {
if (st[j] == false && (t == -1 || d[t] > d[j]))
t = j;
}
st[t] = true;
for (int j = h[t]; j != -1; j = ne[j]) {
int k = e[j];
d[k] = min(d[k], d[t] + w[j]);
}
}
if (d[n] != 0x3f3f3f3f)
return d[n];
else
return -1;
}
int main()
{
memset(st, false, sizeof st);
memset(h, -1, sizeof h);
memset(d, 0x3f, sizeof d);
cin >> n >> m;
while (m--) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
cout << dijkstra() << endl;
return 0;
}
邻接矩阵:稠密图
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1010;
int g[N][N];//图
int d[N];//i点到1的距离
int n,m;
bool st[N];//到1的距离是否已经被确定
int dijkstra()
{
memset(d,0x3f,sizeof d);
memset(st,false,sizeof st);
d[1] =0;
for(int i =0;i < n-1;i++){//控制循环次数 为什么是n-1次 ?
int t = -1;
for(int j =1;j <= n; j ++){//找到目前到1点距离最短且未被确定的点
if(st[j]==false&&(t==-1||d[t] > d[j])){//t==-1的意思是控制第一个被确定的点一定是1
t = j;
}
}
for(int j = 1;j <= n;j++)//????
d[j] = min(d[j],d[t]+g[t][j]);
st[t] = true;
}
if(d[n]==0x3f3f3f3f)
return -1;
return d[n];
}
int main() {
memset(g,0x3f,sizeof g);//换成四个f行不行
cin>>n>>m;
while(m--){
int a,b,c;
cin>>a>>b>>c;
g[a][b] = min(g[a][b],c);
}
cout<<dijkstra()<<endl;
return 0;
}