Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 42716 Accepted Submission(s): 18715
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
3 2
#include<cstdio> #include<cstring> #define max 110 #define INF 0x3f3f3f int n,map[max][max];//map记录两点间的最短路径 void dijkstra() { int dis[max];//记录起始点到当前点的最短路径 int visit[max];//标记是否访问过了 int i,j,next,min; memset(visit,0,sizeof(visit)); for(i=1;i<=n;i++) dis[i]=map[1][i]; visit[1]=1; for(i=2;i<=n;++i) { min=INF; for(j=1;j<=n;++j) { if(visit[j]==0&&min>dis[j]) { min=dis[j]; next=j; } } visit[next]=1; for(j=1;j<=n;j++) { if(visit[j]==0&&dis[j]>dis[next]+map[next][j]) dis[j]=dis[next]+map[next][j]; } } printf("%d\n",dis[n]); } int main() { int m,a,b,c; while(scanf("%d%d",&n,&m)&&n||m) { memset(map,INF,sizeof(map)); while(m--) { scanf("%d%d%d",&a,&b,&c); if(map[a][b]>c) map[a][b]=map[b][a]=c; } dijkstra(); } return 0; }
<span style="font-size:12px;">#include<cstdio> #include<cstring> #include<queue> #define INF 0x3f3f3f #define maxn 110//点数 #define maxm 10010//边数 using namespace std; int dis[maxn];//储存起点到当前点的最短路 int visit[maxn];//标记当前点是否在队列中 int head[maxn]; int n,top; struct node { int to,val,next; }edge[maxm]; void add(int a,int b,int c)//建立邻接表 { edge[top].to=b; edge[top].val=c; edge[top].next=head[a];//指向上一个,edge[].next指向的是前一个,相当于链表里的指针的作用 head[a]=top++; } void spfa(int start) { int i,j,next,u,v; queue<int>q; for(i=1;i<=n;++i) dis[i]=INF; dis[start]=0; visit[start]=1; q.push(start); while(!q.empty()) { u=q.front(); q.pop(); visit[u]=0;//消除标记 for(i=head[u];i!=-1;i=edge[i].next)//遍历以u为前点的所有边 { v=edge[i].to; if(dis[v]>dis[u]+edge[i].val) { dis[v]=dis[u]+edge[i].val; if(!visit[v]) { visit[v]=1; q.push(v); } } } } printf("%d\n",dis[n]); } int main() { int m,i,a,b,c; while(scanf("%d%d",&n,&m)&&n||m) { top=0;//建表从零开始 for(i=1;i<=n;++i) { visit[i]=0; head[i]=-1; } while(m--) { scanf("%d%d%d",&a,&b,&c); add(a,b,c); add(b,a,c); } spfa(1); } return 0; }</span>
<span style="font-size:14px;">#include<cstdio> #define maxn 110 #define INF 0x3f3f3f int dis[maxn][maxn],n; void floyd() { int k,i,j; for(k=1;k<=n;++k) { for(i=1;i<=n;++i) { for(j=1;j<=n;++j) { if(dis[i][j]>dis[i][k]+dis[k][j]) dis[i][j]=dis[i][k]+dis[k][j]; } } } printf("%d\n",dis[1][n]); } int main() { int m,i,j,a,b,c; while(scanf("%d%d",&n,&m)&&n||m) { for(i=1;i<=n;++i) { for(j=1;j<=n;++j) { if(i==j) dis[i][j]=0; else dis[i][j]=INF; } } while(m--) { scanf("%d%d%d",&a,&b,&c); if(dis[a][b]>c) dis[a][b]=dis[b][a]=c; } floyd(); } return 0; }</span>