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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| #include <cstdio> #include <cstring> #include <iostream> #include <vector> #include <queue>
using namespace std;
using LL = long long;
const int INF = 0x3f3f3f3f; const int N = 1e5 + 5;
struct Edge { int to, w; Edge () {} Edge (int _to, int _w) { to = _to, w = _w; } ~Edge () {} };
struct Node { int id, dis; Node () {} Node (int _id, int _dis) { id = _id, dis = _dis; } ~Node () {} friend bool operator < (const Node& n1, const Node& n2) { return n1.dis > n2.dis; } };
vector <Edge> G[N], rG[N]; priority_queue <Node> q;
int T, n, m, k, p; int u, v, w; LL f[N][55], dis[N]; bool flag, vis[N], exi[N][55];
int add (int x, int y) { return (x + y >= p) ? (x + y - p) : (x + y); }
void init () { flag = false; for (int i = 1; i <= n; ++i) { G[i].clear(), rG[i].clear(); for (int j = 0; j <= k; ++j) f[i][j] = -1; } while (!q.empty()) q.pop(); }
void AddEdge (int u, int v, int w) { G[u].push_back(Edge(v, w)); rG[v].push_back(Edge(u, w)); }
void Dijkstra (int s) { fill(dis + 1, dis + 1 + n, INF), fill(vis + 1, vis + 1 + n, false); q.push(Node(s, 0)), dis[s] = 0; while (!q.empty()) { Node nowtop = q.top(); q.pop(); int nowid = nowtop.id; if (vis[nowid]) continue ; vis[nowid] = true; for (auto Ed : rG[nowid]) { int to = Ed.to, w = Ed.w; if (dis[to] > dis[nowid] + w) { dis[to] = dis[nowid] + w; q.push(Node(to, dis[to])); } } } }
LL Solve (int x, int y) { if (exi[x][y]) { flag = true; return 0; } if (f[x][y] > 0) return f[x][y];
exi[x][y] = true; LL ret = 0; for (auto Ed : G[x]) { int to = Ed.to, w = Ed.w; int temp = y - (dis[to] + w - dis[x]); if (temp < 0 || temp > k) continue ; ret = add(ret, Solve(to, temp)); if (flag) return 0; } if (x == n && !y) ret = 1; exi[x][y] = false; return f[x][y] = ret; }
int main() { scanf("%d", &T); while (T--) { init(); scanf("%d%d%d%d", &n, &m, &k, &p); for (int i = 1; i <= m; ++i) { scanf("%d%d%d", &u, &v, &w); AddEdge(u, v, w); } Dijkstra(n); LL res = 0; for (int i = 0; i <= k; ++i) { for (int j = 1; j <= n; ++j) for (int s = 0; s <= k; ++s) exi[j][s] = false; res = add(res, Solve(1, i)); } printf("%lld\n", flag ? -1 : res); } return 0; }
|