求次短路。水过 #include<iostream> #include<queue> using namespace std; #define N 5005 #define inf 100000000 struct node { int dist,v; bool flag; }; struct cmp{ bool operator()(node a,node b){ return a.dist>b.dist; } }; priority_queue<node,vector<node>,cmp>que; struct edge { int v,d; edge *next; }; edge *g[N]; int dist[N][2]; bool use[N][2]; void add_edge(int u,int v,int d) { edge *ptr=new edge; ptr->v=v; ptr->d=d; ptr->next=g[u]; g[u]=ptr; return ; } void dijkstra(int s,int n) { node temp; int d,v,flag,u,w,i; for(i=1;i<=n;i++) dist[i][0]=dist[i][1]=inf; dist[s][0]=0; memset(use,0,sizeof(use)); temp.dist=temp.flag=0,temp.v=s; while(!que.empty()) que.pop(); que.push(temp); while(!que.empty()) { temp=que.top(); que.pop(); v=temp.v,d=temp.dist,flag=temp.flag; if(use[v][flag]) continue; use[v][flag]=1; for(edge *ptr=g[v];ptr;ptr=ptr->next) { u=ptr->v,w=ptr->d; if(d+w<dist[u][0]) { dist[u][1]=dist[u][0]; dist[u][0]=d+w; temp.v=u,temp.flag=0,temp.dist=dist[u][0]; que.push(temp); temp.flag=1,temp.dist=dist[u][1]; que.push(temp); } else if(d+w<dist[u][1]) { dist[u][1]=d+w; temp.dist=dist[u][1]; temp.flag=1; temp.v=u; que.push(temp); } } } } int main() { int n,m,i,a,b,d; scanf("%d%d",&n,&m); for(i=1;i<=n;i++) g[i]=NULL; for(i=1;i<=m;i++) { scanf("%d%d%d",&a,&b,&d); add_edge(a,b,d); add_edge(b,a,d); } dijkstra(1,n); printf("%d/n",dist[n][1]); return 0; }