1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| #include<iostream> #include<stack> #include<queue> #include<cstring> #include<cstdio> using namespace std; typedef long long ll; typedef pair<int,int> PII; struct Node { int var,next,val; } edge[100000005]; int head[100005],tot,dis[100005],N,M; int pre[100005]; bool vis[100005]; priority_queue<PII> Q; void add(int a, int b, int c) { edge[++tot].var = b; edge[tot].val = c; edge[tot].next = head[a]; head[a] = tot; } void init() { tot=0; memset(head,0,sizeof(head)); } void dijkstra(int s) { memset(dis,0x3f,sizeof(dis)); memset(vis,0,sizeof(vis)); memset(pre,-1,sizeof(pre)); while(Q.size()) Q.pop(); dis[s] = 0; Q.push(make_pair(0,s)); while(!Q.empty()) { int x=Q.top().second; Q.pop(); if(vis[x])continue; vis[x]=1; for(int i=head[x]; i; i=edge[i].next) { int y=edge[i].var; if(dis[x]+edge[i].val<dis[y]) { dis[y]=dis[x]+edge[i].val; if(!vis[y]) Q.push(make_pair(-dis[y],y)); pre[y]=x; } }
}
} int main() { int S,E; init(); cin>>N>>M>>S>>E; while(M--) { int x,y,z; cin>>x>>y>>z; add(x+1,y+1,z); } dijkstra(S+1); if(dis[E+1]>0x3f000000) { cout<<"no answer"<<endl; return 0; } cout<<dis[E+1]<<endl; stack<int> ans; for(int i=E+1;i!=-1;i=pre[i]) { ans.push(i-1);
} while(ans.size()) { cout<<'v'; cout<<ans.top()<<" "; ans.pop(); } puts(""); }
|