Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 35605 Accepted Submission(s): 15482
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
3 2
#include<stdio.h> #include<string.h> #define INF 0x3f3f3f #define max 100+10 int dist[max],map[max][max],pre[max],visit[max]; int cross,road; void dijkstra() { int i,j,start=1; int next;//下一并入点 int mindist;//找最小的距离 memset(visit,0,sizeof(visit));//初始化 for(i=1;i<=cross;i++) { dist[i]=map[start][i]; } visit[1]=1; for(i=2;i<=cross;i++) { mindist=INF; for(j=1;j<=cross;j++) { if(visit[j]==0&&mindist>dist[j]) { mindist=dist[j]; next=j; } } visit[next]=1; for(j=1;j<=cross;j++) { if(visit[j]==0&&dist[next]+map[next][j]<dist[j]) { dist[j]=dist[next]+map[next][j]; } } } printf("%d\n",dist[cross]); } int main() { int i,j; int x,y,c; 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]=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; }
#include<stdio.h> #define INF 0x3f3f3f #define max 100+10 int map[max][max]; int cross,road; void floyd() { int k,i,j; for(k=1;k<=cross;k++) { for(i=1;i<=cross;i++) { for(j=1;j<=cross;j++) { if(map[i][j]>map[i][k]+map[k][j]) { map[i][j]=map[i][k]+map[k][j]; } } } } printf("%d\n",map[1][cross]); } int main() { int i,j,x,y,c; 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]=INF; } } while(road--) { scanf("%d%d%d",&x,&y,&c); if(map[x][y]>c) { map[x][y]=map[y][x]=c; } } floyd(); } return 0; }
#include <cstdio> #include <cstring> #include <queue> #include <algorithm> #define INF 0x3f3f3f #define MAXN 100+10 #define MAXM 10000+10 using namespace std; struct Edge { int to, val, next; }edge[MAXM]; int dist[MAXN], head[MAXN], vis[MAXN], top; int n, m; queue<int> q; void addedge(int a, int b, int d) { edge[top].to = b; edge[top].val = d; edge[top].next = head[a]; head[a] = top++; } void init() { for(int i = 1; i <= n; i++) { top = 0; vis[i] = 0; head[i] = -1; } } void spfa() { int i, j; int next; for(i = 1; i <= n; i++) dist[i] = INF; dist[1] = 0; q.push(1); vis[1] = 1;//标记 while(!q.empty()) { int u = q.front(); q.pop(); vis[u] = 0;//消除标记 for(i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].to;//遍历以u为起点 的所有边 的终点v if(dist[v] > dist[u] + edge[i].val)//松弛 { dist[v] = dist[u] + edge[i].val; if(!vis[v])//优化 不会有多余的点进队列 { vis[v] = 1; q.push(v); } } } } printf("%d\n", dist[n]); } int main() { int a, b, d; while(scanf("%d%d", &n, &m), n||m) { init(); while(m--) { scanf("%d%d%d", &a, &b, &d); addedge(a, b, d); addedge(b, a, d); } spfa(); } return 0; }