C. Dijkstra?
time limit per test
2 seconds
memory limit per test
64 megabytes
input
standard input
output
standard output
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
Output
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
Sample test(s)
input
5 6 1 2 2 2 5 5 2 3 4 1 4 1 4 3 3 3 5 1
output
1 4 3 5
input
5 6 1 2 2 2 5 5 2 3 4 1 4 1 4 3 3 3 5 1
output
1 4 3 5
解决方案:加多一个数组来记录路径即可,注意要用long long 否则会溢出
code:#include<iostream> #include<cstdio> #include<cstring> #include<queue> #define MMAX 100003 #define Max 100003 #define inf 1<<30 using namespace std; long long N,M,head[MMAX],vis[MMAX],low[MMAX],outqueue[MMAX]; int ss[MMAX]; int path[MMAX]; struct edge { int from,to,v; int next; } E[2*Max]; int spfa(int start) { queue<int >Q; Q.push(start);///首先得队列里的是源点 low[start]=0;///初识化源点到源点的距离 vis[start]=true;///表示源点在队列中 while(!Q.empty()) //cout<<"sdf"; { int temp=Q.front(); vis[temp]=false; Q.pop(); for(int v=head[temp]; v!=-1; v=E[v].next) { if(low[E[v].to]==-1||(low[E[v].to]>low[temp]+E[v].v)) { low[E[v].to]=low[temp]+E[v].v;///不断松弛 path[E[v].to]=temp; if(!vis[E[v].to]) { vis[E[v].to]=true; Q.push(E[v].to); }///若更新的点不再队列,则将其纳入队列 } } } return low[N]; } int main() { while(~scanf("%lld%lld",&N,&M)&&(M+N)) { memset(head,-1,sizeof(head)); memset(vis,false,sizeof(vis)); memset(path,-1,sizeof(path)); for(int i=0; i<=N; i++) low[i]=-1; int k=0; for(int i=0; i<M; i++) { int from,to,v; scanf("%d%d%d",&from,&to,&v); E[k].from=from; E[k].to=to; E[k].v=v; E[k].next=head[from]; head[from]=k++; E[k].from=to; E[k].to=from; E[k].v=v; E[k].next=head[to]; head[to]=k++; } long long Min=spfa(1); int we=0; if(path[N]!=-1&&low[N]!=-1) { int i=N; ss[we++]=i; while(path[i]!=-1) { i=path[i]; ss[we++]=i; } for(int j=we-1; j>=0; j--) { printf("%d%c",ss[j],j==0?'\n':' '); } } else printf("-1\n"); } return 0; }