链接:http://uva.onlinejudge.org/index.php?
option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1927
//邻接表+队列
#include <iostream> #include <string.h> #include <queue> #include <stdio.h> using namespace std; #define edge_max 100005 #define vertex_max 100005 const int inf = (1<<20); struct Node { int u,w; int next; }Edge[edge_max]; int pre[vertex_max],dist[vertex_max]; //以p[i]的i为起点储存的边数序号 int n,m,start,stop; //顶点数,边数 起点,终点 bool vis[vertex_max]; //记录 void init() { memset(pre,-1,sizeof(pre)); int index=1; int v,u,w; for(int i=0;i<m;i++) { scanf("%d%d%d",&v,&u,&w); Edge[index].u=u; Edge[index].w=w; Edge[index].next=pre[v]; pre[v]=index++; swap(v,u); Edge[index].u=u; Edge[index].w=w; Edge[index].next=pre[v]; pre[v]=index++; } } void spfa(int v) { queue <int> q; fill(dist,dist+n,inf); memset(vis,0,sizeof(vis)); dist[v]=0; vis[v]=1; while(!q.empty()) q.pop(); q.push(v); while(!q.empty()) { int top=q.front(); q.pop(); vis[top]=0; for(int i=pre[top];i!=-1;i=Edge[i].next) { int e=Edge[i].u; if(dist[e]>dist[top]+Edge[i].w) { dist[e]=dist[top]+Edge[i].w; if(!vis[e]) { q.push(e); vis[e]=1; } } } } } int main() { int t,cnt=1; scanf("%d",&t); while(t--) { scanf("%d%d%d%d",&n,&m,&start,&stop); init(); spfa(start); printf("Case #%d: ",cnt++); if(dist[stop]!=inf) printf("%d ",dist[stop]); else printf("unreachable "); } return 0; }