HUD.2544 最短路 (Dijkstra)

时间:2021-12-26 09:32:34

HUD.2544 最短路 (Dijkstra)

题意分析

  1. 1表示起点,n表示起点(或者颠倒过来也可以)
  2. 建立无向图
  3. 从n或者1跑dij即可。

代码总览

#include <bits/stdc++.h>
#define nmax 110
#define inf 1e8
using namespace std;
int mp[nmax][nmax];
int shortpath[nmax];
bool visit[nmax];
int n,m; void dij(int s)
{
int cur = s;
memset(visit,0,sizeof(visit));
for(int i = 1;i<=n;++i) shortpath[i] = inf;
shortpath[cur] = 0;
visit[cur] = true;
for(int i = 1;i<=n ;++i){
for(int j = 1;j<=n;++j){
if(!visit[j] && shortpath[cur] + mp[cur][j] < shortpath[j]){
shortpath[j] = shortpath[cur] + mp[cur][j];
}
}
int nowmin = inf;
for(int j = 1; j<=n;++j){
if(!visit[j] && shortpath[j] <nowmin){
nowmin = shortpath[j];
cur = j;
}
}
visit[cur] = true;
}
}
int main()
{
//freopen("in.txt","r",stdin);
while(scanf("%d %d",&n,&m)!=EOF){
if( n == 0 && m == 0) break;
int sta,ed,cost;
for(int i = 1;i<=n;++i){
for(int j = 1;j<=n;++j){
mp[i][j] = inf;
}
}
for(int i = 0; i<m;++i){
scanf("%d %d %d",&sta,&ed,&cost);
int temp = mp[sta][ed];
if(cost < temp){
mp[sta][ed] = mp[ed][sta] = cost;
}
}
dij(1);
printf("%d\n",shortpath[n]);
}
return 0;
}