题目连接:hdu1874
模板题
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int inf = 9999999;
int map[205][205];
int dis[205];//表示当前点到源点的最短路
int s,e,n;//s表示起点,e表示终点
void dijkstra()
{
bool v[205];//标记是否已放入集合V中
for(int i = 0; i < n; i ++)
{
dis[i] = map[s][i];
v[i] = false;
}
dis[s] = 0;
v[s] = true;
//依次在未放入V集合中的结点中,取dis[]最小值的结点,放入集合V中
for(int i = 1; i < n; i ++)
{
int temp = inf;
int pos = s;
for(int j = 0; j < n; j ++)
{
if(!v[j] && dis[j] < temp)
{
pos = j;
temp = dis[j];
}
}
v[pos] = true;
//更新dis
for(int j = 0; j < n; j ++)
if(!v[j] && map[pos][j] < inf && dis[pos] + map[pos][j] < dis[j])
dis[j] = dis[pos] + map[pos][j];
}
}
int main()
{
int i,j,m,x,y,z;
while(~scanf("%d%d",&n,&m))
{
for(i = 0; i < n; i ++)
for(j = 0; j < n; j ++)
map[i][j] = inf;
for(i = 0; i < m; i ++)
{
scanf("%d%d%d",&x,&y,&z);
map[x][y] = min(map[x][y], z);
map[y][x] = map[x][y];
}
scanf("%d%d",&s,&e);
dijkstra();
if(dis[e] == inf)
printf("-1\n");
else
printf("%d\n",dis[e]);
}
return 0;
}