We need to read problem carefully.
We have a directed graph with n nodes and m edges. Each edge i (i from 1 to m) has source a_i, target b_i, and weight w_i. The edges are given in input order.
We need to choose a path (possibly visiting same vertices multiple times) such that the weights of the edges are in strictly increasing order, and these edges come in the order of input. That is, if we pick edges e1, e2, ..., ek (where each ej is an index from 1..m), then we require that indices are increasing: i1 < i2 < ... < ik. Also their weights are strictly increasing: w_{i1} < w_{i2} < ... < w_{ik}. And the path must be contiguous in terms of node connection: for each j, the target of edge ij must be the source of edge i_{j+1} (i.e., b_{ij} = a_{i_{j+1}}). That forms a path.
Goal: maximize k (number of edges in the path).
Constraints: n up to 1e5, m up to 1e5, weights up to 1e5.
We need to find maximum length of a sequence of edges that is increasing in both index and weight and forms a directed path.
This is reminiscent of DP on edges: For each edge, we want to know the longest path ending at that edge (i.e., using that edge as last). Transition: from a previous edge j (j < i) with w_j < w_i and b_j = a_i.
We can process edges in input order, but weight condition complicates; we need to consider only edges with lower weight. So we need to maintain, for each node, the best DP value for some edge ending at that node with a particular weight? Or we can sort by weight? But indices must be increasing as well. So we need to respect both order constraints: we have edges in input order. We can only transition from an earlier edge. So if we process edges in input order, we can for each edge i, look at all earlier edges j that satisfy w_j < w_i and b_j = a_i. Then dp[i] = max_{j satisfying} dp[j] + 1, with base dp[i] = 1.
But m=1e5, naive O(m^2) is too slow.
We need a data structure to query for a given node (the source of current edge, i.e., a_i) the maximum dp[j] among edges j < i that end at that node (b_j = a_i) and have weight < w_i.
So we need for each node x, we maintain some structure that can answer: given a weight w, what is the maximum dp among edges j that end at x and have weight < w, and also have j < i (but since we process in order, as we insert edges as we go, any edge that ends at x and has been inserted already satisfies j < current i). So we can treat as we iterate i from 1 to m, after computing dp[i], we insert this edge into a data structure associated with its destination node b_i, with key = weight w_i and value = dp[i].
Then for a new edge i, we need to query the data structure of node a_i (since we need edges ending at a_i) for all entries with weight < w_i, and retrieve the maximum dp value.
Thus we need per-node data structures that support:
- insert (weight, value)
- query max value among weights < given w.
Because n and m up to 1e5, we could use per-node maps (like balanced BST) keyed by weight, storing the maximum dp for that weight (and also for any smaller weights we need prefix maximum). But we need query prefix max (max over keys < w). Also we need to handle multiple edges with same weight? We need strictly increasing weights, so w_j < w_i, so equal weights are not allowed. So query for < w, not <= w. So we can store for each weight the best dp, and when we insert a new (w, dp), we may need to update some structure. However if there are many distinct weights, per-node structures could be large, but total edges m is 1e5, so sum of sizes across nodes is m.
We can implement each node's structure as a map (ordered by weight) storing for each weight the maximum dp among edges ending at that node with that weight. But for prefix maximum query, we can also store something like a Fenwick tree or segment tree over weight domain. Since weight up to 1e5, we could compress weights globally. But we need per-node independent? But total nodes 1e5, if each node gets a BIT of size up to 1e5 that would be too much memory (1e10). Not possible.
Alternative: Since we only need to query for node a_i, and we will insert into node b_i, we need per-node data structure that can answer prefix max queries quickly. Because total m is 1e5, we could use a global approach: maybe we sort edges by weight, but we also need index order. However, because we require both index and weight increasing, we could treat edges as points (index, weight) and use something like 2D data structure? But also node connectivity condition complicates.
Maybe we can use DP with segment tree over nodes? Not directly.
We can think about per-node structures using something like a balanced BST with augmentations (like max over subtree). In Python, we could use sortedcontainers, but not allowed in typical CP environment. We could implement per-node something like a list of (weight, dp) inserted in increasing order of weight as we process edges? However, edges are not processed in weight order; they are processed in input order. So for a given node, its incoming edges (edges that end at that node) will be inserted in input order, not weight order. So we need a structure that can query among all inserted entries (which are in order of input) but based on weight.
One common approach for such DP problems: Since m <= 1e5, we could use a segment tree or BIT over weight domain but each node independent? Not possible. However, we might consider that we only need to query for a node a_i, and the data we have is from edges ending at that node. That is essentially mapping from node x to a list of (w, dp) for edges that end at x. We need to be able to answer: among all (w, dp) with w < w_i (some threshold), what is max dp? This is like we need a data structure that supports adding points (w, value) and querying maximum value for w in range [min, w_i-1]. Since weight domain is up to 1e5, we could have a global segment tree per node? Too heavy.
Alternative: Use coordinate compression on all weights. Then each node can maintain its own Fenwick tree (BIT) but dynamically built only for weights that actually appear for that node. Since total edges is m, the sum of number of distinct weights per node is at most m. However, if we build a BIT per node with size equal to number of distinct weights for that node, that is possible if we compress per node. But we need to be able to query prefix max. BIT needs to be built over the sorted list of weights for that node. However, as edges are inserted, the set of weights for a node grows over time; we need to support dynamic insertion and prefix query. That's essentially requiring an online data structure for a dynamic set of points with coordinate (weight) and value (dp). The number of points per node may be small on average. Since m=1e5, per-node average degree about 1, but could be skewed. In worst case, all m edges could end at the same node, say node 1. Then we would have up to 1e5 points for that node. In that case we need to support operations: insert (w, dp) and query max dp for w < given w. That's exactly what a BIT (Fenwick) can do if we know weight domain size (1e5) and we treat it as global. But we cannot allocate a BIT of size 1e5 for every node (which would be 1e5 * 1e5 memory). So we need something more memory-friendly.
Observation: The DP only depends on the maximum dp among all earlier edges ending at a given node with weight less than current edge's weight. That's like we need to maintain for each node a data structure that yields the best dp for each weight threshold. Could we use a global segment tree over nodes? Not exactly.
Alternatively, we could think in terms of "DP by weight" while scanning edges in input order. Since indices are increasing, we process edges sequentially. For each edge, we need to look at previous edges that end at a_i and have smaller weight. Perhaps we can maintain for each node a map of weight to best dp, and also maintain that map in such a way that it's sorted and we can quickly get prefix max. Since the number of entries per node is the indegree of that node (in terms of edges processed so far). We could use something like a balanced binary search tree with augmentations. In C++ we could use std::map and for each weight store the maximum dp, and also we can maintain a running prefix maximum by something like "for each weight, store the max dp for weights <= that weight"? But if we insert a weight that is not the largest, we might need to update prefix maximums for larger weights. That would be O(number of larger weights) in worst-case. Not good.
We can use a Fenwick tree over weight domain globally but separate per node? Actually, we could compress all weights globally (0..100000) and use a Fenwick tree that is per node but built lazily: we could maintain for each node a vector representing the Fenwick tree only for the weights that have been inserted for that node. That is a BIT with dynamic indexing: we need to map weight values to positions in a sorted list of weights that node has. However, since we insert weights on the fly, we would need to know the order of future weights to allocate positions. But we could pre-collect for each node all weights that will ever be inserted? That would require a first pass to collect, for each node, all weights of edges that end at that node. Since we have the entire input, we could do a preprocessing: iterate through edges, and for each edge i, record that node b_i will receive an insertion with weight w_i. So we can know all possible (node, weight) pairs. Then for each node, we can sort unique weights that appear as destination of edges (incoming edges). Then we can assign indices (1..k) for that node. During DP processing, when we insert an edge to node b_i with weight w_i, we know its index in that node's compressed list, and we can update a BIT (Fenwick) for that node with that index, storing the max dp. Since we need to query for maximum dp for weights < w_i at node a_i, we would query the BIT for node a_i over indices less than the index of w_i (if w_i exists in a_i's list; if not, we need to find the greatest index with weight < w_i). However, a_i might have weights that are not exactly w_i. But we need max over weights < w_i. So we can find the largest compressed index among weights that are < w_i. Since we have the sorted list of unique weights for node a_i, we can binary search to find the position (upper bound) of w_i, and query BIT up to that index-1.
But we must be careful: The BIT for a node will store the maximum dp among edges that have been inserted so far (i.e., processed edges) for each weight? Actually, each insertion corresponds to an edge ending at that node, with a specific weight w and dp value. There can be multiple edges with same weight ending at the same node; we need to take max over them. Since we are doing BIT for maximum, we can update the position for weight w with value dp, but if later another edge with same weight gives a larger dp, we should update the BIT to the larger value. BIT for max can handle point updates: set value at index to max(old, new). So that's fine.
Now, we need to precompute for each node the sorted list of distinct weights from all edges that end at that node. However, note: we query on node a_i, which is the source of current edge. But the DP transition uses edges that end at a_i. So we need for each node, the set of weights from edges whose destination is that node. Yes. So we can first read all edges, record for each node the weights of edges that point to it (i.e., incoming edges). For node x, we collect all w such that there exists an edge (a,b,w) with b = x. Then sort and deduplicate.
Then when we process edges in order, for edge i: we need to query node a_i for max dp among incoming edges with weight < w_i. So we use the BIT for node a_i, and query up to index corresponding to w_i (exclusive). Then dp[i] = that max + 1 (if any, else 1). Then after computing dp[i], we need to update the BIT for node b_i, at the index of weight w_i, with dp[i] (if larger than current).
That works if we have a BIT per node, but the total memory for all BITs: each BIT size is equal to the number of distinct weights for that node. Summed over all nodes, total distinct (node, weight) pairs is at most m (since each edge contributes one weight to its destination node; if multiple edges to same node with same weight, they count as duplicate weight, but we deduplicate, so distinct pairs <= m). So total size of all BITs is O(m). However, a BIT typically uses an array of size (k+1) for k distinct weights. So total memory O(m). That's acceptable (1e5). But we need to build BIT structures for each node, but many nodes may have 0 incoming edges. For those, we don't need a BIT. We'll only allocate BITs for nodes that have at least one incoming edge (i.e., indegree > 0). But note: we also need to query for node a_i; a_i could be any node, and if it has no incoming edges, then the query returns 0. So we can handle that by checking if node a_i has a BIT: if not, max = 0.
One nuance: When we query for node a_i, we need to consider only edges that have been processed already (i.e., j < i). Since we update BIT after computing dp for each edge, and we process in order, the BIT for node a_i contains exactly edges ending at a_i with index < i. Good.
Thus the algorithm:
- Read n, m.
- Read all edges into arrays a[1..m], b[1..m], w[1..m].
- For each node v, collect list weights_in[v] = all w_i where b_i == v.
- For each v with non-empty list, sort, deduplicate. Let compw[v] = sorted unique list.
We'll also create a BIT (Fenwick tree for maximum) of size len(compw[v]) + 1 (1-indexed). Initialize all values to 0 (or -inf, but max with 0 is fine; dp can be 0 if no edge). Actually base dp=1; so query returns max dp among previous edges; if none, we treat as 0. So BIT values can be 0 initially.
- Process edges in order i=1..m:
- Let u = a_i, v = b_i, weight = w_i.
- Query on node u:
if u has no BIT (no incoming edges at all), then best = 0.
else:
binary search in compw[u] to find the position idx such that compw[u][idx] < weight. Actually we need all weights < weight. So we find the rightmost index where weight < w_i. Since compw[u] is sorted, we can use bisect_left to find the first index where weight >= w_i. Then the number of weights < w_i is that index (since Python's bisect_left returns insertion point to maintain sorted order). So query BIT up to index (the count of weights less than weight) (i.e., idx). Because BIT indices are 1-based: if idx = 0, then query returns 0.
best = query_max(BIT_u, idx) (since idx is count of elements less than w_i, that matches positions 1..idx)
- dp = best + 1.
- Update BIT for node v at position corresponding to weight w_i:
if v has BIT:
find index pos = index of weight w_i in compw[v] (since we deduplicated, weight must be present because we collected all incoming weights for v; but careful: edge i ends at v, so w_i is in the list for node v, by construction). So we can get pos (1-indexed: pos_in_sorted+1). Then update BIT_v at pos with dp (i.e., set BIT[pos] = max(BIT[pos], dp)).
- Keep track of global maximum answer = max(answer, dp).
Return answer.
Time complexity: O(m log D) where D is the number of distinct weights per node, but with binary search and BIT operations O(log indegree_unique). Since each edge incurs one query and one update, total O(m log m). Preprocessing O(m log m) for sorting per node lists.
But we need to ensure that for each node we can efficiently binary search in its compressed list. That's fine.
Now we must consider correctness: The DP ensures that we pick edges in increasing index order because we process in input order and only consider previous edges. The weight condition is enforced by querying only weights < w_i. The path connectivity is enforced because we only transition from edges ending at a_i. So dp[i] gives the maximum length of a valid path ending with edge i. The path may reuse nodes arbitrarily; that's allowed.
Potential pitfalls: Self-loops? Edge from a to a. That's fine; if we have edge i from x to x, then for a later edge j starting at x, we could use edge i as previous if weight condition satisfied. In our DP, edge i ends at x, so it will be inserted into BIT of node x; later when we process edge j with a_j = x, we query BIT for node x, and if weight_i < weight_j and index_i < index_j, then it will be considered because BIT query includes all previous edges ending at x with weight < w_j. So self-loop works.
Multiple edges: They may have same weight; since condition is strictly increasing, we cannot use same weight. Our query excludes equal weights because we query for weights < w_i; we don't include those with equal weight. So that's correct.
Edge weights can be 0; that's fine.
Now we need to implement BIT for maximum (prefix max). BIT typically supports point update and prefix max query, but standard BIT is for sum. For max, we can use Fenwick tree where update: while i <= n: tree[i] = max(tree[i], val); i += i&-i. Query: ans = 0; while i>0: ans = max(ans, tree[i]); i -= i&-i. However, note that this works only if updates are monotonic (only increasing values). Because if later we update a point with a larger value, we set tree[i] = max. But if we ever needed to decrease a value, it wouldn't work. But here we only ever set to a max, and we never decrease; values only increase because dp for a given weight may increase as we process edges with that weight (if later edges with same weight have larger dp, we update to the max). So that's fine.
But careful: Could there be a scenario where an earlier edge gave a high dp for a weight, and later a different edge gives a lower dp? We would still keep the higher because we take max. So correct.
Now we need to be careful with the query: BIT prefix max up to index idx. Since we inserted edges in order, but if multiple edges with same weight, the BIT stores the maximum dp among them. However, there is a subtlety: When we query for weights < w_i, we consider edges that may have been inserted later but have weight < w_i? Actually we query after processing up to i-1, so all edges with index < i are inserted. That's correct.
Now consider: If there are multiple edges ending at node u with same weight w, and we query for a later edge with weight > w, we will get the max dp among all those edges (since they all have weight w < current). That's fine.
Now we must handle the case where node a_i has incoming edges but the compressed list may have weights that are less than w_i. However, we binary search to get idx, the count of weights strictly less than w_i. That's correct. But what if there are weights less than w_i but those weights have not yet been inserted (because edges with those weights ending at a_i might appear later in input order)? In our BIT, we only have inserted edges that have been processed (index < i). So the BIT may have some of those weights inserted, some not. The BIT initially all zero. When we query prefix max, we get max among those inserted so far. So it's correct.
Now about building the compressed list: We need for each node v, the list of distinct weights from all edges that end at v. That's necessary to assign positions. We'll also need to map weight to index quickly for updates. Since we will process edges in order, for each edge we need to know the index of its weight in the compressed list of its destination node (for update). We can precompute for each edge its position in its destination node's list. Because we have the list, we can store for each edge an update_index (pos) for destination. For query, we need to compute idx for node a_i based on weight w_i; we can binary search at query time. That's acceptable O(log indegree).
Alternatively, we can precompute for each node a mapping from weight to index (using dictionary). That would be convenient. For each node with incoming edges, after we have sorted unique list, we can create a dict weight_to_index (1-indexed). Then for update we can just look up the index from that dict. For query, we need to compute the number of weights less than w_i; we can binary search the list (bisect_left) and get idx = that position (0-based). Then query up to idx (since BIT is 1-indexed, we query upto idx). If idx==0, query returns 0.
Complexities: O(m log m) overall.
Edge case: If there are no edges, m=0? But m>=1 as per constraints? 1 ≤ m ≤ 100000. So m at least 1.
Now confirm with examples:
Example 1:
n=3, m=3
1: 3 1 3
2: 1 2 1
3: 2 3 2
Process:
Preprocess incoming weights:
Node 1: edges ending? Edge 1 ends at 1 (3->1 w=3). So weights_in[1] = [3]
Node 2: edge2 ends at 2 (1->2 w=1). So [1]
Node 3: edge3 ends at 3 (2->3 w=2). So [2]
Create BITs.
i=1: u=3, v=1, w=3. Query node 3: node 3 has BIT? It has incoming edges? Node 3 has weight list [2] from edge3, but edge3 hasn't been processed yet. So node3 currently has no BIT because it has incoming edges? Actually node3 does have incoming edges (edge3) but we only create BITs for nodes that have incoming edges at all. So node3 will have a BIT (size 1). However, at i=1, we haven't inserted any edge into BIT for node3 yet. So BIT of node3 is all zeros. Query for weights < 3: compw[3] = [2]; bisect_left([2], 3) -> index 1 (since 2 <3, insertion position after the element). So idx=1. Query BIT upto 1: returns 0. dp=1. Update node1 BIT: weight 3 in compw[1]=[3]; pos=1; update BIT1 at pos1 with dp=1.
i=2: u=1, v=2, w=1. Query node1: compw[1]=[3]; bisect_left([3],1) -> 0 (since 3 >1). idx=0 -> query returns 0. dp=1. Update node2: compw[2]=[1]; pos=1; update BIT2 at pos1 with dp=1.
i=3: u=2, v=3, w=2. Query node2: compw[2]=[1]; bisect_left([1],2) -> 1 (since 1 <2). idx=1; query BIT2 up to 1. BIT2 currently has entry for weight1 with dp=1. So max=1. dp=2. Update node3: compw[3]=[2]; pos=1; update BIT3 at pos1 with dp=2. Answer = 2. Works.
Second example:
5 5
1: 1 3 2
2: 3 2 3
3: 3 4 5
4: 5 4 0
5: 4 5 8
Preprocess incoming weights:
Node1? edges ending at 1? None.
Node2: edge2 ends at 2 (w=3)
Node3: edge1 ends at 3 (w=2)
Node4: edge3 ends at 4 (w=5), edge4 ends at 4 (w=0) -> [0,5] sorted [0,5]? Actually weights: 5 and 0 -> [0,5]
Node5: edge5 ends at 5 (w=8)
Thus BITs for nodes 2,3,4,5.
Process:
i=1: u=1, v=3, w=2. Node1 has no incoming edges => query best=0. dp=1. Update node3: weight2 in compw[3]=[2]; pos=1; update BIT3 with 1.
i=2: u=3, v=2, w=3. Node3 BIT exists: compw[3]=[2]; bisect_left([2],3) -> 1 (since 2<3). idx=1; query BIT3 up to1: current max = 1 (from edge1). dp=2. Update node2: weight3 in compw[2]=[3]; pos=1; update BIT2 with 2.
i=3: u=3, v=4, w=5. Node3: query BIT3: compw[3]=[2]; bisect_left([2],5) -> 1; idx=1; query returns still 1 (since only edge1). dp=2 (maybe 1+1=2). Actually best=1 => dp=2. Update node4: weight5 in compw[4]=[0,5]; pos? 0->index1? Actually sorted [0,5] -> indices: 0->1, 5->2. So weight5 pos=2. Update BIT4 at pos2 with dp=2.
i=4: u=5, v=4, w=0. Node5: has BIT? Node5 has incoming weight [8] but no edge inserted yet. So BIT5 all zeros. But also query: compw[5]=[8]; bisect_left([8],0) -> 0; idx=0 -> best=0. dp=1. Update node4: weight0 pos=1 (since [0,5] index1). Update BIT4 at pos1 with dp=1. Since BIT4 may have other values; update with max.
i=5: u=4, v=5, w=8. Node4: compw[4]=[0,5]; bisect_left([0,5],8) -> 2 (both <8). idx=2. Query BIT4 up to index2: BIT4 currently has at pos1=1 (from edge4), pos2=2 (from edge3). Also might have? That's it. So max=2. dp=3. Update node5: weight8 pos=1; update BIT5 with dp=3.
Answer=3. Matches example.
Thus algorithm works.
Now let's consider complexities: For each node, we need to create a BIT. Implementation: We'll have arrays (or dict) for nodes: compw = list of sorted unique weights; bit = list of ints (Fenwick). Because n up to 1e5, we can store for each node a structure (maybe as a dict mapping node index to its BIT). We'll store compw and bit as Python lists inside a list of length n+1, but many may be None.
Memory: Each BIT size = len(compw)+1. Sum len(compw) across nodes <= number of distinct (node, weight) pairs, which is at most m (since each edge contributes one weight, but duplicates across edges with same weight to same node count once). In worst case, if all edges go to different nodes or same node but all weights distinct, sum lengths = m. So total BIT array size ~ O(m). Acceptable.
Implementation details in Python:
-
Read n,m.
-
Initialize arrays a = [0]*m, b = [0]*m, w = [0]*m.
-
Also create list incoming_weights = [ [] for _ in range(n+1) ].
-
For i in range(m):
read a_i, b_i, w_i
a[i] = a_i; b[i] = b_i; w[i] = w_i
incoming_weights[b_i].append(w_i)
-
After reading all, for v in 1..n: if incoming_weights[v] not empty: sort and deduplicate. We can use sorted(set(list)). Then store compw[v] = the sorted list. Also create a dict mapping weight to index (1-based) for updates: For idx, val in enumerate(compw[v], start=1): weight_to_idx[v][val] = idx. Since we need this for updates for edges where v is destination. We'll store weight_to_idx[v] as a dict.
Also create BIT list for v: bit[v] = [0]*(len(compw[v])+1) # 1-indexed.
If incoming_weights[v] empty, compw[v] = empty list, bit[v] = None, weight_to_idx[v] = None.
Now process edges in order (0-indexed maybe). Keep answer = 0.
For i in range(m):
u = a[i]; v = b[i]; weight = w[i]
# query for u
if bit[u] is not None:
# binary search in compw[u] for position of first weight >= weight
idx = bisect_left(compw[u], weight) # returns number of elements < weight
if idx > 0:
best = query(bit[u], idx) # query prefix max up to idx
else:
best = 0
else:
best = 0
dp = best + 1
answer = max(answer, dp)
# update for v
if bit[v] is not None:
pos = weight_to_idx[v][weight] # must exist
update(bit[v], pos, dp)
Implementation of BIT functions:
def update(bit, i, val):
while i < len(bit):
if val > bit[i]:
bit[i] = val
else:
# not needed to update if not larger but we still loop? We can break if val <= bit[i]? Not safe because there may be higher indices that also need update if they previously had lower values? Actually BIT for max: each node stores max over a range. If we are updating at position i with a new value val, we need to propagate to all BIT nodes that cover this position. Even if the current BIT[i] is already >= val, it's still possible that some ancestor BIT nodes (i+lowbit) might have the same or larger, but if they are already >= val, then no need to update them? Actually if bit[i] >= val, then the ancestor nodes that include this position might also be >= val, but we can't guarantee because the ancestor might have a smaller value that came from a different range and bit[i] might be from that range? In BIT for max, the typical update algorithm sets bit[idx] = max(bit[idx], val) for all idx that include i. If at some ancestor, bit[idx] is already >= val, then we can skip updating further? But careful: Suppose ancestor node bit[j] currently stores max over a range that includes i. If bit[j] is already >= val, then we don't need to change it. If bit[j] < val, we need to set it to val. However, if bit[i] is already >= val, it's possible that bit[j] might be lower? But bit[j] should be the max over its range, which includes i, so its value must be at least bit[i] (since it originally took max over updates). Actually, when we did previous updates, we updated both bit[i] and bit[j] accordingly. So bit[j] is the max over all updates that affected its range. If we are now updating with a value that is <= bit[i] (which is <= bit[j] because bit[j] >= bit[i]), then bit[j] is already >= val. So we don't need to update any ancestors. So we can early break if val <= bit[i] before updating? But we still need to check ancestors? Actually, we need to traverse up the tree. The standard approach for max BIT is:
while i <= N:
bit[i] = max(bit[i], val)
i += i & -i
This works and doesn't break early. Since bit[i] is monotonic non-decreasing, the complexity is O(log N). Early break could potentially save time but we cannot break simply if bit[i] >= val because ancestors might need update even if bit[i] is already larger? As argued, ancestors cover i and other positions. If bit[i] is already >= val, ancestors are at least that. But consider a scenario: previous updates set bit[i] to a high value, but ancestors might not have been updated because maybe that high value came from an update at a different index that doesn't affect ancestors? Actually in BIT, each update touches all nodes that cover the index i. So when we set bit[i] to a high value, we also updated all ancestors. So ancestors should be at least as high as the value at leaf? Wait, in BIT for max, when we update at index i with value val, we do bit[i] = max(bit[i], val); then go to i + lowbit(i) and do the same. So if we previously updated with a high value, both the leaf and its ancestors would have been set to at least that high value. So the ancestors will have values >= that high value. Therefore if we now have a new value <= that high value, the leaf and ancestors are already >= new val, so we can skip the update entirely (not just stop after leaf). But we don't know that before checking the leaf. However we can check if val <= current bit[i] and also for all ancestors? Actually we can't know ancestors without checking. But we can start from leaf and if bit[i] >= val, we can break because ancestors are >= bit[i]? Not necessarily: It could be that bit[i] is high but ancestors may be lower because earlier updates might have set bit[i] high but ancestors were not updated because maybe they were updated from other positions but not with that high value? Let's reason: In BIT for max, each node stores the maximum value among all indices that fall within its range. For an index i, the nodes that cover i are: i, i+lowbit(i), i+lowbit(i)+lowbit(i+lowbit(i)), ... up to N. Each of these nodes's range includes i. When we update with a value val, we set each such node's stored max to max(current, val). Therefore, if we had previously updated with a high value H at index i, then for each of those nodes, we would have set their stored max to at least H. So they will be >= H. So if current val <= H, then all those nodes already have a value >= H >= val. So no need to update any of them. So if at the leaf node bit[i] >= val, we can break, because we know that the leaf's current value >= val implies that all ancestors (since they contain the leaf) must have been updated to at least that value at the time of that update. However, could it be that after that update, some other update at a different index caused an ancestor to be reduced? No, BIT for max only increases values; it never reduces. So ancestors are monotonic non-decreasing. So once they are set to at least H, they stay at least H. Therefore if the leaf has a value >= val, then ancestors are at least that leaf's value, which is >= val. So we can break early. But we must be careful: The leaf's value might be high, but perhaps the ancestor's value is lower because the leaf's value came from a different update? Actually if leaf's value is high, it must have been set via an update that also updated ancestors. So ancestors should be at least that high. So breaking is safe.
But to be safe and simple, we can just do the full loop O(log N) which is fine given m=1e5, log up to ~17. So we can implement straightforwardly.
def update(bit, i, val):
while i < len(bit):
if val > bit[i]:
bit[i] = val
i += i & -i
def query(bit, i):
res = 0
while i > 0:
if bit[i] > res:
res = bit[i]
i -= i & -i
return res
Now, careful: In update, bit length is len(compw)+1, so the max index is len(compw). So while i <= N (where N = len(bit)-1). So while i < len(bit) (since bit is 0..N inclusive, bit[0] not used). Condition i < len(bit) works because len(bit) = N+1, so i <= N is i < len(bit). So while i < len(bit): works.
Now about binary search: We'll use bisect from Python's bisect module.
from bisect import bisect_left
idx = bisect_left(compw[u], weight) # gives count of elements < weight (since it returns insertion point before any equal). Since we want strictly less, we query up to idx (which is number of elements < weight). So query(bit_u, idx) works.
But note: bit indices start at 1, and compw list is 0-indexed. So if compw length = k, indices 1..k correspond to sorted weights. The number of weights less than weight is idx (0..k). So query upto idx works.
Now, one more nuance: What if there are weights equal to weight? They are not included because idx points to first position where weight >= w_i, so weights at positions idx... are >= w_i. So they are excluded.
Now, for updates: pos = weight_to_idx[v][weight] which is 1-indexed. That exists because we added all weights for incoming edges of v.
But what if there are duplicate weights to same node? weight_to_idx[v] will map weight to a single index. When we update, we set BIT at that index to max of dp values for that weight. So multiple edges with same weight to same node will keep the highest dp. That's correct, because when we later query for a weight > that weight, we can use the best dp from that weight, regardless of which edge gave it. However, we must be careful about index order: If there are two edges with same weight ending at node x, one appears earlier (j) and one later (k). When we process a later edge i that starts at x, we can only use edges j or k if they have index < i and weight < w_i. Since they have same weight, they both satisfy weight < w_i if w_i > weight. But the DP value for that weight may be higher from the later edge k, but note: when we process i, we have already inserted edges up to i-1. If k < i (i.e., k is before i), then k is already inserted; if k > i, then not inserted. But if we store only the maximum dp for that weight, that max might come from an edge that appears after i? No, because we only insert edges after processing them. So at the time of query for i, the BIT contains only edges with index < i. So if the maximum dp for that weight comes from an edge that occurs later (index > i), it won't be in BIT yet. So storing the maximum among all inserted so far is correct. So updating with max ensures that for each weight we keep the best dp among all edges processed up to now. That's what we need for future queries.
Now, what about the case where we update a weight with a dp that is lower than current stored? Then we don't change BIT. That's fine.
Now we must consider that we might also need to update the BIT for a node when the same weight appears multiple times with increasing dp values. The update will set the BIT to the higher dp, and propagate to ancestors. That works.
Thus algorithm should produce correct answer.
Now let's test with some custom cases:
Case: n=2,m=3
1: 1 2 1
2: 2 1 2
3: 1 2 3
We expect max path: edge1 (1->2 w1), edge2 (2->1 w2) yields path length 2? But check indices: i1=1, i2=2, weights 1<2, connectivity: b1=2, a2=2? Actually a2=2, yes. So path: 1->2 (1), 2->1 (2). That's valid. Could also add edge3 after edge2? Edge3 starts at 1, so after edge2 we are at node1? Edge2 ends at 1, so we can then take edge3 (1->2) weight 3. So path: 1,2,3 => length 3? Check indices: 1<2<3; weights 1<2<3; connectivity: b1=2 matches a2=2, b2=1 matches a3=1. So length 3. So answer should be 3. Our DP:
- Edge1 dp=1, update node2.
- Edge2: query node2 (a2=2) for w<2: node2 has weight 1 inserted? Edge1 ends at node2 with weight1, so best=1, dp2=2. Update node1 with weight2.
- Edge3: query node1 for w<3: node1 has weight2 from edge2, best=2, dp3=3. Answer 3. Works.
Case with decreasing weights: Should ignore.
Case with equal weights: Not allowed.
Now, what about path that uses edges that are not in order of input but still indices increasing? Our DP inherently respects that.
Potential issue: The DP might consider sequences where the previous edge ends at a_i, but the path may have used that node multiple times. That's allowed.
Now, about memory: We'll store for each node a list compw and a BIT (list of ints) and a dict weight_to_idx. For nodes with no incoming edges, we can set compw = [] and bit = None and weight_to_idx = None. But in query, we need to check bit[u] is None to indicate no incoming edges. But what if node u has incoming edges but all with weight >= current weight? Then query returns 0; that's fine.
Now we need to be careful about Python recursion? Not used.
Now about time: For each edge, we do binary search O(log deg) (where deg is number of distinct weights for node u), plus BIT query O(log deg) and BIT update O(log deg_v). Summed over edges O(m log m) worst-case. With m=1e5, that's fine.
But we also need to build weight_to_idx dictionaries: For each node, we iterate over its compw list. That's O(m) total.
Now, we also need to consider the case where node a_i may have no BIT (no incoming edges) but we query and get 0. That's fine.
Now, about the fact that we use global answer = max dp. That's final.
Now think about possible pitfalls: The DP defined dp[i] as longest path ending at edge i. But could the optimal path not end at the last edge in terms of index? That's fine because we take max.
Now, is there any scenario where we need to consider paths that start from no edge? No, path must have at least one edge? The problem asks "choose a path" maybe length 0? Typically, we consider at least one edge. The DP with base 1 indicates at least one edge. If no edges? m≥1, so ignore.
Now, check sample notes: In first sample, they said you cannot traverse ... because edge appears earlier... That's enforced by index order.
All good.
Now we should implement.
Implementation plan:
-
Import sys, bisect
-
Read input: data = sys.stdin.read().split() for speed. Or use sys.stdin.buffer.
-
Parse n,m = map(int, data[0:2])
-
Then read edges: for i in range(m): a_i = int(data[3i+2]), b_i = int(data[3i+3]), w_i = int(data[3i+4])? Actually careful indexing: after first two numbers, there are 3m numbers. So we can loop.
Simplify:
it = iter(data)
n = int(next(it)); m = int(next(it))
a = [0]*m
b = [0]*m
w = [0]*m
incoming_weights = [[] for _ in range(n+1)]
for i in range(m):
a[i] = int(next(it))
b[i] = int(next(it))
w[i] = int(next(it))
incoming_weights[b[i]].append(w[i])
Now compress:
compw = [None](n+1)
bit = [None](n+1)
wt_idx = [None]*(n+1)
for v in range(1, n+1):
if incoming_weights[v]:
uniq = sorted(set(incoming_weights[v]))
compw[v] = uniq
# create BIT list of length len(uniq)+1, filled with 0
bit[v] = [0]*(len(uniq)+1)
# create mapping
wt_idx[v] = { weight: idx+1 for idx, weight in enumerate(uniq) }
else:
compw[v] = []
bit[v] = None
wt_idx[v] = None
Now DP loop:
from bisect import bisect_left
ans = 0
for i in range(m):
u = a[i]
weight = w[i]
best = 0
if bit[u] is not None:
idx = bisect_left(compw[u], weight) # count of weights < weight
if idx > 0:
# query bit[u] up to idx
bitu = bit[u]
res = 0
j = idx
while j > 0:
if bitu[j] > res:
res = bitu[j]
j -= j & -j
best = res
dp = best + 1
if dp > ans: ans = dp
v = b[i]
if bit[v] is not None:
pos = wt_idx[v][weight] # guaranteed to exist
# update bit[v] at pos with dp
bitv = bit[v]
j = pos
while j < len(bitv):
if dp > bitv[j]:
bitv[j] = dp
j += j & -j
print(ans)
We need to confirm that wt_idx[v][weight] exists for all edges because we built it from incoming_weights[v] which includes all weights from edges that end at v. Since edge i ends at v, weight w_i is in that list. So it exists.
Edge case: weight could be 0. That's fine.
Now, check if there is any node that has incoming_weights but we didn't allocate BIT because list empty? Already handled.
Now, we need to think about the possibility that node u has BIT but its compw list may not contain any weight < weight (idx=0) => best=0.
Now, could there be any issue where we query for node u that has BIT but compw list is not sorted? We sorted.
Now, is there any need to consider the scenario where we have to also consider not just the maximum dp among weights less than w_i, but also consider that the path could start at any node without needing a previous edge? Our dp already does that because if no previous edge, dp=1. That's the base.
Now, test with larger cases to ensure performance.
Potential memory: For each node, wt_idx is a dict. The total number of entries across all wt_idx dicts is sum of distinct weights per node ≤ m. So memory O(m). Acceptable.
Now, confirm that we don't need to consider node a_i that may have BIT but with weights that are not less than w_i? Already idx=0 returns 0.
Now, maybe there is a nuance: The input order condition says "these edges come in the order of input". Does that mean that the edges we pick must appear in the input in the order we traverse them? Yes, we interpreted as indices increasing. So correct.
Now, could there be any other interpretation like the weights must be increasing and the edges must be taken in the order they appear in the input, meaning we cannot skip an edge that appears between the ones we pick if it violates something? No, typical interpretation: we select a subsequence of edges that respects input order. That's what we did.
Now, check if there is any possibility that the path could reuse an edge? The problem says "possibly passing through same vertices multiple times", but edges? It says "choose a path (possibly passing through same vertices multiple times)" but it doesn't explicitly say we cannot reuse edges. Usually in a path, edges are not repeated, but it says "path (possibly passing through same vertices multiple times)". It doesn't say edges cannot be repeated. In typical path definition, edges are not repeated; but some problems allow repeating vertices but still edges are distinct? Actually "path" often means a walk where vertices can repeat but edges cannot repeat? There is "simple path" vs "walk". The problem says "path (possibly passing through same vertices multiple times)". That suggests it's a walk where vertices can repeat, but edges? Usually a walk can repeat edges as well, but they say "path" but clarify vertices can repeat. It might allow repeated edges? It doesn't explicitly forbid repeated edges. However, if we allowed repeated edges, then we could potentially have infinite length if there is a cycle with increasing weights? But weights must be strictly increasing, so repeated edges with same weight wouldn't be allowed, and because weights are finite, you cannot have infinite increasing sequence. Also, if you repeat an edge, its index is fixed; you cannot use the same edge twice because that would require picking it again, but you cannot pick the same edge twice in the sequence because indices would not be strictly increasing (they'd be equal). So you can't reuse an edge because you can't pick the same index twice. So effectively each edge can be used at most once. So it's fine.
Now, potential alternative solution: Could we use DP with segment tree over nodes sorted by weight? But we've already designed a solution.
Now, implement in Python, ensuring fast I/O.
Testing with given examples.
We'll also test with some edge cases:
- n=1, m=5 self-loops: edges: 1 1 0; 1 1 1; 1 1 2; 1 1 3; 1 1 4. Input order increasing weights already? Could be any order. If they are in increasing order, then we can take all 5. Our DP:
- Preprocess incoming weights for node1: all weights.
- Process in given order. If weights are in increasing order and indices increasing, then dp[i] = previous dp for node1 with weight < w_i +1. So would get 5. Works.
If weights are not monotonic: For example, edges: (1,1,5) idx1, (1,1,1) idx2, (1,1,2) idx3, (1,1,3) idx4. Then longest increasing subsequence by weight respecting indices and connectivity? But connectivity always holds because all edges start and end at node1. So it's essentially longest increasing subsequence (by weight) with index increasing. Our DP: For edge1 w=5, best=0->dp=1. Edge2 w=1, best=0->dp=1 (since no edge with weight<1). Edge3 w=2, query node1 for weights<2: compw node1 includes 1,2,3,5? Actually after preprocessing, node1's incoming weights: 5,1,2,3. Sorted [1,2,3,5]. At processing i=3 (w=2), we have inserted edges1 and 2. BIT for node1: after edge1 update weight5 pos=4 (if sorted list [1,2,3,5] indices 1:1,2:2,3:3,4:5). After edge2 update weight1 pos=1. So query for w<2: bisect_left([1,2,3,5],2) -> index1 (since 1<2, insertion point before 2). So idx=1 -> query BIT up to 1, gives dp=1 from edge2. So dp3=2. Edge4 w=3, query for <3: bisect_left([1,2,3,5],3)=2 (since 1,2 <3, insertion before 3). idx=2, query up to 2: max dp among weights 1 and 2? weight2 has dp2? Actually weight2 was updated by edge3 with dp=2; weight1 has dp=1. So max=2 -> dp4=3. So answer 3. That's correct LIS length? Actually indices: 2 (w=1),3 (w=2),4 (w=3) -> length3. Edge1 cannot be used because weight5 > others but index1 is before; cannot use after because index must increasing; so we can't do 1,2,3,4 because weight5 > 1? Actually weight5 > 1? 5 > 1, so if we try sequence edge1 (5) then edge2 (1) that violates weight increasing (5>1). So LIS in terms of indices: we need increasing weights. So longest is 3. Our DP gives 3. Good.
Now, check performance: With m=1e5, each operation log up to 17, so around 1.7 million operations, fine.
Now, consider potential overflow or negative values? dp values up to m (1e5) so int fine.
Now, we should ensure that BIT query returns max; we can implement as function to reduce code duplication. But inline loops may be okay.
But careful: In update, we used while j < len(bitv):. Since len(bitv) = N+1 (N distinct weights), indices go 1..N. So condition j < len(bitv) ensures we stop at N. That's correct.
Now, is there any scenario where a node u has BIT but its compw list is empty? That can't happen; if incoming_weights[v] exists, then list is non-empty. So bit is not None implies compw not empty. But it's possible that the list is empty if we initialized but no incoming edges? That's not the case.
Now, handle input where some nodes have no incoming edges: bit[u] is None, we treat best=0.
Now, test with second sample manually using code later.
Now, verify with some random small cases by brute force to ensure correctness. But since we cannot run here, we can reason.
But consider scenario with multiple edges ending at same node with same weight. For node x, we have edges: e1: (some->x, w=5, dp=3), e2: (some->x, w=5, dp=5). BIT for node x at weight5 stores max dp (after e1 update, BIT pos for weight5 becomes 3; after e2 update, we update with 5, set to 5). So query later will get 5. Good.
Now, potential bug: When we query node u, we use bisect_left on compw[u] to get idx. But what if there are weights in compw[u] that are less than weight, but some of those weights haven't been inserted yet because edges with those weights haven't been processed (i.e., appear later). BIT query only includes inserted ones, so it's fine.
Now, think about memory overhead of storing incoming_weights for each node as list of all weights (including duplicates) before compression. That's O(m) extra, okay.
Now, is there any more optimized way? Not needed.
Now, code.
But we need to be careful about recursion limit? Not needed.
Now, discuss potential alternative: Use a segment tree over weights globally, but with node-specific condition? Another approach: For each weight, maintain a map of node->best. But we need to transition only if the previous edge ends at current start. That's like we need to combine node and weight. Our per-node BIT is natural.
Now, double-check: The DP is essentially similar to longest chain in DAG defined by edges with order constraints. But we reduced to per-node BIT.
Now, one more nuance: The path must be a sequence of edges where each consecutive pair satisfies b_j = a_i. This is exactly our transition condition. However, what about the path that starts at some node without an incoming edge? That's base case. So DP covers all.
Now, does our DP allow using edges that are not contiguous in terms of nodes? Actually we enforce b_j = a_i, so they are contiguous.
Now, we need to ensure that we treat the path as directed; it is directed, as given.
Now, any possibility of using multiple previous edges? DP picks the best single previous edge; because path is sequential, the optimal ending at edge i is formed by optimal ending at some previous edge j that ends at a_i. So DP works.
Now, confirm that our BIT query returns max over all edges ending at u with weight < w_i, regardless of their own index order. But since we process in order, we only have inserted edges with index < i. So correct.
Now, answer is maximum dp.
Now, implement.
But need to think about possible integer sizes: weight up to 100000, dp up to 100000.
Now, we will implement in Python. However, Python's speed might be a concern with loops and BIT operations for 100k edges, each with about 2*log(up to 100k) ~ 34 operations, plus binary search, total ~ 4 million operations, which is fine in Python if optimized. Use local variable lookups, avoid function calls inside loops. Write BIT operations inline to reduce overhead. But we can also define functions and call them, might still be okay. But we need to be careful with recursion? Not used.
I'll implement with inline loops for query and update, as above. Use local references to lists for speed.
Potential micro-optimizations: Use .append for incoming_weights instead of preallocating? Already using list.
Now, we should test with extreme case where all edges end at node 1 and start from node 1 (self-loops) and weights random. Then node 1's compw length = up to 100k distinct weights. BIT size 100001. BIT operations O(log 100k) ~17. So total ~ 3.4 million BIT steps, fine.
Now, what about memory for weight_to_idx for node1: dict with up to 100k entries, okay.
Now, maybe we can avoid dict for weight_to_idx by binary searching for pos at update time. Since we need to update BIT for node v with weight w_i, we could binary search in compw[v] to find index. That would add another log factor per edge (so 2 binary searches per edge: one for query (bisect_left on a_i) and one for update (bisect_left on b_i) to get pos). But we already have a dict for faster O(1). That's good.
Now, need to ensure that for node v, the weight is guaranteed to be in compw[v]; it is because we added all w_i from edges ending at v. So dict works.
Now, consider if there is an edge with weight not present in compw[v] due to some bug; but that would be an error. So fine.
Now, ready to write final solution.
We'll also include some test harness? Not needed.
Now, final answer.
But before final, check potential off-by-one: In BIT query, we query up to idx, where idx is number of elements < weight. Because indices 1..idx correspond to those weights. For example, compw = [1,2,3], weight=3, bisect_left returns 2 (since 1,2 <3). So idx=2, we query BIT up to 2, which includes weights 1 and 2. That's correct. If weight=0, bisect_left returns 0, query 0 returns 0.
Now, update: For node v, weight w_i, we get pos from dict, which is index (1-indexed). Works.
Now, also need to handle if node v has BIT but we might have multiple updates for same pos; we just update.
Now, complexity of building dict: For each node, we create a dict by iterating over compw list. That's fine.
Now, consider if a node has many duplicate weights; compw will have unique weights; fine.
Now, is there any case where the path could use edges that are not in increasing index but still satisfy "come in the order of input"? That is ambiguous: Could it mean that when you traverse the path, the edges you take must appear in the input in the same order as you traverse them? That is exactly index increasing. So good.
Now, we produce final code.
We'll write with sys.stdin.buffer.read for speed.
Edge Cases:
- n=100000, m=100000, all edges to different nodes? But we need to check memory: For each node, we may have very small BIT. fine.
Now, test with sample inputs.
I'll simulate quickly:
Sample1: Output 2. OK.
Sample2: Output 3. OK.
Now, more test: n=2,m=2; edges: 1 2 5; 2 1 4. Since weights decreasing, can't pick both. Max length 1. DP: first edge dp=1, update node2; second edge: query node2 (a2=2) for w<4: node2 has weight5? No, node2 has incoming weight from edge1? Edge1 ends at node2 weight5. But weight5 >4, so query idx? compw[2]=[5]; bisect_left([5],4)=0, best=0 => dp=1. Answer=1. Good.
Now, if weights increasing: 1 2 1; 2 1 2. Both length 2. DP: first edge dp=1 update node2; second edge query node2: compw[2]=[1]; bisect_left([1],2)=1, query BIT up to 1 gives 1 => dp=2. Answer=2.
Now, test with multiple possibilities: n=3,m=4:
1: 1 2 1
2: 2 3 2
3: 3 1 3
4: 1 2 4
Longest: edges 1,2,3,4? Check connectivity: 1->2,2->3,3->1, then 4 from 1->2 weight 4. Sequence indices 1,2,3,4: weights 1,2,3,4 increasing, connectivity holds: b1=2=a2, b2=3=a3, b3=1=a4? Actually a4=1, b3=1, yes. So length 4. DP should produce 4.
Preprocess: incoming: node1 from edge3 (w3=3) -> [3]; node2 from edge1 (w1=1) and edge4 (w4=4) -> [1,4]; node3 from edge2 (w2=2) -> [2].
Processing:
i1: u=1? a1=1, v=2, w=1. Node1 has BIT? Node1 incoming [3] -> compw[1]=[3], bit[1]. Query node1: bisect_left([3],1)=0 => best=0 => dp1=1. Update node2: pos for weight1 in node2 dict = index1? compw[2]=[1,4]; weight1 pos=1. Update BIT2 at pos1 with 1.
i2: u=2, w=2. Node2: compw[2]=[1,4]; bisect_left([1,4],2)=1 (since 1<2, next 4>2). idx=1, query BIT2 up to1: max=1 => dp2=2. Update node3: node3 compw[3]=[2]; pos=1; update BIT3 with 2.
i3: u=3, w=3. Node3: compw[3]=[2]; bisect_left([2],3)=1; query BIT3 up to1: max=2 => dp3=3. Update node1: node1 compw[1]=[3]; pos=1; update BIT1 with 3.
i4: u=1, w=4. Node1: compw[1]=[3]; bisect_left([3],4)=1; query BIT1 up to1: max=3 => dp4=4. Update node2: node2 compw[2]=[1,4]; weight4 pos=2; update BIT2 at pos2 with 4. Answer=4. Works.
Now, edge case: Node with multiple incoming weights, query for weight that is less than smallest weight in compw -> idx=0, best=0. Good.
Now, potential bug: In update, we need to update BIT even if dp is not larger than current stored at that position? We do if dp > bitv[j]; if dp <= bitv[j], we still need to continue to ancestors? Actually as argued, if dp <= bitv[pos], ancestors are already >= bitv[pos] >= dp, so no need to update any ancestors. So we can break early if dp <= bitv[pos]? But careful: The while loop updates all ancestors, but if we don't update because dp <= bitv[pos], we could break entirely. However, it's safe to continue the loop but doing extra comparisons; but to be safe and simple, we can still loop and compare at each step, which may be unnecessary but not costly. However, there is a nuance: Suppose at the leaf pos, bitv[pos] is high, but some ancestor might have a lower value because of some earlier updates that didn't propagate? No, because when we updated leaf earlier with a high value, we would have updated all ancestors to at least that high value. So they are at least leaf value. So if dp <= leaf, they are >= dp. So we could break. But to avoid bugs, we can just run loop and compare; it's fine.
But what about a scenario where leaf value is high but some ancestor is lower? That cannot happen because updates propagate to ancestors. So it's consistent.
Thus we keep simple.
Now, handle case where node v has BIT but weight is not present? Should not happen.
Now, final code.
One more check: We used bisect_left from bisect module. Ensure import.
Now, we should test with a case where node u has BIT but its compw list is empty? Not possible.
Now, consider potential speed of bisect_left: It's O(log size). Good.
Now, finalize.
But there is a nuance: The problem statement says "the weights of the edges are in strictly increasing order, and these edges come in the order of input." It might be interpreted that the edges we pick must be in the order they appear in the input, i.e., we cannot pick an edge that appears earlier after a later one. That's what we used. So fine.
Now, confirm that we don't need to consider the path's start node? No.
Now, possible improvement: Use arrays for compw and bit, but we already have.
Now, we need to ensure that we treat nodes 1-indexed correctly.
Now, write final solution.
I will produce final answer.
But wait: There's a catch. The problem might be from Codeforces? I recall a problem "Increasing Subsequence" but with graph? Hmm. Actually it might be similar to "D. Maximum path" but not sure. Anyway.
Double-check constraints: n up to 1e5, m up to 1e5, weights up to 1e5. Our algorithm fits.
Now, think about potential memory issue: storing incoming_weights as list of lists of size n+1, each list may have many ints. That's okay.
Now, finalize.
But I want to double-check that we didn't miss a condition: "these edges come in the order of input." Could also mean that when you traverse the path, the order of edges in the path must be the same as the order they appear in the input, but you can skip edges? That's what we did. Yes.
Now, final answer.
Edge Cases to test:
-
m=1: Answer 1.
-
n=100000, m=100000, all edges from i to i with random weights. Works.
-
Graph disconnected: works.
Now, let's consider if there is any situation where using a per-node BIT fails because we need to query for node a_i but a_i may have BIT but its compw list includes weight values that are not less than w_i, but the BIT query will only consider those less. Good.
Now, a potential optimization: Instead of per-node BIT, we could use a segment tree over weights globally where each leaf corresponds to a weight and stores a map node->best. But that would be more complex.
Now, finalize code.
But I should also think about using Python's array module or list.
Now, proceed.
Implementation in final channel. ```python
import sys
from bisect import bisect_left
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
a = [0] * m
b = [0] * m
w = [0] * m
incoming_weights = [[] for _ in range(n + 1)]
for i in range(m):
ai = int(next(it)); bi = int(next(it)); wi = int(next(it))
a[i] = ai
b[i] = bi
w[i] = wi
incoming_weights[bi].append(wi)
# Prepare compression and BITs per node (only for nodes with indegree > 0)
compw = [None] * (n + 1) # sorted list of distinct incoming weights
bit = [None] * (n + 1) # Fenwick tree (1-indexed) for maximum
w2idx = [None] * (n + 1) # mapping weight -> 1‑based index in compw
for v in range(1, n + 1):
if incoming_weights[v]:
uniq = sorted(set(incoming_weights[v]))
compw[v] = uniq
bit[v] = [0] * (len(uniq) + 1)
w2idx[v] = {wt: idx + 1 for idx, wt in enumerate(uniq)}
else:
compw[v] = []
bit[v] = None
w2idx[v] = None
ans = 0
for i in range(m):
u = a[i]
weight = w[i]
best = 0
# Query on node u: max dp among edges ending at u with weight < current weight
if bit[u] is not None:
idx = bisect_left(compw[u], weight) # number of weights < weight
if idx > 0:
bitu = bit[u]
j = idx
res = 0
while j > 0:
if bitu[j] > res:
res = bitu[j]
j -= j & -j
best = res
dp = best + 1
if dp > ans:
ans = dp
# Insert current edge into the structure of its destination node
v = b[i]
if bit[v] is not None:
pos = w2idx[v][weight] # guaranteed to exist
bitv = bit[v]
j = pos
while j < len(bitv):
if dp > bitv[j]:
bitv[j] = dp
j += j & -j
print(ans)
if name == "main":
main()