Recently Irina arrived to one of the most famous cities of Berland — the Berlatov city. There are n showplaces in the city, numbered from 1 to n, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there are no cyclic routes between showplaces.
Initially Irina stands at the showplace 1, and the endpoint of her journey is the showplace n. Naturally, Irina wants to visit as much showplaces as she can during her journey. However, Irina's stay in Berlatov is limited and she can't be there for more than T time units.
Help Irina determine how many showplaces she may visit during her journey from showplace 1 to showplace n within a time not exceeding T. It is guaranteed that there is at least one route from showplace 1 to showplace n such that Irina will spend no more than T time units passing it.
Input
The first line of the input contains three integers n, m and T (2 ≤ n ≤ 5000, 1 ≤ m ≤ 5000, 1 ≤ T ≤ 109) — the number of showplaces, the number of roads between them and the time of Irina's stay in Berlatov respectively.
The next m lines describes roads in Berlatov. i-th of them contains 3 integers ui, vi, ti (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ ti ≤ 109), meaning that there is a road starting from showplace ui and leading to showplace vi, and Irina spends ti time units to pass it. It is guaranteed that the roads do not form cyclic routes.
It is guaranteed, that there is at most one road between each pair of showplaces.
Output
Print the single integer k (2 ≤ k ≤ n) — the maximum number of showplaces that Irina can visit during her journey from showplace 1 to showplace n within time not exceeding T, in the first line.
Print k distinct integers in the second line — indices of showplaces that Irina will visit on her route, in the order of encountering them.
If there are multiple answers, print any of them.
Examples
Input
4 3 13
1 2 5
2 3 7
2 4 8
Output
3
1 2 4
Input
6 6 7
1 2 2
1 3 3
3 6 3
2 4 2
4 6 2
6 5 1
Output
4
1 2 4 6
Input
5 5 6
1 3 3
3 5 3
1 2 2
2 4 3
4 5 2
Output
3
1 3 5
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to solve a problem: given a directed acyclic graph (DAG) with n nodes (up to 5000) and m edges (up to 5000), each edge has a travel time ti (positive up to 1e9). Starting at node 1, need to go to node n, with total time <= T. We want to maximize the number of distinct showplaces visited (i.e., nodes along the path, including start and end). So we need a path from 1 to n that maximizes the number of vertices (length in terms of vertices count) subject to total sum of edge weights along the path <= T.
We need to output the maximum k and one such path.
n,m up to 5000, so we can afford O(n*m) or O(n^2) perhaps. But T can be up to 1e9, so we need to store DP states that consider time as a dimension? Typically, the problem is similar to "find the longest path in DAG with constraints on total weight" which is like DP with two parameters: number of vertices visited and minimal time to achieve that. Since n is small (5000), we can try DP: for each node, we want to know, for each possible number of nodes visited along a path from 1 to this node (including node), the minimum total time to achieve that count. Then for node n, we find the largest count where min time <= T.
That is classic: For DAG, we can sort nodes topologically. For each node v, we maintain an array best[v][k] = minimum total time to reach v with exactly k vertices visited (including v). Since maximum k is n (5000), storing a full n x n table would be 25e6 entries, which is okay memory wise if we store int (8 bytes) maybe 200 MB? Actually 5000 * 5000 = 25,000,000 entries. Each could be a 64-bit integer (since times up to 1e9 and sum may exceed int but we can store up to maybe 1e14). That's 200 MB if 8 bytes, 25e6 * 8 = 200 MB, which is high but maybe okay? But typical memory limit might be 256 MB; could be borderline. However we might compress or use vector of variable lengths. Since each node's maximum possible path length from 1 is limited; but in worst case, a DAG could have a Hamiltonian path from 1 to n, so length up to n. So each node might need up to n entries. But we can use DP that stores for each node a list of (count, min time) but we can keep only the best times for each count as we propagate. Since n=5000, total DP states across all nodes could be O(n^2) in worst case. That's 25e6, which might be okay in C++ with careful memory (e.g., use vector of long long for each node, but each vector of size up to n). But if we allocate a 2D array of size n x (n+1) with LLONG_MAX, that's 5000*5001 ~ 25e6, times 8 bytes = 200 MB, plus overhead maybe beyond limit. Could try to store only needed lengths.
Alternative: Use DP for number of nodes visited as dimension, and for each count we keep which node and minimal time? Another typical solution: Use DP for path length (number of vertices) and store predecessor information. Since graph is DAG, we can process nodes in topological order and for each node, we update its DP from incoming edges. Since each edge only increases count by 1 (since moving to next node adds one node to the path). Actually careful: When we go from u to v, the number of visited nodes in the path that ends at v would be count_u + 1 (since we include v). So DP transition: best[v][k] = min over (u,v) of best[u][k-1] + weight(u,v). So we need to keep best arrays for each node.
To reduce memory, we can store for each node a vector of length up to its reachable max count from 1, and fill gradually. Since n,m=5000, total number of DP entries might be less than n*m? Not necessarily. But we can also store DP as map from count to min time; but that would be similar worst-case.
Better: Use DP for longest path by cost constraint; that's like we want maximize nodes with time <= T. Since n is 5000, we can perhaps run a DP that tracks for each node a list of (time, max nodes) but we want the maximum nodes given time constraint; we can invert: for each node and each possible number of nodes, store minimum time. That's the natural way.
Let's see memory: 25e6 64-bit integers = 200 MB. In C++ using vector of vectors, each inner vector may have overhead. But we can allocate a single flat array of size n*(n+1) maybe 5000*5001 = 25,005,000. That's ~200 MB. Plus some overhead for storing predecessor information? We'll need to reconstruct path, so we need to store for each node and each count the predecessor node that achieved that minimal time. That would double memory to 400 MB, which is too high.
Thus we need a more memory-efficient approach.
We can note that m=5000, which is relatively small (up to 5000 edges). Could use dynamic programming across nodes but storing only the best (minimum time) for each count? But still need to reconstruct path, so we need to store predecessor info.
Alternative: Since n and m are both up to 5000, we could use a BFS-like approach over state (node, count) but number of states might be O(n*m) maybe? Not exactly; the count can go up to n, but each edge can produce new states. However, worst-case path length n, so total states across all nodes could be sum over nodes of number of distinct counts that can be achieved at that node with minimal time. In the worst case, a node may have many possible counts each with a distinct minimal time that is not dominated? But typically, for each node, the function f(k) = minimum time to reach node with exactly k nodes is non-decreasing with k? Actually, not necessarily monotonic: a longer path may have less total time if edges have varying weights? But since all edge weights are positive, adding an extra node adds positive time, so the minimum time to reach a node with exactly k nodes is strictly increasing with k? Let's think: Suppose we have two paths to node v: one with k nodes and time t1, another with k+1 nodes and time t2. Could t2 be less than t1? Possibly, if the k-node path uses heavy edges and the k+1-node path uses lighter edges, even though it has more edges, the sum might be smaller. For example, node 1 to node 2: edge weight 100 (direct), path 1->3->2 with edges weight 1 each, then times: k=2: 100, k=3: 2, so t2 < t1. So indeed, minimum time for larger k might be smaller. So we cannot prune based on monotonicity; we need to consider multiple counts.
But maybe we can use DP over number of nodes as primary dimension: For each possible count (from 1 to n), we compute for each node the minimal time to reach it with exactly that count, and store predecessor. Since count up to n (5000) and nodes n=5000, that's again n^2 = 25e6 states. That's maybe acceptable if we use only two arrays: For current count, we compute best times for nodes, and store predecessor information for that count? But to reconstruct path, we need to know for the final node n, the count k that works, and then we need to trace back through the counts. If we process counts incrementally, we can store predecessor pointers only for the states that are part of the solution. However, we need to know for each node and each count what is the predecessor node (and maybe also the previous count). But we could store predecessor information only when we update a state; but if we process counts in increasing order, we can keep a 2D predecessor array: pred[node][count] which again is n x n. That's large. But maybe we can store the entire path by backtracking from the final DP table after we have computed all. But we can compress: Since we need to output the path only for the optimal count at node n, we could during DP store for each node and each count the predecessor node; then reconstruct. Could we store predecessor only for the states that are not dominated? Possibly store for each node a list of pairs (count, (time, pred)). But again worst-case each node could have many counts.
Given constraints, perhaps 5000*5000 = 25e6, and each entry we could store as a struct with time and pred (2 ints). That's 4 bytes for time? time needs 8 bytes maybe, but we can store time as 64-bit and pred as 32-bit. That's 12 bytes per entry = 300 MB. Too high.
Alternative approach: Since the graph is a DAG with n,m <= 5000, we might use DP with an approach that computes for each node the "longest path in terms of vertices" but with a time constraint, using the concept of "knapsack on DAG" but treat it as a shortest path problem on expanded state space: treat each node and number of visited nodes as a state; there are at most n * n = 25e6 possible states, but m edges produce transitions from (u, cnt) to (v, cnt+1). That's up to m * n transitions (if each state exists) which is too large (25e6 * 5000). But we can limit because not all cnt values are reachable at each node.
Given small m, maybe we can use a DP that processes nodes topologically and for each node, we maintain a list of (count, min_time, predecessor) sorted by count. But we can prune dominated states: For a given node, if we have two states (c1, t1) and (c2, t2) with c1 <= c2 and t1 <= t2, then the state (c2, t2) is dominated (i.e., it's not useful because a higher count with higher time is worse). Actually, we want to maximize count subject to time <= T. For a fixed node, we are interested in the Pareto frontier of (count, time) where we want higher count and lower time. But since we want to maximize count given a time budget, we need to know for each possible count the minimum time, and also for each time the maximum count. Typically we keep the frontier of non-dominated points: a state (c, t) is dominated if there exists another state (c', t') with c' >= c and t' <= t. Because if we have a state with larger count and not larger time, it's better. So we can keep for each node a set of (count, time) pairs where count is increasing and time is decreasing (strictly?). Actually, on the frontier, as count increases, time might increase or decrease? Let's analyze: For a given node, consider all possible paths from 1 to that node. The frontier consists of those (count, time) such that there is no other path with strictly greater count and time <=, or strictly less time and count >=. More formally, a pair (c, t) is Pareto-optimal if there is no other path with c' > c and t' <= t, nor with c' >= c and t' < t. Typically we want the set where count is maximal for a given time or time minimal for a given count.
Given positive edge weights, the frontier may have the property that as count increases, the minimal possible time could go either direction (as earlier example). So the frontier might not be monotonic: we could have (c=2, t=100) and (c=3, t=2). So both are on the frontier: (2,100) is not dominated by (3,2) because (3,2) has higher count and lower time, so (2,100) is dominated actually? Check: (3,2) has c'=3 > 2 and t'=2 <=100, so indeed (2,100) is dominated by (3,2). So (2,100) would be removed from frontier. Similarly, (3,2) dominates any state with <=3 count and time>=2. So the frontier would consist of points that are "better" in both dimensions: higher count and lower time are better. So the Pareto frontier will be a set of points that are not comparable: i.e., you cannot have two points where one has both higher count and lower time, because that would dominate the other. Therefore, on the frontier, if we sort by count increasing, the times should be strictly decreasing. Because if we have (c1, t1) and (c2, t2) with c1 < c2, then for them both to be non-dominated, we must have t1 > t2 (otherwise (c2,t2) would dominate (c1,t1) if t2 <= t1). And also t1 cannot be <= t2 because then (c1,t1) would dominate (c2,t2) if t1 <= t2 and c1 < c2? Actually, domination requires both count >= and time <=. Since c1 < c2, (c1,t1) cannot dominate (c2,t2) because count is less. But (c2,t2) would dominate (c1,t1) if t2 <= t1. So to avoid domination, we need t2 > t1? Wait: For (c1,t1) and (c2,t2) with c1 < c2:
(c2,t2) dominates (c1,t1) if t2 <= t1 (since higher count and not higher time).
(c1,t1) does not dominate (c2,t2) because count is lower.
Thus for both to be non-dominated, we must have t2 > t1. Because if t2 <= t1, then (c2,t2) dominates (c1,t1) and (c1,t1) should be removed. Conversely, if t2 > t1, then (c2,t2) does not dominate (c1,t1) because its time is larger, and (c1,t1) does not dominate (c2,t2) because count is lower. So yes, on the frontier, as count increases, time also increases? Let's check with example: we had (2,100) and (3,2). But here c1=2,t1=100; c2=3,t2=2. Then c2 > c1 and t2 < t1, so (c2,t2) dominates (c1,t1). So (c1,t1) is not on frontier. So the frontier would contain only (3,2) (and maybe other points). So indeed frontier points have increasing count and increasing time? Actually from (3,2) to a higher count say (4,5): here c increase, t increase: 2<5, so (4,5) is not dominated by (3,2) because t is larger; (3,2) does not dominate (4,5) because count is lower. So both can be on frontier. So the frontier exhibits: as count increases, the minimal achievable time might also increase (since to get more nodes you usually need more edges, each with positive weight, so total time tends to increase). However, earlier we gave a counterexample where a longer path had less time; but in that case, the shorter path had a huge time, so the longer path is actually better in both count and time, thus it dominates the shorter one. So the shorter path would not be on the frontier. So indeed the frontier is composed of paths that are "efficient": you cannot increase count without increasing time, and you cannot decrease time without decreasing count. Therefore, the frontier points are such that time is a non-decreasing function of count? Actually strictly increasing? Because if two different paths have the same count but different times, only the minimal time matters. So for each count, we keep the minimum time. Among these, if we have count c with time t, and count c' > c with time t' <= t, then the c-path is dominated and removed. So on the frontier, for increasing counts, times are strictly increasing (since if t' = t, then the higher count path dominates as it has higher count and same time). So the frontier yields pairs (c, t) where t is strictly increasing with c.
Thus for each node, the number of Pareto-optimal (count, min_time) points is at most the number of distinct counts, but the frontier size could be O(n) in worst case (e.g., each count yields a larger time). However, in practice, it could be n. But we can store for each node a vector of pairs (count, time) sorted by count increasing, where times are increasing. And we can maintain this list by merging from predecessors and adding current node. Since each node has at most indegree? m up to 5000, but each node's incoming edges may be many. But we need to combine multiple lists to compute the frontier for node v.
Given m and n are 5000, total frontier sizes across all nodes might be O(n^2) in worst case? Could it be that each node can have O(n) frontier points, leading to total O(n^2) again? Possibly yes. But we can attempt to implement efficient merging: For each node v, we need to compute its frontier based on all incoming edges from u: for each frontier point (c_u, t_u) from u, we can generate candidate point for v: (c_u+1, t_u + w(u,v)). Then we need to merge these candidates and keep the Pareto frontier (non-dominated). Since each node may have many incoming edges, the total number of candidate points could be sum over edges of frontier size of u. In worst case, if each node has O(n) frontier points and there are O(n) edges (but m=5000, so max edges 5000), total candidates processed could be O(m * n) = 5000 * 5000 = 25e6, which is acceptable. And then we reduce to frontier of size O(n). But the merging of many candidate lists into a frontier may need careful data structures to avoid O(size^2). But we can simply collect all candidates from all incoming edges into a list, then sort by count and then filter to keep Pareto frontier (keeping those with increasing time). However, sorting all candidates for each node could be costly: total candidates across all nodes = O(m * avg frontier size). In worst case, if each node's frontier is O(n), and each node's indegree could be up to n (but m=5000, so total edges 5000, thus each node's indegree average ~ m/n = 1, but some nodes could have many). In worst-case, a node could have indegree O(n) (like n-1 edges from all others to it) but then m would be O(n^2) which exceeds 5000 for n=5000? Actually m <= 5000, so indegree of a node cannot exceed 5000, but if n=5000, indegree can be 5000, but then that node would have all possible edges from others to it, that's 4999 edges, still less than 5000. So worst-case indegree could be ~5000. So for a node with indegree 5000, and each predecessor u could have frontier size up to O(n)=5000, then the number of candidates is 50005000 = 25e6 for that node alone. That's huge but still maybe borderline in terms of time. But total across all nodes cannot exceed O(m * n) = 25e6? Actually careful: each edge will be used to generate candidates from the frontier of its source node. So total candidates generated across all edges = sum over edges (size(frontier of u)). If each node's frontier size is at most O(n), then total candidates = m * O(n) = up to 50005000 = 25e6. That's acceptable. However, sorting the candidates per node could be expensive if we sort a large list per node. But we can avoid sorting by merging incrementally: Since we process nodes in topological order, we could for each node v, iterate over incoming edges and for each candidate, insert into a temporary array and then after collecting all, we sort and filter. Sorting an array of size up to maybe 25e6 across all nodes? But worst-case for a single node, we might have to sort 25e6 numbers, which would be heavy. However, is it possible for a single node to have 25e6 candidates given m=5000 and n=5000? Let's compute: Suppose node v has indegree d, and each predecessor u has frontier size s_u. The total candidates = sum_{u in pred(v)} s_u. Since sum over u of s_u across all nodes might be O(n^2) (if each node's frontier size ~ n, total sum across nodes of frontier sizes = O(n^2) = 25e6). Then an individual node v could have sum of s_u up to O(n^2) if it receives from many nodes with large frontiers. But total sum over all nodes of candidates from all incoming edges equals sum over edges (size(frontier(u))) = sum over nodes (outdegree(u) * size(frontier(u))). The worst-case distribution: if we have a node u with large frontier size and high outdegree, it contributes many candidates. Since outdegree can be up to n but m=5000, total outdegree sum = m = 5000. So sum over edges of size(frontier(u)) <= max frontier size * m. Because each edge contributes the frontier size of its source. So total candidates across all edges is at most m * max_s, where max_s <= n. So total candidates <= 5000 * 5000 = 25e6. This total is distributed across nodes; a node with high indegree can have many candidates if its predecessors have large frontiers. But note that each edge is counted once for its target. So the total number of candidate points processed overall is <= 25e6. However, per node, we might need to sort its own candidate list. The candidate list size for node v is sum_{u: u->v} frontier(u). Since sum over v of that sum = total candidates = <= 25e6. So average per node is 25e6 / n = 5000. So typical candidate list size is 5000. But some nodes could have larger if they have many incoming edges from nodes with large frontiers. However, note that if a node has high indegree, those predecessors may have small frontiers due to topological order? Actually frontiers could be large for nodes that are later in order, but indegree could be from any earlier nodes. In the worst-case graph, we could have a DAG where all edges go into node n (the sink). Then node n has indegree m = 5000, and each predecessor u could have a frontier size up to maybe the number of nodes reachable from 1. If the graph is a chain from 1 to each u, each u could have frontier size equal to its position in the chain. For node n, the candidates from all 5000 predecessors could sum to large numbers. But the total sum over edges of frontier sizes is bounded by 50005000 = 25e6, so overall it's acceptable. However, careful: when we merge a new list, we might need to compare each element of the new list with the existing frontier and eliminate dominated points. Since both lists are sorted by count, we can do a kind of merge that constructs a new Pareto-optimal list. But because we need to keep only non-dominated points, after merging we might need to drop some points from both lists. Implementation can be similar to merging two Pareto frontiers (both sorted by count increasing, times increasing). The resulting frontier will be the Pareto-optimal set of the union of the two point sets. This can be computed by merging the two lists (like merging sorted arrays) but while also checking domination.
Alternatively, we can adopt a DP approach using "DP with predecessor array but compressed by using only needed counts for each node". Since n is 5000, we might be able to store DP as an array of size n+1 for each node if we use 2D array but store only time values (64-bit) and reconstruct path by storing predecessor for each state only when needed? Could we reconstruct path without storing all predecessors? Perhaps we can use a technique: after computing DP (minimum times for each node and count), we can find optimal count for node n, then we can backtrack by re-running DP from start but with knowledge of the optimal count? Not exactly.
We could store predecessor only for the states that are part of the optimal path when we reconstruct using DP decisions. But the optimal path is unknown until after DP is computed. However, we can store for each node and each count the predecessor node (or edge) that achieved the minimum time. That's large. But we could compress by storing only the best predecessor for each node and each count, but we can pack into 2 bytes? Not enough.
Alternatively, we could store the entire DP as 2D array of times, and then after we know the optimal count k, we can reconstruct the path by walking backwards: starting from node n with count k, we look at all incoming edges (u, v) and check if best[u][k-1] + w(u,v) == best[v][k] and also best[u][k-1] is finite. Since the DP values are stored, we can recompute the predecessor by scanning incoming edges. However, that would require O(m) per step, total O(km) which could be up to 50005000=25e6, acceptable. But we need to be careful about multiple possibilities; we can pick any. So we don't need to store predecessors explicitly, we can recompute during backtracking. That reduces memory to just the DP table of best times (and maybe we also need to store whether a state is reachable). So we need a 2D array of times: best[n+1][n+1] (or n+1 for count 1..n). Count dimension: we need indices up to n. However, for node v, the maximum possible count is at most the length of longest path from 1 to v (in terms of nodes). But in worst case could be n. So we need size n x (n+1). But we could use dynamic allocation: vector<vector> dp(n+1, vector(n+1, INF)). That's 5001 * 5001 = 25 million entries. Each entry 8 bytes -> 200 MB. Plus overhead of vector (each vector has overhead). This may exceed memory if the overhead is large (each inner vector has a small overhead, plus the outer vector). Overhead per inner vector might be ~24 bytes, times 5001 = 120KB, negligible. But each inner vector stores its data as a contiguous array; the total for data is 200MB. So total ~200MB plus some extra. Memory limit is not specified in problem statement (typical Codeforces problems have 256 MB). 200 MB may be okay if memory limit is 256 MB; but we also need other arrays (graph, etc.) but they are small. So 200 MB might be acceptable. However, we must also consider that we may need to initialize the dp table with INF; that's O(n^2) time, which is 25e6 operations, fine. Then we need to compute DP. Since the graph is a DAG, we can process nodes in topological order. For each node u, we iterate over its outgoing edges (v). For each count c where dp[u][c] is not INF, we update dp[v][c+1] = min(dp[v][c+1], dp[u][c] + w). But the number of transitions: For each edge (u,v), we need to iterate over all counts c for which dp[u][c] is reachable. In worst case, dp[u] may have many reachable counts (up to n). So total transitions = sum over edges of number of reachable counts at source. That could be O(m * n) = 25e6 again. That is acceptable. So overall time O(n^2 + mn) maybe 50e6, fine. So the naive DP with full 2D time table and no predecessor storage, plus backtracking, seems feasible within constraints (5000). Memory: 200 MB for dp table, plus maybe we need another array to store something else? Let's estimate more precisely: n ≤ 5000, so n+1 = 5001. So dp size = 5001 * 5001 = 25,010,001. Using 8 bytes = 200,080,008 bytes ≈ 191 MB? Actually 25,010,001 * 8 = 200,080,008 bytes ≈ 190.7 MB. Plus some overhead for vectors, maybe around 200 MB. That's close but might be under 256 MB. But some judges have memory limit 256 MB for Codeforces? The problem is from Codeforces? It looks like Codeforces problem "Irina and the Journey" maybe? I recall a problem "Irina and the way to the park" but not sure. Actually it's Codeforces Round #? I think it's CF 366 Div2 E? Or maybe 321C? Not sure. Usually Codeforces memory limit is 256 MB. So 200 MB should be okay, but we must also store graph (m edges). Graph storage: adjacency list, each edge with to, weight, maybe also we need reverse adjacency for backtracking? For backtracking we need to check incoming edges. So we could store both outgoing and incoming lists, or just store edges and for backtrack we can iterate over all edges and check if v is current node. That would be O(m) per step, total O(km) ≤ 5000m) = 25e6, fine. But we need to be careful: scanning all edges for each step is O(k*m) which is okay, but we could also store reverse adjacency list to make it O(k + m) total, but that's minor.
But we also need to store topological order. Since graph is a DAG, we can compute topological order by DFS or Kahn. n,m up to 5000, that's trivial.
Now, main issue: DP table of size n x (n+1) is large but maybe okay. However, I'm concerned about memory overhead of vector of vectors. In C++, a vector<vector> uses dynamic allocation; each inner vector allocates its own block of memory. The overhead per inner vector is maybe 24 bytes (pointer, size, capacity). So 5001 * 24 ≈ 120,024 bytes, negligible. The data is stored in separate contiguous arrays; but overall memory fragmentation might be okay.
But we must also consider that we need to initialize all entries to INF. Setting 25 million 64-bit values to INF takes time but is fine.
Alternate: we can use a 1D array of size n * (n+1) using a single vector of size n*(n+1). That would be more memory efficient (no per-row overhead) and perhaps faster due to contiguous memory. We can compute index = (v-1)(n+1) + c, where c ranges from 1 to n (or 0 to n). We'll have n nodes, counts from 0? But path must include start node 1. For simplicity, we can use counts representing number of nodes visited so far, including current. At start, node 1 with count 1 and time 0. So we need dp[node][count] for count >= 1. We'll allocate size n * (n+1) maybe with count dimension up to n inclusive. Use 0-index for node and count. Node indices 0..n-1. Count 0..n. But count=0 unreachable. We'll set dp[node][count] as INF for unreachable. Memory: n * (n+1) = 50005001 = 25,005,000 entries. Slightly less. That's same magnitude.
So we can allocate a 1D array of long long of that size. 25e6 * 8 = 200 MB. That is okay.
But we need to access quickly. We'll also need to store which counts are reachable? We'll just check INF.
Now, DP computation: We process nodes in topological order. For each node u, we need to iterate over all counts c where dp[u][c] is not INF. Instead of scanning all n counts for each node (which would be O(n^2) overall anyway), we can scan c=1..n for each node. That is O(n^2) = 25e6, plus transitions. So total O(n^2 + m*n) = up to 25e6 + 25e6 = 50e6, fine.
Implementation steps:
Read n,m,T.
Build graph: edges list (u,v,w). Also compute indegree for topological sort. Or use adjacency list for outgoing edges to process DP easily.
Perform topological sort: Kahn's algorithm using queue. Since n=5000, it's fine.
DP array: let's define dp as vector<vector> perhaps easier. But to reduce overhead, we can use single vector of length n*(n+1). We'll define a function idx(u, cnt) where u is 0-indexed, cnt from 1 to n. But we can also include cnt=0; but we won't use it.
Initialize all to INF (some large number > 1e14). Use LLONG_MAX / 2.
Set dp[idx(0,1)] = 0 (node 1 with count 1).
Process nodes in topological order (array order). For each node u (0-indexed), for cnt from 1 to n: if dp[idx(u,cnt)] < INF, then for each outgoing edge (v, w): new_cnt = cnt+1; if dp[idx(v, new_cnt)] > dp[idx(u,cnt)] + w, update it.
However, careful: We need to ensure we process nodes in topological order so that when we process u, all incoming contributions to u have been already considered? Actually DP is forward: we start from node 1 and propagate forward. Since it's a DAG, processing in topological order ensures that when we process u, all paths to u have been fully processed (i.e., all predecessors have been processed and have propagated to u). But note: our DP update goes from u to its outgoing edges. So if we process nodes in topological order, when we process u, we have already computed the best values for u (since all incoming edges to u come from nodes earlier in order). That's correct. So we can propagate from u to its successors.
After DP, find best answer: For node n-1 (0-index), find the maximum cnt such that dp[idx(n-1, cnt)] <= T. That cnt is the number of nodes visited (including 1 and n). Output cnt.
Reconstruct path: We need to output the sequence of nodes (showplaces) in order from 1 to n. We have the count cnt_max. We'll backtrack from node = n (1-indexed) with current count = cnt_max. We'll create a list path initially empty, then push node n at end? Actually we need to output nodes in order from 1 to n. So we can reconstruct backwards and then reverse.
Backtrack method: Start at cur_node = n (index n-1). cur_cnt = cnt_max.
While cur_node != 1 (index 0):
For each incoming edge (prev, cur_node, w) from the graph (we can iterate over all edges and check if v == cur_node, or we can store reverse adjacency list to speed up), we check if dp[idx(prev, cur_cnt-1)] + w == dp[idx(cur_node, cur_cnt)] and dp[idx(prev, cur_cnt-1)] is not INF. (There might be multiple such prev; any works). Choose the first such prev.
Then set cur_node = prev, cur_cnt = cur_cnt-1, and record prev (or push cur_node after change? We'll store nodes in reverse order: initially add n, then as we find prev, add prev to front, or push to vector and later reverse). I'll push into a vector path_backwards starting with n, then each step add prev to front. At the end we have 1 as the first. Ensure we have exactly cnt_max nodes.
Potential pitfalls:
The DP array uses count up to n, but the actual maximum count for a node might be less. We'll just iterate over all counts (1..n) for each node; that's O(n^2). Acceptable.
Edge weights up to 1e9, sum could exceed 2^31, so use long long.
Need to ensure we use INF > possible max sum: worst-case path may have up to n edges, each up to 1e9 => 5e12, so INF can be 1e18.
Topological sort: since graph is DAG, but there may be nodes unreachable from 1. However, we only care about nodes reachable from 1. But DP will propagate only from node 1. The topological order might include nodes not reachable from 1; they will have INF dp values and won't affect. It's fine.
We must guarantee that there is at least one route with time <= T, so answer exists.
Now, about memory: 200 MB for dp array might be high but likely okay. However, we can try to reduce memory further: we could store dp as vector<vector> but with inner vectors sized to (n+1). That's same memory. Or we could store dp as vector<vector>? time can be up to 5e12, need 64-bit. So 8 bytes.
Alternative to reduce memory: we could store dp as vector<vector> for predecessor? No.
Could we use only two rows? Not exactly, because we need to keep dp for all nodes to later backtrack. For backtrack we need dp values for all nodes and counts? Actually for backtrack we only need to check dp[prev][cnt-1] + w == dp[cur][cnt]. So we need dp values for all nodes and all counts. So we need the full table.
But perhaps we can compress by storing dp for each node only for counts that are achievable. But as argued, worst-case each node could have up to n counts, so still O(n^2). But maybe we can store as vector of pairs for each node (cnt, time). That would take maybe less memory because we only store reachable counts. However, in worst-case, each node could have all counts from some min to max (like chain: node i can be reached with counts from 1 to i). So that's O(n^2) pairs, each pair is (cnt (int), time (long long)) = 12 bytes, maybe 300 MB if stored as separate objects with overhead. Not necessarily better.
So the flat array is probably the most memory efficient.
But 200 MB is okay? I've seen Codeforces problems with n=5000 and similar DP memory usage. For instance, "Maximum number of points with cost" sometimes uses 5000x5000 arrays. So it's plausible.
But we also need to store graph and reverse adjacency, plus topological order array, etc. That's negligible.
Now, confirm with examples.
Example 1:
4 3 13
1-2:5
2-3:7
2-4:8
Paths:
1-2-3: nodes 3, time 12
1-2-4: nodes 3, time 13
1-2: nodes 2, time 5 (but not reaching n=4)
So answer k=3, path 1 2 4.
Our DP: start dp[1][1]=0.
From 1, update 2: dp[2][2]=5.
From 2 (cnt=2, time=5), update 3: dp[3][3]=12; update 4: dp[4][3]=13.
From 3? No out edges.
Check dp[4][3] =13 <=13 => k=3.
Backtrack: cur_node=4, cnt=3. Look at incoming edges: from 2 (weight 8). Check if dp[2][2] +8 ==13? dp[2][2]=5, so yes. Set cur_node=2, cnt=2. Incoming edges for 2: from 1 (weight5). Check dp[1][1]+5=5 == dp[2][2]=5. So cur_node=1, cnt=1. Done. Path 1,2,4.
Works.
Example 2:
6 6 7
Edges:...
We can test later.
Edge Cases: If there are multiple paths with same count and time, any is fine.
Now about topological order: Since graph is DAG, we can compute order via DFS or Kahn. But note: node numbering might not be in topological order. So we need to compute it.
Implementation details:
We'll use 0-indexing for nodes: convert input u,v to u-1, v-1.
Read edges into vector edges (u,v,w). Also build adjacency list out_adj[u].push_back({v,w}) for DP propagation, and in_adj[v].push_back({u,w}) for backtrack.
Compute indegree array indeg[v]++ for each edge. Then Kahn: queue nodes with indegree 0. But careful: We need to process nodes in topological order only for DP forward propagation. However, we might not need to include nodes that are not reachable from 1, but it's fine.
But what if node 1 has indegree >0? That's possible because edges could point to 1? But it's a DAG, so cycles none, but node 1 could have incoming edges. However, we start at node 1, so we only propagate from node 1. In topological order, we need to ensure we process node 1 before its successors. If node 1 has indegree >0, it may not be a source. In Kahn, we start with nodes indegree 0; if node 1 has indegree >0, it might not be processed early. But we can still process nodes in topological order; we must ensure we process node 1 before any node reachable from it. In a DAG, any topological order will have the property that if there is a path from u to v, u appears before v. So as long as we have a valid topological order, node 1 will appear before any node reachable from it (since there is a path from 1 to those nodes). But if there is no path from 1 to some node, it's fine. So we just need to compute a topological order of the whole graph; it's guaranteed to exist. However, if node 1 has incoming edges from some nodes, those nodes appear before 1, but that doesn't affect propagation because we only propagate from 1 forward.
Thus we can compute topological order via DFS or Kahn.
After we have order array 'topo', we iterate over nodes in that order. For each node u, we iterate over counts and then over out_adj[u].
But we must be cautious: For each node u, we should only propagate if dp[u][cnt] is finite. However, scanning all counts for each node results in O(n^2) loop. That's 25e6 iterations, each iteration then loops over outgoing edges, but that would multiply. Actually, we would have nested loops: for each node u (n times), for each count c (n times), if dp[u][c] finite, then for each outgoing edge (d out-degree). That would be O( sum over nodes (n * outdeg(u) ) ) = O(n * m) if we check condition for each count? But we only do the inner loop over outgoing edges when dp[u][c] is finite. In worst case, dp[u][c] might be finite for many c (up to n). So for each such combination, we do outdeg(u) work. So total operations = sum over edges of number of counts at source that are finite. Since each edge may be considered for each count of its source. In worst case, each node may have finite dp for all counts, so total = sum over edges (n) = m*n = 25e6. So that's okay.
But we must ensure we don't double count? In code, we can loop as:
for (int u : topo) {
for (int cnt = 1; cnt <= n; ++cnt) {
long long cur_time = dp[idx(u, cnt)];
if (cur_time == INF) continue;
for (auto &[v, w] : out_adj[u]) {
int ncnt = cnt + 1;
long long new_time = cur_time + w;
if (new_time < dp[idx(v, ncnt)]) {
dp[idx(v, ncnt)] = new_time;
}
}
}
}
But note: This updates dp for later nodes. Since we process in topological order, we may later process node v and propagate further. That's fine.
Now, we need to consider that the number of counts can be up to n, but for a node, the maximum meaningful count is limited by its position in the DAG. For chain, node i can have counts only up to i. But scanning all up to n is fine; we just do many INF checks.
Now, about indexing: We'll allocate a 1D vector dp of size n * (n+1). We'll define idx(node, cnt) = node * (n+1) + cnt. Since node from 0 to n-1, cnt from 0 to n (we'll use cnt=1..n). We'll waste column 0 but that's okay.
Initialize all to INF.
Set dp[idx(0, 1)] = 0.
After DP, we find answer:
int best_cnt = 0;
for (int cnt = 1; cnt <= n; ++cnt) {
if (dp[idx(n-1, cnt)] <= T) best_cnt = cnt;
}
cout << best_cnt << endl;
Now reconstruct path:
vector path;
int cur_node = n-1;
int cur_cnt = best_cnt;
while (true) {
path.push_back(cur_node+1); // convert to 1-index
if (cur_node == 0) break; // node 1
// find predecessor
bool found = false;
for (auto &[prev, w] : in_adj[cur_node]) { // iterate reverse edges
if (cur_cnt > 1) {
long long prev_time = dp[idx(prev, cur_cnt-1)];
if (prev_time != INF && prev_time + w == dp[idx(cur_node, cur_cnt)]) {
cur_node = prev;
cur_cnt--;
found = true;
break;
}
}
}
assert(found);
}
reverse(path.begin(), path.end());
// Now path size should be best_cnt.
Print path.
Check: We push cur_node before updating, starting from n, then after loop we break when cur_node becomes 1 and we have already pushed 1? Actually in loop we push first, then if cur_node==0 break after push. That means we push 1 then break. Then we reverse. Let's test: start cur_node= n-1 (4-1=3 for n=4). push 4. cur_node!=0, so we find prev=2, cur_node=2, cur_cnt=2. loop again: push 2. cur_node!=0, find prev=1, cur_node=1, cur_cnt=1. loop again: push 1. now cur_node==0 break. So path contains [4,2,1]. Reverse -> [1,2,4]. Good.
Edge Cases: The path may be exactly k nodes; we must ensure we have exactly best_cnt nodes.
Possible paths:
1-2-4-6: nodes 4, time 2+2+2=6
1-3-6: nodes 3, time 3+3=6
1-2-4-6-5: but 5 is not n (n=6), so not endpoint.
1-? maybe 1->2->? No other.
Also 1->2->4->6 then to 5 is not n.
So best is 4 nodes (1,2,4,6). Time 6 <=7.
DP should find.
Now we must ensure that DP can handle nodes with multiple incoming edges and merging.
We'll test conceptually: For node 6, incoming from 3 (weight3) and 4 (weight2). dp[3]? from 1->3 (cnt=2, time=3) and maybe longer? Actually 1->3 is only one edge, so dp[3][2]=3. Then from 3, we can go to 6: dp[6][3] = 3+3=6.
From node 4: dp[4] comes from 1->2->4: 1->2 (cnt=2, time=2); then 2->4 (cnt=3, time=2+2=4). So dp[4][3]=4. Then 4->6: dp[6][4] = 4+2=6. So dp[6][4]=6, dp[6][3]=6. So both give same time but different counts. For T=7, we can take count 4. So max count is 4.
Our DP will compute these. Backtrack from node6 cnt=4: check incoming edges: from 4 weight2, check dp[4][3] +2 = 4+2=6 equals dp[6][4]=6 -> choose prev=4. Then from node4 cnt=3: incoming from 2 weight2: dp[2][2] +2 =? dp[2][2] from 1->2: time2? Actually dp[2][2]=2. 2+2=4 equals dp[4][3]=4 -> prev=2. Then node2 cnt=2: incoming from 1 weight2: dp[1][1]=0 +2=2 equals dp[2][2]=2 -> prev=1. So path 1,2,4,6. Works.
Paths:
1-3-5: nodes 3, time 6
1-2-4-5: nodes 4, time 2+3+2=7 >6 (exceeds)
1-2-4-5? 7>6 not allowed.
1-2? not reaching 5.
So max nodes =3 (1,3,5). DP should yield.
Check: dp[3][2]=3; dp[5][3]=6; dp[5][4] from 1-2-4-5: dp[2][2]=2; dp[4][3]=2+3=5; dp[5][4]=5+2=7 >6. So only count 3 works.
Thus answer 3.
All good.
Now, we must also consider if there is a path with more nodes but same or less time? In example 1, both paths of 3 nodes had times 12 and 13; no 4 node path (since n=4, max nodes is 4? Actually a path from 1 to 4 could be 1-2-3-4? But there is no edge 3->4. So max nodes 3. So our answer matches.
Thus algorithm seems correct.
Now, potential performance issues: DP loops over all counts for each node, even if many are INF. In worst case, many may be INF? But if graph is dense enough that many paths exist, many counts may be reachable. Actually, since m <= 5000, the number of distinct paths may not be huge, but we cannot rely on that. For a DAG, the number of possible counts for a node could be up to its number of distinct path lengths from 1. In a DAG with 5000 nodes and 5000 edges, it's possible to have many distinct lengths per node? For example, a DAG where node i has edges from many previous nodes, could lead to many possible counts. In worst case, a node could have O(n) distinct counts. But is it possible to have all counts from 1 to n for many nodes? That would require many distinct paths of different lengths. For a node to have count k, there must be a path of length k-1 edges from 1. The graph may allow many combinations. For instance, consider a graph where node 1 connects to all other nodes with direct edges, and also there are longer paths? But to have a path of exactly k nodes, you need a sequence of k-1 edges. With limited edges, it's still possible that a node has many possible lengths. For node n, it could have paths of many lengths. However, the total number of distinct path lengths across all nodes might be bounded by something like O(n sqrt m) etc. But we can't rely. So in worst-case, it's conceivable that each node could have up to O(n) distinct counts. For example, consider a DAG that is a "layered" graph where node 1 connects to all nodes in layer2, each node in layer2 connects to all nodes in layer3, etc. But with m=5000, we cannot have complete bipartite connections between many layers because that would require many edges. For n=5000, to have many paths, you'd need many edges. Since m=5000, the total number of edges is limited. So the number of distinct counts per node may be limited by its indegree and the structure. However, it could still be large: For node v, its possible counts come from concatenating counts from its predecessors. If each predecessor has a range of counts, the union might be large. But with only 5000 edges, the sum of frontier sizes across all nodes might be less than 5000 * something. But we cannot guarantee it's less than n^2. However, we already saw total transitions m*n = 25e6 is okay. So scanning all counts per node is fine.
Now, memory: 200 MB. I'll implement with single vector dp(n * (n+1), INF). But note: n can be as high as 5000, so n*(n+1) = 25,005,000. That's within 32-bit signed int? 2.5e7 fits in int. Use int for indices.
But we need to be careful about stack vs heap: 200 MB should be allocated on heap (using vector). So vector dp(N) where N = n * (n+1). That's fine.
Now, for topological order, we need to process nodes in order. Since graph may have multiple components, but we only care about nodes reachable from 1, but we'll compute order for all.
We'll compute indegree from edges. Then Kahn: queue of nodes with indegree 0. While queue not empty, pop front, add to order, for each outgoing edge, decrement indegree of v and push if 0.
But note: If there is a node with indegree >0 that never becomes 0 due to being in a separate component with cycle? Graph is DAG, so all nodes will eventually be processed. However, if there are multiple sources, they will be added. That's fine.
Now, we must ensure we process node 1 even if it has indegree >0; in Kahn, it will be processed only after its predecessors are removed. But that's okay; DP propagation from node 1 occurs when we process node 1 in topological order. Since dp[1][1] is set initially, we then propagate from it. The nodes that come before 1 in topological order are those that have a path to 1. But those nodes are not reachable from 1? Actually, if there is an edge to 1, then there is a path from that node to 1. But we are starting at 1, so we don't care about those. However, during DP processing of those earlier nodes, their dp entries will be INF (since we didn't set them). So no problem. When we later process node 1, we have dp[1][1] set, and propagate forward.
Potential issue: If there is a node that is a predecessor of 1 (i.e., there is a path from that node to 1), that node will be processed before 1. In DP, when we process that node, we might propagate to its outgoing edges, possibly updating dp for some nodes reachable from it, including maybe nodes that are also reachable from 1 later. But those nodes could get dp values from a path that does not start at 1, which is invalid. However, because we initialize dp only for node 1 with count 1 and all others INF, any propagation from nodes not reachable from 1 will start from INF and thus remain INF. For a node u that is not 1, dp[u][*] is INF initially, and during processing of its predecessors (if any) they are INF, so no updates. So when we later process u, its dp remains INF. So propagation only from node 1 onward. So it's fine.
Thus we can safely use topological order.
Now, we need to ensure that we don't overflow long long when adding. T up to 1e9, sum of up to 5000 edges each 1e9 => 5e12, fits in 64-bit (9e18). So safe.
Now, we can code.
But wait: Could there be a path that revisits nodes? Since graph is directed and acyclic, no cycles, so path is simple automatically. So count of nodes equals number of vertices visited without repetition.
Now, confirm that we used count as number of vertices. When we go from u to v, we add 1 to count, because we include v. That's correct as long as we start count=1 for node 1. So after moving along k-1 edges, we have count=k.
Now, final answer: print k and then the path.
Now, let's think about possible optimization: we might not need to store dp for counts > n? No.
Now, we should test with extreme n=5000, m=5000, chain-like? Actually chain would have each node with a single incoming edge, so DP would have for node i, counts from 1 to i are reachable? In a simple chain 1->2->3->...->n, each node i can only be reached with exactly i nodes (since any path from 1 to i must go through all intermediate nodes? Actually in a chain, there is exactly one path, so node i is reachable only with count i. So dp[i][i] is set, others INF. So scanning all counts for each node still does many INF checks, but that's okay.
Now, worst-case for transitions: for each edge (u->v), we check all counts for u. In chain, only one count is finite, so we do O(m) work effectively. So overall runtime is dominated by scanning over all nodes and counts (n^2) for INF checks. That's 25 million operations, which is trivial.
But in worst-case where each node has many finite counts, the transition work may increase to 25 million as well.
Thus total operations maybe 50 million, which is fine for 2 seconds in C++.
Now, memory: 200 MB. Could we reduce it further? Maybe we can store dp as int64_t, but also we could store only two layers for DP and then for backtrack we could recompute? But backtrack requires dp values to compare, so we need all. Alternatively, we could store dp as array of unsigned int (32-bit) if we know max total time is <= 5e12? 5e12 fits in 2^33 ~ 8.6e9? Actually 5e12 > 2^32 (4.29e9). So we need 64-bit. So 8 bytes.
Maybe we can compress by storing dp as 2D array of int64_t using vector of vectors, but each inner vector's memory overhead might increase memory. Using a single flat vector is better.
Also we could use dynamic bitset? Not helpful.
Given typical memory limit for Codeforces is 256 MB, 200 MB is acceptable, but we must ensure we don't exceed. Also we need to store graph adjacency lists (out and in). For each edge, we store two entries (out and in) each containing (int, long long) maybe 12-16 bytes. With m=5000, that's negligible (< 200 KB). So total memory < 210 MB. Should be okay.
But we must also consider that we use vector dp(N) which uses contiguous memory; that's allocated on heap. Most judges allow 256 MB for heap.
However, sometimes Codeforces memory limit is 256 MB for total, including code and stack. So 200 MB leaves 56 MB for other things, which is plenty.
Thus we can proceed.
But wait, there is another nuance: The DP updates may require to consider counts up to n, but for node v, we only care up to n. However, when we propagate from u to v, cnt+1 could be n+1 if cnt=n. But since path can't have more than n nodes, we can skip if cnt == n because then adding one would exceed n. So in loop, we only consider cnt up to n-1 for outgoing edges. So we should add condition: if (cnt < n) then propagate.
Also, for dp indexing, we have allocated up to n (count n). So we can store count = n.
Now, one more thought: Could there be a path that visits more than n nodes? No, maximum nodes is n.
Now, implementing:
Pseudo-code:
int n,m;
long long T;
cin>>n>>m>>T;
vector<vector<pair<int, long long>>> out_adj(n), in_adj(n);
vector indeg(n,0);
for(i=0;i<m;i++){
int u,v; long long w; cin>>u>>v>>w; u--; v--;
out_adj[u].push_back({v,w});
in_adj[v].push_back({u,w});
indeg[v]++;
}
// topological sort
vector topo;
queue q;
for(i=0;i<n;i++) if(indeg[i]==0) q.push(i);
while(!q.empty()){
int u = q.front(); q.pop();
topo.push_back(u);
for(auto &[v,w] : out_adj[u]){
if(--indeg[v]==0) q.push(v);
}
}
// note: due to DAG, all nodes processed.
const long long INF = 1e18;
int Ncnt = n+1; // number of columns (count 0..n)
vector dp(n * Ncnt, INF);
auto idx = [&](int node, int cnt) { return node * Ncnt + cnt; };
dp[idx(0,1)] = 0; // node 1, count=1
for(int u : topo){
for(int cnt = 1; cnt <= n; cnt++){
long long cur = dp[idx(u, cnt)];
if(cur == INF) continue;
if(cnt == n) continue; // can't extend further
for(auto &[v,w] : out_adj[u]){
int ncnt = cnt+1;
long long nt = cur + w;
if(nt < dp[idx(v, ncnt)]){
dp[idx(v, ncnt)] = nt;
}
}
}
}
// Find best count for node n-1
int best_cnt = 0;
for(int cnt = 1; cnt <= n; cnt++){
if(dp[idx(n-1, cnt)] <= T) best_cnt = cnt;
}
cout << best_cnt << endl;
// reconstruct path
vector path;
int cur_node = n-1;
int cur_cnt = best_cnt;
while(true){
path.push_back(cur_node+1);
if(cur_node == 0) break; // reached node 1
bool found = false;
for(auto &[prev, w] : in_adj[cur_node]){
if(cur_cnt > 1){
long long prev_time = dp[idx(prev, cur_cnt-1)];
if(prev_time != INF && prev_time + w == dp[idx(cur_node, cur_cnt)]){
cur_node = prev;
cur_cnt--;
found = true;
break;
}
}
}
assert(found);
}
reverse(path.begin(), path.end());
for(int x : path) cout << x << " ";
cout << endl;
Now, verify that we didn't miss any case: Node 1 might have incoming edges; but during reconstruction, we stop when cur_node==0 (node 1). That's fine.
Also, note that dp[0][1] is set to 0, but there could be a path that starts from node 1 and goes to some node and then returns? Not possible due to acyclicity.
Now, consider if there are parallel edges? Problem says at most one road between each pair, so fine.
Now, think about possible overflow of INF: Use 1e18.
Now, we must ensure that we don't have negative weights; all positive.
Now, about topological order: It's possible that the graph has multiple sources; Kahn's algorithm as above works. But we must ensure that we don't miss nodes due to indegree not becoming zero because of unreachable parts? In a DAG, there must be at least one source in each connected component? Actually, in a DAG, there can be nodes with indegree>0 that are not reachable from any source? No, every node in a DAG has at least one source (node with indegree 0) that can reach it? Not necessarily: In a DAG, there can be a node that is part of a component where all nodes have indegree at least 1 (i.e., a cycle? But no cycles). In a DAG, there is no directed cycle, so there must be nodes with indegree 0. But it's possible for a node to be unreachable from any indegree-0 node? Actually, consider two separate components: component A has source nodes, component B may also have source nodes. If there is an edge from A to B, then B's nodes may have indegree from A, but there will still be a source in B? Let's think: Take a DAG: nodes 2->3, and node 1 with no incoming, but no edges from 1 to others. Then nodes 2 and 3 have indegree at least 1, but node 2 has indegree 0? Actually node 2 has indegree 0 because no edge from 1 to 2? The graph: edges: 2->3. Then indeg(2)=0, indeg(3)=1. So node 2 is a source. So every DAG has at least one source in each weakly connected component? Yes, because if a component has no source, then every node has indegree at least 1, you can trace backwards indefinitely, which would eventually repeat due to finite nodes, forming a cycle, contradiction. So Kahn works.
Thus topological order will include all nodes.
Now, we should consider if there are nodes that are not reachable from 1; dp for those will remain INF; no effect.
Now, one more optimization: We could restrict DP only to nodes reachable from 1, but not necessary.
Now, test with n=5000, m=0? But m >= 1, and there is at least one route from 1 to n with time <= T, so m >=1 and 1 can reach n.
Now, potential bug: We used auto &[v,w] in loops, need C++17.
Now, also note: In the DP loop, we are updating dp for v that may appear later in topological order. That's fine because we process nodes in order, so when we later process v, we have already considered all contributions from predecessors (since all predecessors appear before v in topological order). But careful: In our loop, we are iterating over topo list; for each node u, we propagate to its outgoing neighbors v. Since u appears before v in topological order, when we later process v, we have already processed all its incoming edges? Actually, we are updating dp[v][...] as we go. Since v appears later in topo, when we later process v, it will have accumulated all contributions from its predecessors because we processed them earlier. That's correct.
Now, backtracking: We need to ensure that dp values are exact. The DP uses min updates, so there may be multiple ways. Our backtracking picks the first predecessor that matches the equation. Since we used min, the equality holds for at least one predecessor.
Now, what about floating point? No.
Now, we need to be careful about the count dimension: When we allocate dp as n * (n+1), we use cnt from 0 to n. But we only set dp[idx(0,1)] = 0, and for updates we only use cnt >=1 and cnt+1 <= n. So cnt=0 remains INF. That's fine.
Now, memory: vector dp(n * (n+1), INF). This initializes all to INF. That's okay. But note: n * (n+1) can be up to 25,005,000. That's okay. But we might get memory allocation error if memory limit is tight. But I think it's okay.
Nevertheless, we can also reduce memory by using vector for counts? But we need 64-bit.
Alternatively, we could use array of int (4 bytes) if we cap time? But T up to 1e9, sum up to 5e12, need > 2^32, so 64-bit necessary.
Thus proceed.
Now, let's test with sample inputs to ensure correct output format (space at end maybe allowed). Output requires second line with k distinct integers in order. Sample output shows space after last number; that's fine.
Now, I'll also think about correctness proof: DP finds minimal time for each node and each possible count (number of vertices). Since we propagate in topological order, we consider all paths. Then answer is max count with time <= T at node n. Since we want maximum count, we check from high to low or just iterate ascending and take max that satisfies; that works.
Now, we should consider that the answer k is at least 2, as guaranteed.
Now, edge case: There could be a path that visits more nodes but with time exactly T; our check includes <=.
Now, check for potential overflow in dp values: INF = 1e18, safe.
Now, the graph may have up to 5000 nodes but edges only 5000, so adjacency lists are small.
Now, test with custom cases:
Case: n=2, m=1, T large: edge 1->2 weight 5. dp[1][1]=0; from 1 update dp[2][2]=5. Answer cnt=2, path 1 2.
Case: n=2, m=1, T=4 (insufficient time): but problem guarantees at least one route with time <= T, so not happen.
Case: multiple paths, need to pick any.
Now, confirm topological order: If there is an edge from 1 to n directly and also longer path, both considered.
Now, final step: Write code.
But I'd like to double-check the backtracking logic: We push cur_node before checking if it's start. So we will push 1 at the end, then reverse. That yields correct order.
Alternatively, we could create path in reverse order and then reverse.
Now, need to ensure that we break when cur_node==0 after push, to include 1.
Now, what if there is a path that uses exactly best_cnt nodes but during backtrack we might accidentally pick a predecessor that leads to a dead end (i.e., dp[prev][cur_cnt-1] is correct but we might later not find a path to 1 with remaining counts)? Since dp values are consistent, there must be a full path. Picking any predecessor that satisfies the equation should lead to a valid path to 1 with exactly cur_cnt-1 nodes. Because the DP ensures that if dp[v][c] is achieved via some u, then dp[u][c-1] is the corresponding minimal time and there is a path from 1 to u with that time and count. So recursively we can get to 1.
Now, we need to be careful: There might be multiple u that satisfy the equation due to ties. We can pick any; all lead to a valid path.
Now, performance of backtracking: For each step, we iterate over in_adj[cur_node] which could be up to indegree(v). In worst-case, indegree could be O(m)=5000. So total up to 5000*5000=25e6 checks. Acceptable.
Now, we could optimize by breaking as soon as found.
Now, final code.
But before finalizing, consider if there is any scenario where dp[n-1][cnt] <= T but the path uses more than cnt nodes? No, dp is defined as number of nodes.
Now, one more nuance: The problem states "visit as much showplaces as she can", which means distinct showplaces. Since DAG ensures simple path (no cycles), our count equals distinct nodes.
Now, we should confirm that dp array's size is exactly n*(n+1). We can declare:
int N = n;
int cols = n + 1;
vector dp(N * cols, INF);
Now, indexing: nodecols + cnt. Node from 0 to N-1, cnt from 0 to n inclusive. So total indices: Ncols = N*(n+1). Good.
Now, there is a slight inefficiency: we use cnt as int, but we may have count up to n. That's fine.
Now, we must also ensure that while reconstructing, we don't access dp with cnt=0. In loop, we check cur_cnt > 1 before accessing dp[prev][cur_cnt-1]; that's safe because when cur_cnt=1, we would be at node 1, and loop will break because cur_node == 0? Actually we break after push and check if cur_node == 0. So when cur_cnt=1, cur_node must be 1. So we won't go into the predecessor search. So safe.
Now, potential bug: The condition "if (cur_cnt > 1)" inside for loop ensures we don't access invalid cnt-1.
Now, the path vector size should equal best_cnt. We can assert after reconstruction.
Now, confirm that topological order includes all nodes; but what if there is an edge from a later node to earlier node? That would create a cycle? Actually topological order ensures no edge from later to earlier in the order. In a DAG, such an ordering exists. In our Kahn's algorithm, we get a valid order. Since we process u and then decrement indegree of v, we are building order where for each edge u->v, u appears before v. That's property of topological order.
Thus DP propagation is correct.
Now, double-check the DP update: we might be updating dp for a node that appears later in topo, but later in the same iteration of topo we might process that node later, but we might also have other predecessors that are processed even later? Since all predecessors of v appear before v in topo, they will have been processed before we get to v in the outer loop. So by the time we process v, all updates from its predecessors have been applied. That's correct.
Now, but what about updating dp for a node that is earlier in topo? That would require an edge from a later node to earlier node, which would violate topological order. So not possible.
Thus DP is correct.
Now, one more thought: We could speed up the DP by only iterating cnt up to the current maximum possible count for node u (like we could store a max_cnt for each node). But not needed.
Now, we should also consider the possibility of large T up to 1e9, but dp times up to maybe 5e12, so comparisons fine.
Now, I think solution is ready.
But before coding, let's search memory: 200 MB for dp. On some judges, stack size is limited, but dp is on heap. That's fine.
But what if n=5000, then N = 5000, cols=5001, product=25,005,000. Each long long 8 bytes = 200,040,000 bytes ≈ 190.7 MB? Actually 25,005,000 * 8 = 200,040,000 bytes = 190.7 MiB? Wait: 1 MiB = 2^20 bytes = 1,048,576 bytes. 200,040,000 / 1,048,576 = 190.8 MiB. Yes about 191 MiB. That's under 256 MiB.
But we also have other vectors: out_adj and in_adj each store about m pairs. Each pair might be two ints? Actually we store int v and long long w, so 12 bytes (assuming alignment). For m=5000, that's 60KB each, negligible. Topo vector size n ints: 20KB. So total < 192 MiB. So okay.
Now, we need to ensure we use 64-bit for dp and time.
Potential issue: In the DP loop, we might update dp[v][ncnt] multiple times; we do min check. That's fine.
Now, corner case: The graph might have multiple edges between same pair? Problem says at most one road, so no.
Now, confirm that we correctly handle the case where the path might have exactly n nodes (i.e., visits all showplaces). Then count = n. In DP, we only propagate if cnt < n, so we cannot extend beyond n. That's fine because path can't have more than n nodes.
Now, if the optimal path has n nodes, then we start with count=n at node n, backtrack works.
Now, we might also need to consider that dp[n-1][cnt] may be INF for many cnt.
Now, sample 2 output: "4\n1 2 4 6". Our code will output "4\n1 2 4 6" with trailing space maybe. Acceptable.
Now, let's test with sample 2 in mind: Graph edges as given. Ensure topological order: It's a DAG. We'll compute indegree. Node 1 indegree 0, node2 indegree1, node3 indegree1, node4 indegree1, node6 indegree2, node5 indegree1. Kahn: start with 1, remove edges, indeg2 becomes0, indeg3 becomes0. Next queue may have 2 and 3 (order depends). Let's say 2 then 3, or 3 then 2. But both fine. Our DP will still compute correctly because propagation order might affect intermediate updates but final dp values after processing all predecessors will be correct. Since we process nodes in topological order, when we process node v, all its predecessors have been processed? Not necessarily if some predecessor appears later? Actually topological order ensures all predecessors appear earlier. So if we get order 1,2,3,4,6,5? Let's see: After processing 1, indeg2 and indeg3 become 0. Suppose we push both into queue; order may be 2 then 3. Then process 2: its outgoing edge to 4 reduces indeg4 from 1 to 0? indeg4 initially 1? Edge 2->4, so indeg4=1 from 2. Also edge 1->2 already accounted. So after processing 2, indeg4 becomes 0, so push 4. Then process 3: its outgoing edge to 6 reduces indeg6 from 2 to 1? indeg6 initially: from 3 and from 4 later? Actually indeg6 gets from 3 and 4. At this point, 4 hasn't been processed yet, but indeg6 initially =2 (from 3 and 4). After processing 3, indeg6 becomes 1 (still from 4). Then process 4: outgoing to 6 reduces indeg6 to 0, push 6. Then process 6: outgoing to 5 reduces indeg5 to 0, push 5. Then process 5. So order: 1,2,3,4,6,5. In this order, when we process 4, its predecessor 2 has been processed, but also maybe 4's dp may need to consider path from 1->2->4. That's fine. For node 6, its predecessors are 3 and 4. Both appear before 6 in order (3 and 4). So when we process 6, we have already applied updates from 3 and 4 to dp[6]. So correct.
Now, what if the order is 1,3,2,4,6,5? Then when processing 2, its predecessor 1 is done. When processing 4, predecessor 2 is done. When processing 6, both 3 and 4 are done. So also fine.
Thus DP works.
Now, we need to guarantee that dp values for node v are finalized when we process v, because all incoming updates have been made. However, consider this scenario: We process u, propagate to v. But v may appear later in order, so the update is applied before we process v. That's fine. But could there be a case where an update to v comes from a node that appears later in the topological order? That would violate the topological property, because if there is an edge u->v, then u must appear before v. So no.
Thus DP is sound.
Now, we also need to consider that we may update dp for a node v multiple times from different u's, and the min may be updated later from a u that appears later in the order? But since all u appear before v, all updates occur before we process v. So when we process v, its dp values are final for the purpose of propagating further. So it's fine.
Now, backtrack: We rely on dp values to find predecessor. Since dp values are minimal times, we may have a situation where dp[v][cnt] is achieved by multiple u. We pick any. Good.
Now, what about the possibility that dp[v][cnt] is not exactly the sum of dp[u][cnt-1] + w due to rounding? All integers, fine.
Now, final answer.
Now, we should also consider that n=5000, m=5000, and T is up to 1e9. The DP may produce times that exceed T, but we only need to compare.
Now, potential improvement: early break in count search for node n: we can iterate cnt from n down to 1 and break when found, to avoid scanning all. But we need the maximum, so starting from n down is better. We'll do:
int best_cnt = 0;
for (int cnt = n; cnt >= 1; --cnt) {
if (dp[idx(n-1, cnt)] <= T) {
best_cnt = cnt;
break;
}
}
But careful: There might be some cnt that is not reachable (INF) but lower ones may be reachable. Starting from n down, we find the highest reachable and within T. But we need to ensure that if dp[n-1][cnt] is INF, we skip. So loop from n down to 1, if dp <= T, set best_cnt and break. That's efficient.
Now, confirm: The answer always exists, so best_cnt > 0.
Now, final code.
Now, before concluding, we should consider if any alternative solution exists that uses less memory, but given constraints, this is fine.
Now, some potential pitfalls:
When n=5000, n+1=5001, product 5000*5001=25,005,000. This multiplied by 8 = 200,040,000 bytes. That's 190.7 MiB as said. But some compilers may allocate memory with some overhead for vector (like capacity). vector uses exactly sizeof(long long)*capacity bytes plus a small overhead for the vector object itself (on stack). So fine.
We must use 64-bit for indices: int is 32-bit, max 2e9, so 25e6 fits.
Use 'long long' for time; INF = 1e18.
When reading input, use int for u,v, and long long for ti (since ti up to 1e9, fits in int, but we should use long long for consistency).
Now, we also need to compute topological order. If there are multiple edges, indegree counts accordingly.
Now, test on sample.
I'll write a quick mental test with sample 1.
Input:
4 3 13
1 2 5
2 3 7
2 4 8
Our code:
n=4, m=3, T=13.
out_adj[0]: (1,5)
out_adj[1]: (2,7), (3,8)
out_adj[2]: none
out_adj[3]: none
in_adj: for 1: (0,5); for 2: (1,7); for 3: (1,8)
indeg: 0:0,1:1,2:1,3:1? Actually compute: Edge 0->1 indeg[1]++ => indeg[1]=1; 1->2 indeg[2]=1; 1->3 indeg[3]=1. So indeg[0]=0.
Topo: queue initially 0, pop 0 -> topo[0]=0; then for edge 0->1, indeg[1]-- =>0, push 1. Next pop 1 -> topo[1]=1; edges 1->2: indeg[2]-- =>0 push 2; 1->3 indeg[3]-- =>0 push 3. Then pop 2 -> topo[2]=2; no out. Pop 3 -> topo[3]=3. Order: 0,1,2,3.
DP: dp[05+1]=0 (since cols=5). Process u=0, cnt from1..4: only cnt=1 finite. For each out edge to 1: ncnt=2, nt=5, set dp[15+2]=5. Then process u=1: cnt=2 finite (5). For out edges: to 2: ncnt=3, nt=12 set dp[25+3]=12; to 3: ncnt=3, nt=13 set dp[35+3]=13. Then process u=2: cnt=3=12, but cnt=3==n? n=4, so cnt<4 can propagate? Actually cnt=3 <4, but out_adj[2] empty, so nothing. Similarly u=3: cnt=3, out empty. After DP, dp[3][3]=13, dp[3][4]=INF. Check node 3 (index 3) counts from 4 down: cnt=4 INF, cnt=3 13 <=13 -> best_cnt=3. Backtrack: cur_node=3, cnt=3. in_adj[3] contains (1,8). Check prev_time = dp[1][2] =5, 5+8=13 matches. So prev=1, cnt=2. in_adj[1] contains (0,5). prev_time dp[0][1]=0, 0+5=5 matches. So prev=0, cnt=1. push etc. Path: [4,2,1] reversed -> 1 2 4. Good.
Now, sample 2: n=6, T=7. We'll test quickly with code mentally? Not necessary.
Now, sample 3: similar.
Now, we must ensure that we include nodes 1 and n in count. That's done.
Now, potential issue: When reconstructing, we use in_adj which contains pairs (prev, w). But we didn't store the reverse edges for nodes that have multiple incoming edges with same weight? That's fine.
Now, check for node 1: in_adj[0] may have incoming edges from other nodes (if any). But we break when cur_node == 0, so we don't need to consider them.
Now, finalize.
But before finalizing, I recall that some Codeforces problems with n up to 5000 use DP with O(n^2) memory and time, and it's accepted. For example, problem "D. Print 1337-string"? Not that. But I've seen 5000^2 DP in many problems.
Thus I think this solution will pass.
Now, possible improvements: We could reduce memory by half if we use unsigned int for time? But sum up to 5e12 > 2^32, so need 64-bit.
Alternatively, we could use vector dp(n * (n+1)); but we can also compress by using int64_t.
Now, we should also ensure that we use fast I/O (ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);) to avoid TLE on large input.
Now, final code.
Let's write the code.
I'll include necessary headers: , , , , .
Now, implement.
Potential bug: The topological sort may produce order that doesn't include all nodes if there is a cycle, but problem says no cycles.
Now, one more subtle point: In Kahn's algorithm, we start with nodes indegree 0. However, if there are multiple components, some nodes may have indegree 0 and be processed. But if there is a component with no source? Not possible. So fine.
Now, about time limit: DP loops: for each node (n), for each count (n), for each outgoing edge (outdeg). That could be up to n * n * outdeg? Actually the nested loops: For each node u, we have inner loop over cnt (n times). For each cnt we then loop over out_adj[u] (outdeg(u)). So total operations = sum_u ( n * outdeg(u) ) = n * m. Because sum outdeg = m. So exactly n*m = up to 25e6. That's fine. But also we have the condition if (cur == INF) continue; if many INF, we still loop over cnt but skip inner loop. So worst-case when many INF, we still iterate over all cnt but skip the inner loop, which is still O(n^2) for the outer loops (node * cnt) = 25e6. So total ~ 50e6 operations. That's fine.
Now, we also have the reconstruction loop: up to n * avg indegree (maybe 25e6). So total < 100e6, still okay.
Now, we need to be careful about using auto& in loops to avoid copying.
Now, final code:
cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
ll T;
cin >> n >> m >> T;
vector<vector<pair<int, ll>>> out_adj(n), in_adj(n);
vector<int> indeg(n, 0);
for (int i = 0; i < m; i++) {
int u, v; ll w;
cin >> u >> v >> w;
u--; v--;
out_adj[u].emplace_back(v, w);
in_adj[v].emplace_back(u, w);
indeg[v]++;
}
// topological sort
vector<int> topo;
queue<int> q;
for (int i = 0; i < n; i++) {
if (indeg[i] == 0) q.push(i);
}
while (!q.empty()) {
int u = q.front(); q.pop();
topo.push_back(u);
for (auto &[v, w] : out_adj[u]) {
if (--indeg[v] == 0) {
q.push(v);
}
}
}
int cols = n + 1; // count from 0 to n
vector<ll> dp(n * cols, INF);
auto idx = [&](int node, int cnt) {
return node * cols + cnt;
};
dp[idx(0, 1)] = 0; // start at node 1 with count 1, time 0
for (int u : topo) {
for (int cnt = 1; cnt <= n; cnt++) {
ll cur = dp[idx(u, cnt)];
if (cur == INF) continue;
if (cnt == n) continue; // cannot extend further (would exceed n nodes)
for (auto &[v, w] : out_adj[u]) {
int ncnt = cnt + 1;
ll nt = cur + w;
if (nt < dp[idx(v, ncnt)]) {
dp[idx(v, ncnt)] = nt;
}
}
}
}
int best_cnt = 0;
for (int cnt = n; cnt >= 1; cnt--) {
if (dp[idx(n-1, cnt)] <= T) {
best_cnt = cnt;
break;
}
}
cout << best_cnt << '\n';
// reconstruct path
vector<int> path;
int cur_node = n - 1;
int cur_cnt = best_cnt;
while (true) {
path.push_back(cur_node + 1);
if (cur_node == 0) break; // reached node 1
bool found = false;
for (auto &[prev, w] : in_adj[cur_node]) {
if (cur_cnt > 1) {
ll prev_time = dp[idx(prev, cur_cnt - 1)];
if (prev_time != INF && prev_time + w == dp[idx(cur_node, cur_cnt)]) {
cur_node = prev;
cur_cnt--;
found = true;
break;
}
}
}
assert(found);
}
reverse(path.begin(), path.end());
for (int x : path) {
cout << x << ' ';
}
cout << '\n';
return 0;
}
We should test with sample inputs.
Let's run mentally sample 2.
n=6, cols=7.
out_adj: as described.
Topo order as earlier: [0,1,2,3,5,4]? Actually node indices: 0=1,1=2,2=3,3=4,4=5? Wait mapping: 0:1, 1:2, 2:3, 3:4, 4:5, 5:6? Actually n=6, nodes 0..5 correspond to 1..6. So let's map: 0->1, 1->2, 2->3, 3->4, 4->5, 5->6.
Edges:
0->1 (2)
0->2 (3)
2->5 (3)
1->3 (2)
3->5 (2)
5->4 (1) // since 6->5: node5->4? Actually edge 6->5: from node5 to node4.
Wait careful: Edge "6 5 1" is from showplace 6 to showplace 5, so u=6 (index5), v=5 (index4), w=1. So out_adj[5].push_back(4,1), in_adj[4].push_back(5,1). Yes.
Now indeg: compute quickly, but it's a DAG.
Topo order might be 0,1,2,3,5,4? Let's see: 0 indeg0, process. Then indeg1 becomes0 (from 0->1), indeg2 becomes0 (0->2). Queue gets 1 and 2. Suppose process 1 first, then out from 1 reduces indeg3 from 1 to 0, push 3. Process 2, out from 2 reduces indeg5 from 2 to 1? indeg5 initially: from 2 and from 3? Actually indeg5: from 2 (edge 3->6) and from 3 (edge 4->6). At this point, 3 not yet processed, but indeg5 from 2 is reduced to 1 (still from 3). Then process 3 (from queue). out from 3 reduces indeg5 from 1 to 0, push 5. Process 5, out from 5 reduces indeg4 from 1 to 0, push 4. Process 4. So order: 0,1,2,3,5,4. So node 5 (index5, which is node 6) is processed before node4 (index4, node5). That's fine; it's topological because edge is 5->4 (6->5), so 5 before 4.
Now DP: Start dp[0][1]=0.
Process u=0: cnt=1: propagate to v=1 (cnt2) dp[1][2]=2; to v=2 (cnt2) dp[2][2]=3.
Process u=1: dp[1][2]=2 finite. cnt=2 (<6). propagate to v=3 (cnt3) dp[3][3]=2+2=4.
Process u=2: dp[2][2]=3 finite. propagate to v=5 (cnt3) dp[5][3]=3+3=6.
Process u=3: dp[3][3]=4 finite. propagate to v=5 (cnt4) dp[5][4]=4+2=6.
Process u=5: dp[5][3]=6, dp[5][4]=6. cnt=3: propagate to v=4 (cnt4) dp[4][4]=6+1=7? Actually from 5->4 weight1: from cnt3 produces cnt4, time 6+1=7; also from cnt4 (cnt=4) propagate? cnt=4 finite, but cnt=4==n? n=6, so ok, propagate to v=4 (cnt5) dp[4][5]=6+1=7? Wait dp[5][4]=6, so from cnt4 we get cnt5 time=7. So dp[4][5]=7. Also maybe from cnt3 we also produce cnt4 for node4: dp[4][4] = min(inf,7) =7. So node4 gets dp[4][4]=7, dp[4][5]=7. Process u=4: dp[4][4]=7, dp[4][5]=7, but they are for node 4 (which is node5). Not needed for final answer.
Now node n-1 = 5 (node6). Check dp[5][4]=6 <=7, dp[5][5]? maybe? dp[5][5] from some path? Could be from 0->2->5? That's cnt3; to get cnt5 maybe 0->1->3->5? that's cnt4; there is no cnt5. So dp[5][4]=6 is best. For cnt=4, time 6 <=7, best_cnt=4. Good.
Now, we should also test a case where there are multiple optimal counts but we pick any. That's fine.
Now, what about the scenario where the DP may update dp[v][cnt] to a smaller value later from another u, but we already processed v later? Since we process v after all u, all updates occur before processing v. So final value is min over all. But if we had processed v earlier? Not possible because all u are before v. So no issue.
Now, about time: DP loop uses a range-based for topo, but we also need to ensure we don't accidentally process nodes that have not yet been assigned all incoming updates? Already correct.
Now, check if there is any need to treat nodes that are not reachable from 1 to avoid propagating from them? They have INF dp, so they won't propagate.
Now, final code seems good.
Now, but we might have a potential bug: In DP, we only skip cnt == n, but we also need to ensure we don't propagate if cnt+1 > n, but cnt==n ensures that. So okay.
Now, consider if there is a node with count exactly n, but we might still propagate? No, we skip.
Now, one more thing: In the topological sort, we used a queue and reduced indegrees. But if the graph has multiple components, we still get an order. However, if there is an edge from a node in a later component to a node in earlier component? That would create a cycle across components? Actually components are not defined; but topological order ensures that all edges go from earlier to later. So it's fine.
Now, check the memory: vector dp(n * cols) might allocate exactly n*cols elements. For n=5000, cols=5001, that's 25,005,000. That's about 200 MB. On some online judges, the memory limit might be 256 MB, but also there is memory for the stack, code, etc. Should be okay. However, if the judge has a lower limit (like 128 MB), then it would fail. But problem statement does not specify memory limit, but typical Codeforces limit is 256 MB for such problems. I'll assume it's okay.
Nevertheless, I'll see if we can reduce memory by using int32_t for dp if we know that the maximum total time is <= 1e9? No, T up to 1e9, but sum could be up to 5e12, so int32 is insufficient. So we need 64-bit.
Could we use vector< vector > but with each inner vector sized to n+1? That would also allocate similar memory but with overhead per vector. Actually each inner vector's dynamic array is separate and may cause fragmentation but total memory would be roughly the same plus overhead. The flat vector is more memory efficient.
Now, consider if we can use 'int' for count, 'long long' for time.
Now, one more thing: In the DP, we might have multiple updates to dp[v][ncnt]; we are only storing the minimum time. For reconstruction, we need to ensure that the dp value we use corresponds to a path that exists. Since we only store the minimum time, it's fine. But if there are multiple ways to achieve the same minimum time for a given (v,cnt), we may pick any during backtracking.
Now, what about integer overflow? INF = 1e18, adding edge weights up to 1e9 could exceed 1e18 if many additions? Worst-case sum of 5000*1e9 = 5e12, far below 1e18. So safe.
Now, output formatting: The problem output shows a space after the last number. That's acceptable.
Now, we should test with a larger case manually? Not necessary.
Potential bug: In the reconstruction loop, we check condition: prev_time + w == dp[idx(cur_node, cur_cnt)]. Since both are long long, equality holds. But due to multiple updates, there might be rounding issues? No.
Now, consider if the DP yields a path where time exactly equals T; fine.
Now, edge case: If there is a direct edge from 1 to n with weight <= T, but also a longer path with more nodes but also <= T. Our DP will consider both.
Now, confirm that the graph is acyclic; we rely on that for DP order.
Now, we could also compute DP using BFS but topological is fine.
Now, one more improvement: For nodes that are not reachable from 1, we could skip processing them entirely to save time, but not needed.
Now, final code is ready.
But I recall a known Codeforces problem: "Irina and the Journey" maybe Codeforces Round #366 (Div. 2) problem E? Actually I think it's "K. Berland" but not sure. Regardless, solution matches known editorial: DP with O(n^2) time and memory.
Double-check constraints: n up to 5000, m up to 5000. So m is same order as n. So DP with O(n^2) is fine.
Now, I will produce final answer.
But before final, I want to verify that we haven't misinterpreted "number of showplaces she may visit". It says "how many showplaces she may visit during her journey from showplace 1 to showplace n within a time not exceeding T." That includes start and end. So count = nodes in path.
Our DP counts nodes visited, including start and end, so correct.
Now, about the condition "It is guaranteed, that there is at most one road between each pair of showplaces." That's not used but okay.
Now, final code as above.
Now, I should consider if there is any possibility that the DP array index may exceed bounds: For node index n-1 and count n, idx = (n-1)(n+1) + n = (n-1)(n+1)+n = (n-1)(n+1) + n = (n^2 -1) + n = n^2 + n -1? Actually compute: (n-1)(n+1) = n^2 -1. Then plus n gives n^2 + n -1. Our total size is n*(n+1) = n^2 + n. So idx max = n*(n+1) - 1? Let's compute max index: for node = n-1, count = n (since cols = n+1, count from 0..n). So idx = (n-1)(n+1) + n = (n-1)(n+1) + n = (n^2 -1) + n = n^2 + n -1. That's exactly one less than n*(n+1) because total size = n*(n+1) = n^2 + n. So max index = n^2 + n -1, which is valid (0-indexed). So we are within bounds.
Now, for node 0, count = n: idx = 0*(n+1) + n = n, also within.
So all good.
Now, finalize. ```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
code
int n, m;
ll T;
cin >> n >> m >> T;
vector<vector<pair<int, ll>>> out_adj(n), in_adj(n);
vector<int> indeg(n, 0);
for (int i = 0; i < m; ++i) {
int u, v; ll w;
cin >> u >> v >> w;
--u; --v;
out_adj[u].emplace_back(v, w);
in_adj[v].emplace_back(u, w);
indeg[v]++;
}
// topological order
vector<int> topo;
queue<int> q;
for (int i = 0; i < n; ++i)
if (indeg[i] == 0) q.push(i);
while (!q.empty()) {
int u = q.front(); q.pop();
topo.push_back(u);
for (auto &[v, w] : out_adj[u]) {
if (--indeg[v] == 0)
q.push(v);
}
}
// DP table: dp[node][cnt] = minimal time to reach node with exactly cnt vertices visited
int cols = n + 1; // counts 0..n
vector<ll> dp(n * cols, INF);
auto idx = [&](int node, int cnt) {
return node * cols + cnt;
};
dp[idx(0, 1)] = 0; // start at node 1 with count 1, time 0
for (int u : topo) {
for (int cnt = 1; cnt <= n; ++cnt) {
ll cur = dp[idx(u, cnt)];
if (cur == INF) continue;
if (cnt == n) continue; // cannot extend beyond n vertices
for (auto &[v, w] : out_adj[u]) {
int ncnt = cnt + 1;
ll nt = cur + w;
if (nt < dp[idx(v, ncnt)]) {
dp[idx(v, ncnt)] = nt;
}
}
}
}
// find maximum feasible count for node n
int best_cnt = 0;
for (int cnt = n; cnt >= 1; --cnt) {
if (dp[idx(n - 1, cnt)] <= T) {
best_cnt = cnt;
break;
}
}
cout << best_cnt << '\n';
// reconstruct the path
vector<int> path;
int cur_node = n - 1;
int cur_cnt = best_cnt;
while (true) {
path.push_back(cur_node + 1); // convert to 1‑based
if (cur_node == 0) break; // reached node 1
bool found = false;
for (auto &[prev, w] : in_adj[cur_node]) {
if (cur_cnt > 1) {
ll prev_time = dp[idx(prev, cur_cnt - 1)];
if (prev_time != INF && prev_time + w == dp[idx(cur_node, cur_cnt)]) {
cur_node = prev;
--cur_cnt;
found = true;
break;
}
}
}
assert(found);
}
reverse(path.begin(), path.end());
for (int x : path) cout << x << ' ';
cout << '\n';
return 0;
5000 = 25e6, but if all edges go into n, then each of those 5000 edges originates from a different u, and each u's frontier size could be up to n (5000). So total candidates for n would be sum over 5000 nodes each with frontier size up to 5000, which could be 25e6. That is acceptable? Sorting 25e6 candidates for one node would be heavy: sorting 25 million integers takes considerable time and memory, but maybe still borderline in C++? 25 million integers (each 8 bytes) is 200 MB just for the array, plus sorting overhead. That might be too much for typical contest memory limit (256 MB). However, we could avoid sorting by merging frontiers from each predecessor incrementally, maintaining the frontier for v as we go. For each predecessor u, we have its frontier list sorted by count (increasing) with times increasing. When we generate candidates from u (c+1, t + w), the resulting list is also sorted by count (since original sorted by count, adding constant to count preserves order). Then we need to merge this sorted list into the current frontier for v, performing a Pareto-optimal merge. This can be done efficiently using two-pointer technique, akin to merging sorted lists and pruning dominated points. Since we have up to 5000 incoming edges, we could sequentially merge each candidate list into an accumulated frontier for v. Each merge operation would process O(|current frontier| + |new list|) and result in a new frontier that is Pareto-optimal. The total time across all merges for node v could be O(d * n) if we are not careful. But if we process each edge sequentially, and the frontier size is bounded by O(n), then merging a new sorted list of size s into a frontier of size f yields O(s + f) and the result size f' <= n. Over d edges, total work could be O(d * n + total s). Since total s = sum of frontier sizes of predecessors for node v, which could be up to 25e6, and d * n could also be up to 5000
5000 = 25e6, acceptable. So we can just store edges in a vector and for each backtrack step scan all edges to find a predecessor. That would be O(k
But note: We must ensure we find a valid prev. Since dp values were computed, there must be at least one.
The scanning over all edges each step could be O(m) per step, total O(cnt_max * m) ≤ 5000*5000 = 25e6, acceptable. But we might need to store edges for quick lookup; but m is only 5000, so scanning 5000 edges 5000 times is 25 million checks, each checking dp values (array accesses). That's fine.
However, we need to be careful: dp[idx(prev,cur_cnt-1)] might be INF; we need to check equality exactly; due to potential overflow or rounding, but all integers, so fine.
But there's a nuance: Because we updated dp[v][new_cnt] with min, there might be multiple prev that achieve the same minimal time. We can pick any.
To make backtracking faster, we could also store for each node and count the predecessor (if we wanted), but that would increase memory. We'll avoid.
But note: When scanning all edges for each step, we need to know for current cur_node, which edges are incoming. We can precompute reverse adjacency list: vector<vector<pair<int, long long>>> rev_adj(n), where for each edge (u,v,w) we add to rev_adj[v] a pair (u,w). That would store m entries, small. Then during backtrack, for cur_node we iterate over rev_adj[cur_node] (size indegree). That's O(indegree) per step, total O(sum indegree over path) = O(m) maybe less. That's better. So we'll store reverse adjacency.
Finally output cnt_max and the path (nodes in order).