Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 36830 Accepted Submission(s): 13539
3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
2 -1
<span style="font-size:12px;">#include<cstdio> #include<cstring> #define INF 0x3f3f3f #define max 210 int n,map[max][max]; int start,end; void dijkstra() { int dis[max],visit[max]; int i,j,min,next; memset(visit,0,sizeof(visit)); for(i=0;i<n;++i) dis[i]=map[start][i]; visit[start]=1; for(i=1;i<n;++i) { min=INF; for(j=0;j<n;++j) { if(!visit[j]&&min>dis[j]) { min=dis[j]; next=j; } } visit[next]=1; for(j=0;j<n;++j) { if(!visit[j]&&dis[j]>dis[next]+map[next][j]) dis[j]=dis[next]+map[next][j]; } } if(dis[end]==INF)//若起点到终点距离认识初始话数值,则起点不能到达终点 printf("-1\n"); else printf("%d\n",dis[end]); } int main() { int m,i,j,a,b,x; while(scanf("%d%d",&n,&m)!=EOF) { for(i=0;i<n;++i)//不要用memset(map,0,sizeof(map))代替这两道for循环,错误的 { for(j=0;j<n;++j) { if(i==j) map[i][j]=0; else map[i][j]=INF; } } while(m--) { scanf("%d%d%d",&a,&b,&x); if(map[a][b]>x) map[a][b]=map[b][a]=x; } scanf("%d%d",&start,&end); dijkstra(); } return 0; }</span>
spfa算法,代码如下:
<span style="font-size:12px;">#include<cstdio> #include<cstring> #include<queue> #define INF 0x3f3f3f #define maxn 210 #define maxm 1010 using namespace std; int dis[maxn],visit[maxn],head[maxn],top,n; struct node { int to,val,next; }dege[maxm]; void add(int a,int b,int c)//建立邻接表 { dege[top].to=b; dege[top].val=c; dege[top].next=head[a];//指向上一个,edge[].next指向的是前一个,相当于链表里的指针的作用 head[a]=top++; } void spfa(int start,int end) { int i,u,v; queue<int>q; for(i=0;i<n;++i) { dis[i]=INF; visit[i]=0; } 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=dege[i].next)//遍历以u为前点的所有边 { v=dege[i].to; if(dis[v]>dis[u]+dege[i].val) { dis[v]=dis[u]+dege[i].val; if(!visit[v]) { visit[v]=1; q.push(v); } } } } if(dis[end]==INF)//若不存在start到end的路径,dis[end]的值为INF printf("-1\n"); else printf("%d\n",dis[end]); } int main() { int m,i,a,b,c,start,end; while(scanf("%d%d",&n,&m)!=EOF) { top=0;//建表从零开始 for(i=0;i<n;++i) head[i]=-1; while(m--) { scanf("%d%d%d",&a,&b,&c); add(a,b,c); add(b,a,c); } scanf("%d%d",&start,&end); spfa(start,end); } return 0; } </span>
floyd算法,代码如下:
#include<cstdio> #define maxn 210 #define INF 0x3f3f3f int dis[maxn][maxn],n; void floyd(int start,int end) { int i,j,k; for(k=0;k<n;++k) { for(i=0;i<n;++i) { for(j=0;j<n;++j) { if(dis[i][j]>dis[i][k]+dis[k][j]) dis[i][j]=dis[i][k]+dis[k][j]; } } } if(dis[start][end]==INF) printf("-1\n"); else printf("%d\n",dis[start][end]); } int main() { int m,start,end,i,j,a,b,c; while(scanf("%d%d",&n,&m)!=EOF) { for(i=0;i<n;++i) { for(j=0;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; } scanf("%d%d",&start,&end); floyd(start,end); } return 0; }