#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <math.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
#define N 550
#define M 100010
//单源最短路经
//有点贪心的味道
int f[N][N];
int ans[N];
int path[N];
int vis[N];
int n,m;
void find(){
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++){
ans[i] = f[1][i];
if(ans[i]<M) path[i] = 1; //一开始,所有最短路的上一个点都是点1
else path[i] = -1;
}
vis[1] = 1;
ans[1] = 0;
for(int i=1;i<=n;i++){
printf("%d\n",ans[i]);
}
//初始化完毕
for(int i=1;i<n;i++){
//n-1次循环
int minc = M;
int v = -1;
for(int j=1;j<=n;j++){
if(!vis[j] && ans[j]<minc){
minc = ans[j];
v = j;
}
}
vis[v] = 1;
if(v!=-1){
for(int j=1;j<=n;j++){
if(!vis[j] && ans[j] > ans[v] + f[v][j])
{
path[j] = j;
ans[j] = ans[v] + f[v][j];
}
}
}
}
}
int main() {
freopen("/Users/a1/Public/20150717/20150717/in.txt","r",stdin);
while(scanf("%d",&n) && n){
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
f[i][j] = M;
scanf("%d",&m);
while(m--){
int a,b,c;scanf("%d %d %d",&a,&b,&c);
f[a][b] = c;
}
find();
for(int i=1;i<=n;i++){
printf("%d\n",ans[i]);
}
}
return 0;
}
单源最短路径(一样有点贪心的感觉,n-1次循环,不断进行更新源点到其它各点距离)
最新推荐文章于 2023-10-20 13:26:33 发布