Two-dimensional shortest path.
In an undirected graph, there is a "shortcut" between nodes except the sides. The shortcut can be seen as a special side, from the start point to the end point, and the minimum number of times the shortcut is used given.
Dist [I] [J]: the shortest time for reaching the I point and passing through the J shortcut path.
The shortest path of the priority queue is optimized.
1. If you have reached the end point, you still need to continue expansion, because there may be fewer shortcuts.
2. If you have reached the end point, you can use the current number of shortcuts as the limit. The number of nodes that continue to expand must be smaller than this value.
3. If the number of shortcuts passes through this node before, it is necessary to extend the number of shortcuts.
4. If the time limit is exceeded, the node does not expand.
#include <cstdio>#include <cstring>#include <vector>#include <algorithm>#include <queue>using namespace std;#define N 102#define E 10020#define inf 0x3f3f3f3fstruct node { int u, l, s; node (int a=0, int b=0, int c=0): u(a), l(b), s(c) {} bool operator < (const node &a) const { return l > a.l; }};struct Node { int u, l; Node(int a=0, int b=0): u(a), l(b) {}};vector<Node> g[N], sg[N];int n, m, S, in, out, t;bool inq[N][E];int dist[N][E];int spfa() { priority_queue<node> Q; int limit = S; node x, y; memset(inq, false, sizeof(inq)); for (int i=1; i<=n; i++) for (int j=0; j<=S; j++) dist[i][j] = inf; Q.push(node(in, 0, 0)); dist[in][0] = 0; while (!Q.empty()) { x = Q.top(); Q.pop(); if (x.u == out && x.s < limit) limit = x.s; if (!inq[x.u][x.s]) { for (size_t i=0; i<g[x.u].size(); i++) { y.u = g[x.u][i].u; y.l = x.l + g[x.u][i].l; y.s = x.s; if (y.l < dist[y.u][y.s] && y.l <= t) { dist[y.u][y.s] = y.l; Q.push(y); } } if (x.s < limit) { for (size_t i=0; i<sg[x.u].size(); i++) { y.u = sg[x.u][i].u; y.l = x.l + sg[x.u][i].l; y.s = x.s + 1; if (y.l < dist[y.u][y.s] && y.l <= t) { dist[y.u][y.s] = y.l; Q.push(y); } } } } inq[x.u][x.s] = true; } for (int i=0; i<=S; i++) if (dist[out][i] <= t) return i; return -1;}int main() { while (scanf("%d%d", &n, &m) == 2) { int u, v, l; for (int i=0; i<=n; i++) { g[i].clear(); sg[i].clear(); } for (int i=0; i<m; i++) { scanf("%d%d%d", &u, &v, &l); g[u].push_back(Node(v, l)); g[v].push_back(Node(u, l)); } scanf("%d", &S); for (int i=0; i<S; i++) { scanf("%d%d%d", &u, &v, &l); sg[u].push_back(Node(v, l)); sg[v].push_back(Node(u, l)); } scanf("%d%d%d", &in, &out, &t); int ans = spfa(); if (ans == -1) printf("Impossible\n"); else printf("%d\n", ans); } return 0;}