Input

Output

Sample Input
3 3
0 1 1
0 2 3
1 2 1
0 2
3 1
0 1 1
1 2
Sample Output
2
-1

dijkstra算法模板

# 代码

#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
const int N = 210;
int n,m,map[N][N];
bool st[N];
void init()
{
memset(st,0,sizeof st);
memset(map,0x3f,sizeof map);
for(int i = 0; i < n; i ++)
map[i][i] = 0;
}
int dijkstra(int a, int b)
{
if(a == b) return 0;
for(int i = 1; i <= n; i++)
{
int t1 = 0x3f3f3f3f + 1,t2;
for(int j = 0; j < n; j++)
if(!st[j]&&t1 > map[a][j])
{
t1 = map[a][j];
t2 = j;
}
st[t2] = true;
for(int j = 0; j < n; j ++)
if(!st[j])map[a][j] = min(map[a][j],t1+map[t2][j]);
}
if(map[a][b] == 0x3f3f3f3f)return -1;
return map[a][b];
}
int main()
{
while(scanf("%d%d",&n ,&m) != EOF)
{
init();
for(int i = 0; i < m; i ++)
{
int a,b,c;
scanf("%d%d%d", &a, &b, &c);
map[a][b] = min(map[a][b],c);
map[b][a] = min(map[b][a],c);
}
int a,b,ans;
scanf("%d%d",&a,&b);
if(a>b)swap(a,b);
ans = dijkstra(a,b);
printf("%d\n",ans);
}
return 0;
}


©️2019 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客