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 91 92 93 94 95 96 97 98 99
| #include <cstdio> #include <algorithm> #include <cstring> #include <queue> #define INF 0x3f3f3f3f #define MAXN 1005 #define MAXE 100005 using namespace std;
struct Node { int x, dis1, dis2; Node(int a, int b, int c) { x=a; dis1=b; dis2=c; } friend bool operator < (Node x, Node y) { return x.dis2>y.dis2; } };
int n, m, a, b, t, dis[MAXN], S, T, K, ans=INF; bool vis[MAXN];
struct Graph { int cnt, head[MAXN]; struct Edge {int next, to, dis;} edge[MAXE];
void addedge(int from, int to, int dis) { edge[++cnt].next=head[from]; edge[cnt].to=to; edge[cnt].dis=dis; head[from]=cnt; }
void spfa() { memset(dis, 0x3f, sizeof(dis)); queue<int> q; dis[T]=0; vis[T]=true; q.push(T); while(!q.empty()) { int x=q.front(); q.pop(); vis[x]=false; for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(dis[to]<dis[x]+edge[i].dis) continue; dis[to]=dis[x]+edge[i].dis; if(!vis[to]) q.push(to), vis[to]=true; } } }
void Astar() { int tot=0; priority_queue<Node> q;
if(S==T) K++; q.push(Node(S, 0, dis[S])); while(!q.empty()) { Node top=q.top(); q.pop(); if(top.x==T) { tot++; if(tot==K) {ans=top.dis1; return;} } for(int i=head[top.x]; i; i=edge[i].next) { int dis1=top.dis1+edge[i].dis; int dis2=dis1+dis[edge[i].to]; q.push(Node(edge[i].to, dis1, dis2)); } } }
} G1, G2;
int main() { scanf("%d%d", &n, &m); for(int i=1; i<=m; i++) { scanf("%d%d%d", &a, &b, &t); G1.addedge(a, b, t); G2.addedge(b, a, t); } scanf("%d%d%d", &S, &T, &K); G2.spfa(); G1.Astar(); if(ans==INF) printf("-1\n"); else printf("%d\n", ans); }
|