Description
Input
Output
1 #include <cstdio> 2 #include <cstring> 3 #include <queue> 4 #include <utility> 5 using namespace std; 6 7 const int INF = 0x3f3f3f3f; 8 const int MAXN = 1010; 9 const int MAXM = 100010; 10 11 #define X first 12 #define Y second 13 14 typedef pair<int, int> PII; 15 16 int head[MAXN], rhead[MAXN]; 17 int next[MAXM], rnext[MAXM], to[MAXM], rto[MAXM], cost[MAXM]; 18 int ecnt; 19 20 void init() { 21 ecnt = 1; 22 memset(head, 0, sizeof(head)); 23 memset(rhead, 0, sizeof(rhead)); 24 } 25 26 void add_edge(int u, int v, int c) { 27 cost[ecnt] = c; 28 to[ecnt] = v; next[ecnt] = head[u]; head[u] = ecnt; 29 rto[ecnt] = u; rnext[ecnt] = rhead[v]; rhead[v] = ecnt++; 30 } 31 32 int dis[MAXN]; 33 bool vis[MAXN]; 34 35 void dijkstra(int st, int n) { 36 for(int i = 1; i <= n; ++i) dis[i] = INF; 37 memset(vis, 0, sizeof(vis)); 38 priority_queue<PII> Q; 39 dis[st] = 0; Q.push(make_pair(0, st)); 40 while(!Q.empty()) { 41 int u = Q.top().Y; Q.pop(); 42 if(vis[u]) continue; 43 vis[u] = true; 44 for(int p = rhead[u]; p; p = rnext[p]) { 45 int v = rto[p]; 46 if(dis[v] > dis[u] + cost[p]) { 47 dis[v] = dis[u] + cost[p]; 48 Q.push(make_pair(-dis[v], v)); 49 } 50 } 51 } 52 } 53 54 int a_star(int st, int ed, int n, int k) { 55 priority_queue<PII> Q; 56 Q.push(make_pair(-dis[st], st)); 57 while(!Q.empty()) { 58 int u = Q.top().Y, c = -Q.top().X; Q.pop(); 59 if(u == ed && --k == 0) return c; 60 for(int p = head[u]; p; p = next[p]) 61 Q.push(make_pair(-(c - dis[u] + cost[p] + dis[to[p]]), to[p])); 62 } 63 return -1; 64 } 65 66 int main() { 67 int n, m, st, ed, k; 68 while(scanf("%d%d", &n, &m) != EOF) { 69 init(); 70 for(int i = 0; i < m; ++i) { 71 int u, v, c; 72 scanf("%d%d%d", &u, &v, &c); 73 add_edge(u, v, c); 74 } 75 scanf("%d%d%d", &st, &ed, &k); 76 dijkstra(ed, n); 77 if(dis[st] == INF) { 78 printf("-1\n"); 79 continue; 80 } 81 if(st == ed) ++k; 82 printf("%d\n", a_star(st, ed, n, k)); 83 } 84 }