Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 38585 Accepted Submission(s): 16862
#include<stdio.h> #include<string.h> #define INF 0x3f3f3f int map[110][110]; int visit[110];//记录最短距离节点 int lowtime[110];//记录最短 时间 int cross; int dijkstra() { int j,i,mintime,next; memset(visit,0,sizeof(visit));//初始化visit数组为0; for(i=1;i<=cross;i++) { lowtime[i]=map[1][i]; //初始化lowtime数组为从1到i的时间 } visit[1]=1; for(i=1;i<cross;i++) { mintime=INF; for(j=1;j<=cross;j++) { if(!visit[j]&&mintime>lowtime[j]) { mintime=lowtime[j]; next=j; } } visit[next]=1; for(j=1;j<=cross;j++) { if(!visit[j]&&lowtime[j]>map[next][j]+lowtime[next]) lowtime[j]=map[next][j]+lowtime[next]; } } printf("%d\n",lowtime[cross]); } int main() { int road,x,y,c,i,j; while(scanf("%d%d",&cross,&road)&&cross!=0&&road!=0) { for(i=1;i<cross;i++) { for(j=1;j<=cross;j++) { if(i==j) map[i][j]=0; else map[i][j]=map[j][i]=INF; } } while(road--) { scanf("%d%d%d",&x,&y,&c); if(map[x][y]>c) { map[x][y]=map[y][x]=c; } } dijkstra(); } return 0; }
spfa算法:
#include<stdio.h> #include<string.h> #include<queue> #define MAX 110 #define INF 0x3f3f3f using namespace std; int n,m; int map[MAX][MAX],low[MAX]; bool vis[MAX]; void init() { int i,j; for(i=1;i<=n;i++) for(j=1;j<=n;j++) map[i][j]=i==j?0:INF; } void spfa() { int i,j; queue<int>q; while(!q.empty()) q.pop(); memset(vis,0,sizeof(vis)); memset(low,0x3f,sizeof(low)); low[1]=0; q.push(1); vis[1]=true; int u; while(!q.empty()) { u=q.front(); q.pop(); vis[u]=false; for(i=1;i<=n;i++) { if(low[i]>low[u]+map[u][i]&&map[u][i]<INF) { low[i]=low[u]+map[u][i]; if(!vis[i]) { vis[i]=true; q.push(i); } } } } printf("%d\n",low[n]); } int main() { int i,j; while(scanf("%d%d",&n,&m),n|m) { init(); for(i=1;i<=m;i++) { int a,b,c; scanf("%d%d%d",&a,&b,&c); if(map[a][b]>c) map[a][b]=map[b][a]=c; } spfa(); } return 0; }