The "Road Accident" band is planning an unprecedented tour around Treeland. The RA fans are looking forward to the event and making bets on how many concerts their favorite group will have.
Treeland consists of n cities, some pairs of cities are connected by bidirectional roads. Overall the country has n - 1 roads. We know that it is possible to get to any city from any other one. The cities are numbered by integers from 1 to n. For every city we know its value ri — the number of people in it.
We know that the band will travel along some path, having concerts in some cities along the path. The band's path will not pass one city twice, each time they move to the city that hasn't been previously visited. Thus, the musicians will travel along some path (without visiting any city twice) and in some (not necessarily all) cities along the way they will have concerts.
The band plans to gather all the big stadiums and concert halls during the tour, so every time they will perform in a city which population is larger than the population of the previously visited with concert city. In other words, the sequence of population in the cities where the concerts will be held is strictly increasing.
In a recent interview with the leader of the "road accident" band promised to the fans that the band will give concert in the largest possible number of cities! Thus the band will travel along some chain of cities of Treeland and have concerts in some of these cities, so that the population number will increase, and the number of concerts will be the largest possible.
The fans of Treeland are frantically trying to figure out how many concerts the group will have in Treeland. Looks like they can't manage without some help from a real programmer! Help the fans find the sought number of concerts.
Input
The first line of the input contains integer n (2 ≤ n ≤ 6000) — the number of cities in Treeland. The next line contains n integers r1, r2, ..., rn (1 ≤ ri ≤ 106), where ri is the population of the i-th city. The next n - 1 lines contain the descriptions of the roads, one road per line. Each road is defined by a pair of integers aj, bj (1 ≤ aj, bj ≤ n) — the pair of the numbers of the cities that are connected by the j-th road. All numbers in the lines are separated by spaces.
Output
Print the number of cities where the "Road Accident" band will have concerts.
Examples
Input
6
1 2 3 4 5 1
1 2
2 3
3 4
3 5
3 6
Output
4
Input
5
1 2 3 4 5
1 2
1 3
2 4
3 5
Output
3
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 understand the problem: Given a tree with n nodes (n up to 6000). Each node has a value r_i (population). The band will travel along some simple path (no node repeated) and will have concerts in some nodes along that path (subset of nodes on the path) such that the sequence of values of concert nodes is strictly increasing. The goal is to maximize the length (number of concerts) of such a sequence. They will choose a path and then choose a subsequence of nodes on that path (preserving order along the path) that is strictly increasing in r values, to maximize the length. The answer is the maximum possible number of concerts.
Essentially, we need to compute the longest increasing subsequence along any simple path in the tree. But note: The path can be any simple path; we are free to pick the start and end nodes, and then we can select a subsequence (preserving the order along the path) that is strictly increasing. Since the path is simple (no cycles) and the order is along the path. The path can be traversed in either direction? Usually, a path is defined as a sequence of nodes where consecutive nodes are adjacent. The band can start at any city and travel along the path; they can decide to have concerts in some cities along the way. Since they will not visit a city twice, the path is simple. And they can choose the direction. So for a given undirected path, we can traverse it in two directions, yielding two sequences (reversed). The sequence of values must be strictly increasing. So we want the maximum length of a strictly increasing subsequence (not necessarily contiguous) along a simple path in either direction.
This is reminiscent of finding the longest increasing path in a tree, but with subsequence, not necessarily contiguous. However, because it's a path and we can skip nodes, the problem reduces to: for any pair of nodes u and v, consider the unique simple path between them, and we want the longest increasing subsequence along that path (in either direction). The answer is the maximum over all such paths.
n <= 6000, so O(n^2) might be possible, but maybe O(n^2 log n) is okay? 6000^2 = 36 million, which is borderline but perhaps okay in C++ with careful implementation. But we need to compute the longest increasing subsequence along a path quickly. Perhaps we can think in terms of DP on tree like LIS on paths? Another approach: Since the tree is small (n up to 6000), we could consider for each node as root, run a DFS that maintains some DP? But we need to consider paths that are not necessarily starting at root; they can be arbitrary. Could use centroid decomposition? But maybe O(n^2) is acceptable if we implement a method to compute LIS on a path in O(L) time, where L is the path length. Since sum of lengths over all paths would be O(n^3) if we naively, but we could use DP from each node? There are O(n^2) paths, but each path's length can be up to O(n), so total O(n^3) too large.
We need smarter method.
Observation: The longest increasing subsequence on a path is essentially the length of the longest chain of increasing values along the path where order matters. Because we can skip nodes, we just need to count how many nodes we can pick in increasing order. This is similar to: given a sequence a_1,...,a_k, what is the length of the longest increasing subsequence? That can be computed via patience sorting in O(k log k), but k can be up to n (max path length). If we could compute for each path quickly, maybe using DP that merges paths? Since the tree is small (6000), maybe we can try O(n^2) total: For each node as root, compute something? Actually, number of paths is O(n^2). If we can compute LIS for each path in O(1) after some preprocessing? Unlikely.
Alternative viewpoint: The maximum length of increasing subsequence along any path is equivalent to the size of the longest chain (in terms of values) that can be arranged along a simple path respecting tree adjacency? Wait, it's not just any chain; we need the nodes to lie on a simple path and the values to be increasing along the path. So we are looking for a path in the tree such that the sequence of values along the path (allowing skipping) is increasing. The maximum number of concerts is essentially the longest sequence of nodes v1, v2, ..., vk such that they are all distinct, each vi is a node, the vi's lie on some simple path in the tree in that order (i.e., there exists a simple path P with endpoints a and b, and the vi appear in order along P, not necessarily consecutive), and r(v1) < r(v2) < ... < r(vk). So we want to find the maximum k for which there exists a simple path containing an increasing sequence of nodes.
This can be seen as: we want to find a path that contains a strictly increasing subsequence of length k. This is similar to: we want to find a path where we can assign a direction such that the values are (not necessarily monotonic overall) but we can pick an increasing subsequence.
We could think of it as we want to find a path with a long increasing subsequence. Since we can skip nodes, the worst case we can always pick nodes that are increasing if we can order them by value along the path.
Maybe the answer equals the length of the longest chain in the tree that is increasing in value and forms a path? Actually, consider a path with nodes values: 1,5,2,6,3,7,4,8. The longest increasing subsequence is 1,2,3,4,5,6,7,8? Wait, careful: The LIS of that sequence is 1,2,3,4,6,7,8? Actually, compute: [1,5,2,6,3,7,4,8]. The LIS length is 5? Let's compute: 1,2,3,4,8 length 5; or 1,2,3,7,8 length 5; or 1,5,6,7,8 length 5. So it's 5. But maybe there exists a path where LIS is larger? Possibly. The maximum possible is n if values are strictly increasing along the path. But the tree may not have a Hamiltonian path with increasing values. So the problem is to find a path that best sorts the values.
Given n ≤ 6000, we could try to consider each node as the "minimum" of the increasing subsequence? Or maybe the problem can be reduced to computing for each pair of nodes the LCS? No.
Another approach: Since we can skip nodes, the LIS along a path is essentially the maximum number of nodes on that path that can be selected such that their values are increasing in the order they appear. This is like we are looking at the partial order defined by: node x < node y if x appears before y on the path and r_x < r_y. The size of the longest chain in this partial order is the LIS. So for a given path, it's the longest chain.
But maybe we can use DP on tree: For each node, we can consider paths that go through it. The LIS along a path that goes through a node could be derived from LIS on the two sides. However, LIS is not easily decomposable because it depends on the order of values along the path. But if we fix the direction, we can consider the path as concatenation of two sequences: from a node to one side (in reverse direction) and then to the other side. But the LIS might start on one side and continue on the other.
Alternatively, we can treat the path as a sequence of nodes. The LIS can be computed via DP where for each node we know the length of the longest increasing subsequence ending at that node for the prefix. If we could compute for any path from root, we can do it. But to consider all paths, maybe we can use rerooting or tree DP that for each node we compute two things: the longest increasing subsequence that starts at some node and goes away? But note: The subsequence must be increasing in the direction of travel. That is, if we pick a direction from some start to end, the sequence of selected nodes must have increasing r values. So essentially, we are looking for a directed path (in terms of direction of travel) but we can skip nodes. So we could think of it as we are selecting a sequence of nodes v1, v2, ..., vk such that for each i, vi and vi+1 are connected via a path that does not include any other v_j? Actually, since all nodes must lie on the same simple path, the order is along that path. So we can say: there exists a simple path P, and indices along P increasing. So the condition is that v_i appear in increasing order along P. For the purpose of existence of such P, we could equivalently say that the nodes v_i, when arranged in increasing order of their positions along the tree? Not exactly.
Maybe we can reframe: The set of nodes {v1,...,vk} with r(v1)<...<r(vk) must lie on a simple path, and moreover they must appear in that order along the path. That is, the path must visit them in increasing order of r. So if we can find a simple path that visits these nodes in that order, it's sufficient. So the problem is: find the longest increasing sequence of values such that the corresponding nodes are in order on some simple path. This is like a tree path that is "increasing" in terms of node values, but we can skip.
Observe that any increasing sequence of nodes that lie on a simple path and appear in that order along the path is equivalent to saying that the nodes are linearly ordered by both their r-values and by their positions on the path. Essentially, we need the nodes to be comparable in a certain partial order: For two nodes u and v, if there is a simple path that goes from u to v and we place u before v, then we need r_u < r_v and also that u is before v along the path. But given any two nodes, there is a unique simple path between them. So if we decide a direction from u to v, then the order is defined: u comes before v along the path. So if we have a sequence of nodes v1, v2, ..., vk with r increasing, we need that for every i < j, the unique path from vi to vj must have vi before vj? But that's always true if we consider the order along that path from vi to vj. However, the condition that all nodes lie on a single simple path is stronger: there must exist a simple path P that contains all nodes, and the order along P is consistent with the sequence order. That implies that the nodes must be collinear in the tree: they must all lie on a single simple path, which is equivalent to saying that the nodes are all on some path (i.e., there is a node that is the "median" etc). More concretely, a set of nodes lies on a simple path if and only if the tree induced by these nodes (the minimal subtree connecting them) is a path. That is, the nodes have at most two nodes of degree >1 in the induced subgraph? Actually, a tree is a path if all nodes have degree <=2. So for the set S = {v1,...,vk}, the subgraph formed by the union of all edges on the unique paths between any two nodes in S (the Steiner tree) must be a path (i.e., have no branching). Equivalently, there should be at most two nodes in S that are leaves of that tree (i.e., have degree 1 in the induced tree) and all internal nodes are in S or not? But nodes not in S can be on the path as well, but they are allowed because the path can include nodes not hosting concerts. So S is a subset of nodes on some simple path. That means that the nodes in S are totally ordered by their positions along that path. So we can think of ordering S by the path order. So the problem reduces to: find the largest set S of nodes such that their values are strictly increasing when ordered by their positions along some simple path that contains them. That path may also include other nodes not in S.
So we need to find a simple path P, and an increasing subsequence of the nodes on P (by value) maximizing its length. So it's exactly as originally.
Given n up to 6000, maybe we can try to compute LIS for each path, but there are O(n^2) paths. Could we compute for all paths in O(n^2) total using some dynamic programming that merges LIS from two ends? Let's explore.
Consider any path. The LIS can be computed in O(L log L). Summing over all paths would be O(n^2 log n) in worst-case if each path length is O(n), which is too high.
But maybe we can use the fact that tree is sparse and path lengths sum to O(n^2)? Actually, number of paths is O(n^2) and total length of all paths is sum_{u<v} dist(u,v). This sum can be O(n^3) in worst-case (e.g., a star: distances are 2 for many pairs, but length each path is 2 (two nodes plus maybe center?), actually star: For each pair of leaves, the path length is 2 edges: leaf-center-leaf, number of nodes = 3. So total length of all paths = sum_{pairs} (dist+1) maybe? But if we count nodes on each path, for star, number of pairs = O(n^2), each path has 3 nodes, so total nodes over all paths = O(n^2). In a line tree (path graph), the number of paths is O(n^2) and each path length can be up to n, so total sum of lengths over all paths is roughly sum_{i<j} (j-i+1) which is O(n^3). For n=6000, n^3 is 216e9, too large. So we cannot iterate over all paths explicitly.
We need a more clever method.
Could it be that the answer equals the length of the longest increasing subsequence in the entire tree if we consider the tree as a sequence along its diameter? Not necessarily; the best path might not be the whole tree.
Another thought: Since we can skip nodes, the LIS along a path is essentially the length of the longest chain that respects the order along that path. Could it be that the maximum possible LIS over all paths is equal to the length of the longest increasing chain in the tree that is also a path (i.e., a simple path where values are increasing along the path)? But we can skip, so we can have increasing values not necessarily monotonic along the path, but we can pick a subsequence. So it's more flexible. For example, in the path: 1,5,2,6,3,7,4,8, the LIS length is 5, while the longest monotonic increasing path (where each consecutive node is larger) is probably only 2? Actually, check consecutive: 1<5, 5>2,2<6,6>3,3<7,7>4,4<8, so the longest consecutive increasing segment is length 2. So LIS is longer.
We need to find max LIS over all paths.
Maybe we can think of it as: For each node as a potential "middle" of the increasing subsequence, we can combine increasing sequences from two directions, but careful with order. Suppose we have a path that goes through a node u. The LIS along the entire path could be either entirely on one side of u, or it could include u and some nodes from left side and some from right side, but note that if we include nodes from both sides, then the order along the path must be either left side nodes then u then right side nodes, or reversed. Without loss, we can fix direction: start from one endpoint, go through u, end at other endpoint. Then the LIS can be composed of an increasing subsequence from the left part ending at some value less than something, then u, then an increasing subsequence from the right part starting with values greater than u's value. However, the left part subsequence is taken from the prefix (nodes visited before u) and must be increasing and end with a value < r_u (if u is selected) because the next selected after that left part is u, so the last selected value before u must be < r_u. Similarly, if we don't select u, we might have left subsequence that continues into right subsequence, but then the transition must be from a selected node in left side to a selected node in right side with increasing values, but there could be nodes between them that are not selected. However, if we skip u, we still have the order: left side nodes (before u) then some nodes after u (right side). The LIS could skip u. So effectively, the LIS on concatenated sequence of left (in reverse order maybe) and right. But if we consider u as the splitting point, and we consider the path from some start to u and then from u to some end, we need the direction of traversal. Typically, to combine, we need the left part sequence in the order as traversed (from start to u) and the right part in order (from u to end). So the total sequence is left + right. The LIS can be computed as the maximum over splits: either LIS entirely in left, or entirely in right, or crossing that includes some from left and some from right. For crossing, we need the maximum length of an increasing subsequence that takes some suffix of the left part? Actually, in a concatenated sequence A then B, the LIS can be formed by taking some subsequence of A and some subsequence of B, but all elements from B come after all elements from A. So any crossing LIS consists of an increasing subsequence from A (call it SA) and an increasing subsequence from B (call it SB) such that max(SA) < min(SB)? No, not necessarily; because we can interleave: we could pick elements from A that are less than some elements from B, but also we could skip some elements from B that are too small. The condition for a combined subsequence is that for any element a from SA and b from SB, since a comes before b, we need a < b to keep increasing. So the last selected element from A must be less than the first selected element from B. But also earlier elements from A must be less than later from B, but that's automatically satisfied if each SA is increasing and the last element of SA is less than the first element of SB? Not exactly: Suppose SA = [2,5] (increasing), SB = [3,4] (increasing). Then the combined sequence would be 2,5,3,4. That's not increasing because 5 > 3. So we need that every element in SA is less than every element in SB. Because the order is SA (all elements) then SB (all). So we need max(SA) < min(SB). So crossing LIS with split at u is: choose a subsequence from left with values all less than some threshold, and a subsequence from right with values all greater than that threshold. This threshold is the value of the element that bridges them, which could be either an element from left that is the last selected, or an element from right that is the first selected. Alternatively, we can include u itself; then SA must have max < r_u and SB must have min > r_u.
Thus, to compute max crossing LIS, we might need to know for each possible threshold the maximum length of increasing subsequence entirely within left with all values less than threshold, and similarly within right with all values greater than threshold. But this seems complex.
Given n=6000, maybe we can afford O(n^2) DP. Since path lengths sum can be O(n^3) in worst case (line tree), but perhaps we can design an algorithm that runs in O(n^2) total for all paths using DP that computes LIS for all paths starting from each node? Let's think.
If we consider each node as root, and consider all paths that start at that root and go downwards, we can compute LIS for those paths incrementally. But we need all paths, not just root-paths. However, any path can be considered as two halves meeting at some LCA. If we root the tree arbitrarily, any path can be broken into an upward part from some node to its ancestor and then downward to another node. That is, the path from u to v can be represented as: go from u up to LCA(u,v), then down to v. The order along the path can be either direction: we could traverse from u to v or v to u. For LIS we can choose direction that yields longer sequence. So we can assume the path is oriented from u to v. Then the sequence is: nodes from u up to LCA (excluding LCA maybe included twice) and then from LCA down to v (excluding LCA if already counted? Usually path includes LCA once). So it's like two sequences: the upward part (starting from u, going upwards to LCA) in reverse order of depth; then the downward part (from LCA to v) in depth order.
If we fix the LCA as some node c, then paths that have c as LCA are those where one endpoint is in one subtree of c, the other endpoint in a different subtree (or possibly the same subtree? Actually LCA is c if u and v are in different child subtrees of c, or one is c itself). For each such path, the sequence is: go from u up to c (inclusive? we can decide). Actually the unique path from u to v: start at u, go up to c, then go down to v. If we traverse from u to v, the order is: nodes on the upward path from u to c (including u, then its parent, ... up to c), then nodes on the downward path from c to v (excluding c because already visited? Actually the path includes c once, so typically we list nodes: u = x0, x1, ..., xk = c, then y1, ..., ym = v, where y1 is a child of c? Actually if we go from u up to c, we will reach c. Then we go from c down to v; the first node after c is a child of c towards v. So the sequence includes c exactly once. So the total sequence is: nodes from u to c (including both) and then nodes from c to v (excluding c). So it's concatenation of A (nodes from u up to c, in that order) and B (nodes from c down to v, after c). But careful: A ends with c, B starts with child of c. So c is included only at the end of A.
Now, the LIS on this sequence can be computed if we know the LIS of A and B individually, but crossing involves elements from A (including possibly c) and B. Since c is the junction, it might be convenient to treat c as a pivot.
Maybe we can try to compute for each node c, and for each child subtree, we can compute something like: for each node x in that subtree, the LIS of the path from x up to c (including both) in the direction from x to c. Similarly, for each node y in that subtree, the LIS of the path from c to y (including both) in direction from c to y. Then we can combine two such halves from different subtrees to form a full path from x in subtree1 to y in subtree2, with LCA c. The total sequence would be: path from x to c (x -> ... -> c) then c -> ... -> y (excluding c? Actually c appears twice if we include both; we need to include c only once. But when concatenating, the path from x to c includes c at the end, and the path from c to y includes c at start. To avoid duplication, we should consider the full path as the sequence: nodes from x to c (including c) followed by nodes from c to y (excluding c). So the combined sequence length is len(A) + len(B) -1. Similarly, when computing LIS, we need to handle the duplication carefully.
But maybe we can treat the full path as two separate sequences: A (x to c) and B' (c's child to y) with c only once. So we can consider LIS that may include c or not.
Given the constraints (n <= 6000), perhaps we can try to compute the answer via DP that for each node as root, we compute the longest increasing subsequence for all downward paths? But we also need paths that go up and then down.
Alternate approach: Since n is relatively small (6000), maybe we can attempt O(n^2) algorithm by enumerating one endpoint and then doing DFS to compute something for all other endpoints. For each node u as start, we could perform a DFS that traverses the tree and builds the sequence of nodes along the current path from u to the current node v. As we DFS from u, we maintain the current path (the unique path from u to v). The order is along that path. We can compute LIS of the sequence dynamically as we extend the path? Could we compute the LIS length for the path from u to v for all v, in total O(n log n) per u? If we can, then overall O(n^2 log n) might be okay? n=6000, n^2=36e6, times log n (about 13) = 468e6 operations, maybe borderline but possibly okay in optimized C++? But we need to be careful: O(n^2) might be okay if constant small; O(n^2 log n) might be high but still could pass in 2 seconds? 36e6 * log2(6000) ~ 36e6 * 13 = 468 million. That's high but maybe optimized code could run within a few seconds? However, each operation would involve updating LIS (like patience sorting) which uses binary search and vector updates, constant moderate. 468 million binary searches maybe okay? Each binary search on vector of size up to n. But we would need to maintain the LIS while traversing, which is more involved.
Let's explore this idea: For a fixed start node u, we want to compute the LIS length for the path from u to every other node v, considering the path as the sequence of nodes visited when traveling from u to v (i.e., order along the unique path). Since the tree is undirected, we can root at u, and then the path from u to v is simply the nodes along the DFS from u to v in the rooted tree, which is the set of nodes on the simple path. So if we perform a DFS from u, we can maintain the current sequence of nodes from u to the current node. As we go down an edge, we append a node. As we backtrack, we remove it. So we can maintain a dynamic structure that supports appending a value and popping, and can compute the current LIS length? But LIS is not easily maintained with append/pop; we would need to recompute from scratch? There is a known data structure for maintaining LIS under online appends (like patience sorting), but supporting removal (pop) is hard. However, since the DFS stack corresponds to the path, and we are only appending and then popping (LIFO), maybe we can maintain the LIS using a persistent or rollback structure. Since n is only up to 6000, we could recompute LIS from scratch for each v? That would be O(L^2) per path, too heavy.
Instead, for each u, we could compute for each v by simulating the path sequence and performing patience sorting incrementally. Because DFS from u will traverse the tree, and when we go from a node to its child, we add child's value to the end of the sequence. We could maintain the patience piles (the array of tails) for the current sequence. When we add a value x, we update the piles: find the first pile where tail >= x (for strictly increasing LIS? Actually standard patience sorting for LIS: we maintain an array d where d[i] is the smallest possible tail of an increasing subsequence of length i. To compute LIS length, we process each element: find the first d[i] >= x (since strictly increasing, we need x > d[i-1]? Actually for strictly increasing LIS, we want d[i] to be the minimal tail for length i, and we update: find the first d[i] >= x (if any) and set d[i] = x; if none, append x. This gives length as size of d. So we can update d in O(log L) per insertion. But removal: when backtracking, we need to revert the last insertion. Since we are doing a depth-first traversal, we can maintain a stack of changes to d. When we insert, we record what we changed (maybe we replaced some d[i] or appended). When backtracking, we undo that change. This is feasible because the depth of recursion is at most n, and we can store the previous value of d[i] (or if we appended, we pop). So we can maintain d as a vector, with ability to rollback one operation. That would allow us to compute LIS for the current path at each node v in O(log n) per insertion, and O(1) per rollback (just revert the change). Over the whole DFS from u, we will have O(n) insertions and removals (since each node visited once in DFS). At each node v, we can record the current LIS length (size of d). So we can compute for all v from u in O(n log n) time. Then for each u, we get LIS lengths for all paths starting at u. But note: The path is considered from u to v in that direction. However, we could also consider the opposite direction (from v to u) which might yield a different LIS length because the sequence is reversed. Since the band can travel either direction along the path, the number of concerts for the path between u and v is the maximum of the LIS length of the sequence from u to v and the LIS length from v to u. But in our DFS from u, we only get the LIS from u to v (order u->...->v). To get the reverse, we could also run DFS from u but treat the sequence in reverse? Actually, if we start at u and go to v, the order is fixed. To get the LIS for the reverse order, we could also run DFS from each u and compute LIS on the reversed sequence? But maybe we can just compute both directions by considering each unordered pair once: we can run DFS from each u, compute LIS for u->v, and also compute LIS for v->u by symmetry? If we also run DFS from each v, we would get both. So overall we would compute all directed paths. But we only need the maximum over all undirected paths, so we can take the max of the two directions. So if we compute LIS for all ordered pairs (u,v) (u start, v end) we will cover both directions. That would be O(n^2 log n) total time because we do n DFSs each O(n log n) => O(n^2 log n). With n=6000, that's about 6000 * 6000 * log 6000? Wait, O(n^2 log n) from n DFS each O(n log n) would be O(n^2 log n) indeed: each DFS processes n nodes and each insertion O(log n). So total operations = n * (n * log n) = n^2 log n. That is about 36e6 * 13 ≈ 468 million operations as before. But maybe we can reduce constant: Each DFS visits each edge twice, total visits across all DFSs would be n * (2*(n-1))? Actually each DFS from a node visits all nodes once, so total node-visits across all DFS = n * n = n^2. For each node visited, we do an insertion (when we arrive) and later a rollback (when leaving). So total operations ~ 2 * n^2. For each insertion, we need to perform a binary search on the d array (current piles). The size of d is at most the LIS length, which is at most n. Binary search is O(log size). In worst-case, average log n. So total time is O(n^2 log n). 468 million binary searches is maybe okay in C++ with good optimization, but we also have overhead of recursion and vector operations. Could be borderline but perhaps acceptable given n <= 6000 and typical time limits (maybe 2-3 seconds)? Let's estimate more precisely: n=6000, n^2 = 36e6. For each node visit, we do:
binary search in vector (using lower_bound) O(log L) ~ up to 13.
possibly push_back or assign to vector.
store a rollback state (maybe a stack of changes).
We'll also need to update answer: at each node v during DFS from u, we have current LIS length = d.size(). That gives the length for path u->v. We take max answer = max(answer, current length). Also we should consider the reverse direction? But we are visiting each ordered pair (u,v) exactly once: when start is u and we reach v. That gives LIS length for direction u->v. Since the band can also travel from v to u, we might get a different length. But we will also later run DFS from v, and when we visit u, we will compute LIS for v->u. So overall we will consider both directions. So the global max over all ordered paths covers both. So we don't need extra.
But wait: Is the LIS computed on the sequence from u to v exactly the same as the longest increasing subsequence along that path when traveling from u to v? Yes, because the path order is fixed. So this works.
Now, we must be careful: The path from u to v includes both endpoints. In our DFS, when we go from u to v, we process nodes in order: we start at u (root) and then go down. But we need the entire sequence from u to v. At the moment we visit node v (i.e., when we first arrive), the current sequence on the stack (the recursion stack) is exactly the path from u to v. So if we maintain the LIS state incrementally as we go deeper, when we are at node v, the LIS of the current sequence (path) is computed. So that's correct.
However, there is a nuance: The band can choose any path and then pick a subsequence that is strictly increasing. The subsequence can be any nodes along the path in order. That's exactly the LIS on the sequence of node values along that path (in the direction of travel). So our computed LIS length for the directed path is correct for that direction.
Thus the plan: For each node as start (root), perform a DFS that traverses the entire tree. At each step (when entering a node), we insert its value into the LIS structure, update answer, then recursively visit children (neighbors except parent), then upon leaving, rollback the insertion. The LIS structure is based on patience sorting for strictly increasing subsequence.
Now we need to implement a rollback-friendly version of the patience piles. We maintain a vector d where d[i] is the smallest possible tail value of an increasing subsequence of length i+1 (or 1-indexed). Standard algorithm:
Initialize empty vector d.
For each new value x:
Find pos = lower_bound(d.begin(), d.end(), x) (first element >= x)
If pos == d.end(): d.push_back(x)
else: *pos = x
The LIS length is d.size().
This algorithm works for strictly increasing subsequence? Actually, for strictly increasing, we need to ensure we don't allow equal values because populations are distinct? The problem says ri are not necessarily distinct? It says "population is larger than the population of the previously visited with concert city" strictly increasing, so equal values are not allowed. Input constraints: ri from 1 to 10^6, but not guaranteed distinct. So we must handle equal values: if equal, they cannot both be in the increasing sequence because strictly larger is required. So we need strictly increasing, so when processing, if we have equal values, they cannot be part of the same increasing subsequence. In patience sorting for strictly increasing LIS, we use lower_bound (first >= x) to replace, which ensures we don't allow equal to extend? Actually, the standard LIS algorithm using lower_bound gives the length of the longest non-decreasing subsequence? Wait, recall: For strictly increasing LIS, we use lower_bound for d that stores the minimal tail of an increasing subsequence of length i+1, and we replace the first element that is >= x. This yields the length of the longest strictly increasing subsequence. I think for strictly increasing, it's correct: we want to find the first element that is >= x (since if we have equal, we cannot put equal after equal, so we replace the equal to maintain the smallest tail). Using lower_bound on a strictly increasing sequence? Actually, there are variants: For LIS (strictly increasing), the typical algorithm with binary search uses d[i] as the smallest tail value of an increasing subsequence of length i+1. The update: find the first d[i] >= x, set d[i] = x. If all d[i] < x, append x. This works for strictly increasing because when we have equal x, we replace the first element that is >= x, which might be an element equal to x, thus we keep the same length but potentially allow future numbers that are only slightly larger than x? It indeed gives the length of the longest non-decreasing subsequence? Let's test: Sequence [2,2]. Process 2: d empty -> push 2 => d=[2], length=1. Next 2: lower_bound(d,2) returns index0 (since d[0]=2 >=2), set d[0]=2 => d=[2]. length=1. So LIS (strictly increasing) length is 1, which is correct because can't have two equal in strictly increasing. If we used upper_bound (first > x) we would get? For 2, upper_bound would find first >2 => end, then push => d=[2,2]? That would be length 2, which is wrong for strictly increasing. So lower_bound is correct for strictly increasing. So algorithm is fine.
Now, we need rollback: When we go deeper, we apply the update to d. We need to be able to revert that update when we backtrack. Since the update either changes an existing element (at position pos) or appends a new element. In case of change, we can store the previous value at that position before overwriting, and also the previous size. In case of append, we store that we appended (so rollback will pop). Additionally, we may need to store the pos index. So we can maintain a stack (or use recursion return) to revert. Since DFS depth is limited, we can do it manually by having a function that returns a "state" change record. For simplicity, we can implement the DFS as recursive function that after processing children, we revert d to previous state based on info we saved before modification.
Pseudo:
vector d; // global for current DFS
function dfs(u, parent):
// process insertion of r[u]
int pos = lower_bound(d.begin(), d.end(), r[u]) - d.begin();
bool appended = false;
int old_value;
if (pos == d.size()):
d.push_back(r[u]);
appended = true;
else:
old_value = d[pos];
d[pos] = r[u];
// current LIS length = d.size()
ans = max(ans, (int)d.size());
code
for v in adj[u]:
if v != parent:
dfs(v, u)
// rollback
if (appended):
d.pop_back();
else:
d[pos] = old_value;
Now, we need to run this dfs from each node as root. That means we will call dfs(root, -1) for each root. Each DFS will modify the global d (which we need to reset empty before each DFS). That's fine.
Complexity: For each root, we visit all nodes, each insertion does a binary search in d. d's size is at most the LIS length, but can be up to O(n). Binary search O(log n). So O(n log n) per root, O(n^2 log n) total.
Now, is 6000^2 = 36e6 manageable? 36 million binary searches of ~12 steps each => 432 million operations. Each operation includes vector accesses and comparisons. In C++, this could run within 2-3 seconds if optimized well? Possibly borderline but I think it's okay. There is also recursion overhead: 6000 DFS calls, each doing recursion depth up to 6000. That's 36 million recursive calls? Actually, each DFS from a root visits n nodes, so total recursive calls across all roots = n * n = 36e6. Recursion overhead per call might be significant (function call, loop over adjacency). But we can implement DFS iteratively? Recursion depth may cause stack overflow if we use recursion depth 6000, which is okay in C++ if we increase stack limit or use iterative? 6000 depth is fine for recursion typically (default stack size might be 8MB, 6000 frames maybe okay). But calling 36 million recursive calls overall could be heavy. We could try to reduce overhead by using iterative DFS with explicit stack? But still we need to maintain LIS state. Maybe we can use an iterative approach, but recursion may be simpler.
But note: In each DFS from a root, we visit all nodes, but the recursion overhead for each node visit is constant. 36 million function calls might be okay if optimized (e.g., using inline or not too much). But each call also loops over adjacency list of that node. Total adjacency traversals across all DFS = n * (sum of degrees) = n * (2*(n-1)) = 2n(n-1) ≈ 2n^2 = 72 million. So total work about 100 million operations plus binary searches. Might be okay.
We can also try to optimize by using a more efficient approach: perhaps we can compute answer in O(n^2) without log factor using some DP merging? But maybe not necessary.
But wait, we need to consider that the band can also have concerts only in some cities along the path, but we are computing LIS of the entire path sequence. That's correct.
Now, we should test with sample.
Sample1:
6
1 2 3 4 5 1
Edges: 1-2,2-3,3-4,3-5,3-6
We can compute manually: The maximum LIS on a path? Possibly path 1-2-3-4: values 1,2,3,4 => LIS=4. Path 1-2-3-5: 1,2,3,5 => 4. Path 1-2-3-6: values 1,2,3,1 => LIS? Sequence 1,2,3,1: LIS is 3 (1,2,3). Path 4-3-5: 4,3,5 => LIS maybe 2? So answer 4, matches.
Sample2:
5
1 2 3 4 5
Edges: 1-2,1-3,2-4,3-5
Path 4-2-1-3-5: values 4,2,1,3,5 -> LIS? Let's compute: 4,2,1,3,5: LIS length? Could be 2,3,5? Actually, 1,3,5 length 3. Or 2,3,5 length 3. So 3. Maybe other path yields 3. Answer 3.
Our algorithm would find 3.
Now, we must verify correctness: Does the band have to have concerts in order along the path? Yes. Could they start at any city and travel along the path? Yes. So LIS along directed path is the maximum number of concerts for that directed traversal. Since they can choose direction, we take max over both directions. So our algorithm that computes LIS for each ordered pair (u,v) covers both directions. So answer is max over all DFS roots of the d.size() at each node. Actually we need to consider all ordered pairs (u,v). That is exactly what we will do.
Edge Cases: What about paths of length 0 (single node)? The band can have a concert in a single city? They travel along some path and have concerts in some cities. Could they just stay at one city and have a concert? That would be a path of length 0 (just one city). The sequence would consist of that single city, so LIS length =1. So answer at least 1. Our algorithm will consider when u=v? During DFS from u, we start at u (root) before exploring children. At the moment we process u (insert its value), the current path is just u, LIS length =1. So that's considered.
Now, we must ensure that for each ordered pair we compute LIS correctly. Our DFS from root u will compute LIS for path from u to each node v. But note: When we start at u, we first insert u into d, then we go to children. So at the point we are at v, d contains the LIS for the entire sequence from u to v, which includes all nodes along that path, including u and v. That's correct.
Now, we need to think about duplicate values: Our LIS algorithm with lower_bound handles equal values correctly. Good.
Potential pitfalls: The tree is undirected. In DFS from a root, we treat the root as start, and we traverse edges. However, the path from root to a node goes along the unique simple path. That's fine.
Now, complexity: O(n^2 log n). n=6000, O(36e6 * log) ~ 36e6 * 12 = 432e6. This might be borderline but perhaps acceptable in C++ with optimization (like using arrays and manual binary search, using vector and lower_bound). But we can also attempt to improve by using a more efficient method: Since we are doing many binary searches on a vector d that is size at most the current LIS length, and we are doing many updates and rollbacks, we can use a simple array and a variable len. For insertion: find pos with binary search (using std::lower_bound on d, d.begin(), d.begin()+len). Update: if pos==len then d[len++]=x; else old = d[pos]; d[pos]=x; and record old and pos for rollback. Rollback: if appended, len--; else d[pos]=old. That's essentially same.
Now, can we reduce log factor? Maybe we can compute LIS length using a fenwick tree along the path? But insertion is online. The log factor is probably fine.
But what about memory? We just need adjacency list, values array. That's fine.
Now, before coding, we should consider if there is any flaw: Are we double-counting or missing paths where the band travels not from one endpoint to the other but perhaps they start somewhere in the middle and go to an endpoint? But the band's path is a simple path; they can start at any city and end at any city, as long as it's a simple path. So indeed any simple path can be represented by its two endpoints. The order of traversal can be either direction. So by considering all ordered pairs (u,v), we cover all paths and all directions. So max over all (u,v) of LIS(u->v) gives answer.
But wait: Is it possible that the optimal concert subsequence uses nodes that are not all on the path between the endpoints? No, because the path is defined as the route they travel, which is a simple path. They will visit all nodes on that path (maybe not all, but they will pass through them). The concerts are a subsequence of the visited nodes. So all concert nodes are on that path, and the order is along the path. So yes.
Thus algorithm is correct.
Now, we need to implement. We'll write:
int n;
vector r(n+1);
vector<vector> adj(n+1);
int ans = 0;
void dfs(int u, int p, vector& d) {
// Insert r[u]
auto it = lower_bound(d.begin(), d.end(), r[u]);
int pos = it - d.begin();
bool appended = (pos == d.size());
int old_val;
if (appended) {
d.push_back(r[u]);
} else {
old_val = d[pos];
d[pos] = r[u];
}
// Update answer
ans = max(ans, (int)d.size());
code
for (int v : adj[u]) {
if (v != p) {
dfs(v, u, d);
}
}
// Rollback
if (appended) {
d.pop_back();
} else {
d[pos] = old_val;
}
}
int main() {
read input
for (int root = 1; root <= n; ++root) {
vector d; // empty
dfs(root, -1, d);
}
print ans
}
But note: In the recursion, we pass d by reference, but we need to record old_val and appended flag across recursive calls. Since after returning, we rollback. That works as we have stack discipline.
Now, about time: For each root, we call dfs recursively. The recursion will go through whole tree. That's fine.
But we can potentially prune: we don't need to run DFS from every root if we already have some symmetries? However, not obvious.
But maybe we can improve by noting that for any unordered pair, the LIS in one direction might be the reverse of the LIS in the other direction of the reversed sequence, but we can't derive one from the other easily. So we need both directions.
Now, is there a possibility of double counting? No, we just take max.
Now, test on worst-case: a line of 6000 nodes. Then for each root, DFS will traverse whole line. Complexity: For a line, the recursion depth is up to 6000, okay. The total number of node visits is n^2 = 36e6. For each visit, we binary search in d. In a line, the LIS length for path from root to node might vary. The d vector may be of size up to path length. The binary search takes O(log L). So total ~ n^2 log n. With n=6000, it's about 36e6 * ~12 = 432e6. This might be high but maybe still within time if optimized and using fast I/O. But 432 million operations might be ~0.5-1 second per 100 million? It could be around 3-5 seconds. Possibly acceptable for typical contest limits (2 seconds maybe not). We can try to reduce constant.
Idea: Since n is only 6000, we could perhaps compute answer by considering each node as the "center" and using DP to combine paths in O(n^2) total without log factor. Let's think if we can compute LIS for all paths more efficiently.
Alternative approach: For each node as root, we can compute LIS for all downward paths using DP that stores the best increasing subsequence ending at the current node? Actually, if we fix the direction (away from root), the LIS of the path from root to a node is just the length of the longest increasing subsequence that ends at some node along that path? Wait, the LIS of the whole sequence is not necessarily ending at the last node. So we need full LIS, not just ending at the node. However, we can compute LIS length for the path by maintaining the patience piles as we go. That's what we do. So that seems efficient.
Could we reuse computation across different roots? Possibly using rerooting technique: The LIS from a parent to its subtree when root changes? But LIS is not easily recomputed because the sequence order changes.
Given constraints, O(n^2 log n) might be acceptable. Let's approximate more precisely: For each node as root, we will call dfs on all nodes, but each edge traversed twice. So total function calls = n (roots) * n (nodes) = 36e6. In each call, we do:
binary search on vector d of size up to current LIS length. In worst case, for root at one end of a line with increasing values, d size can be up to the depth. So binary search O(log depth). In many roots, average LIS length might be smaller.
updating answer.
loop over adjacency: for each node, we iterate over its neighbors. In total across all roots, we will iterate over each edge twice per root (once from each endpoint? Actually, in each DFS from a root, each edge is traversed twice (down and up). So total edge traversals = n * (2*(n-1)) = about 2n^2. That's 72 million iterations.
So total operations: 36e6 binary searches + 72e6 neighbor checks + overhead. That's about 108e6 plus binary searches. Binary search itself involves about log steps of integer comparisons. So maybe total operations ~ 500 million. In C++, 500 million simple operations can be around 2-3 seconds on modern CPU? Possibly borderline but might pass with optimizations like using arrays and inline functions. Also, we can reduce neighbor checks by using adjacency list and for each root, we still need to iterate over all edges. That's necessary.
We can try to micro-opt:
Use global arrays for adjacency (vector g[MAXN]) and use for loops with index.
Use iterative DFS instead of recursion to avoid function call overhead? But recursion may be okay.
Use manual binary search on d array (since d is increasing) to reduce overhead of lower_bound which might be generic. But lower_bound on vector is optimized.
Use small fixed-size arrays? d size <= n. We can maintain d as an array (int d[MAXN]) and variable len. For binary search, we can implement our own:
int pos = std::lower_bound(d, d+len, r[u]) - d;
That's fine.
Precompute r values in array.
Also, we could prune roots: Since the answer is symmetric, running from all roots might be redundant? But we need both directions. However, note that for any unordered pair (u,v), LIS(u->v) and LIS(v->u) are not necessarily equal, but the maximum over all ordered pairs is the answer. Could we compute max over unordered paths by only considering each path once but computing LIS in both directions? That would be half the roots? Not exactly: Running DFS from each node gives us LIS for all directed paths. But maybe we could compute LIS for all undirected paths by considering each node as LCA? Possibly we could compute for each unordered pair by doing a single LIS calculation that is direction-aware. But that seems not simpler.
But maybe we can compute answer by considering each node as the "minimum" in the increasing subsequence and then expanding? Not sure.
Given the problem is from Codeforces? Possibly intended solution is O(n^2) or O(n^2 log n) with n=6000. Actually, I recall a problem "Road Accident" maybe from Codeforces Round? Let's search memory: I think there is Codeforces problem 1149C? Not sure. But I've seen a problem about longest increasing subsequence on a tree path, and typical solution is O(n^2) DP with LIS merging using binary search, maybe O(n^2 log n) is acceptable. Let's see constraints: n ≤ 6000, that's quite small, so O(n^2) is 36 million, O(n^2 log n) is ~400 million. Usually Codeforces time limit 2 seconds, and O(n^2) with n=6000 passes easily, but O(n^2 log n) might be borderline but often passes with optimization. But many solutions use O(n^2) algorithm. Let's try to find O(n^2) solution.
Idea: For each node as root, we can compute for each other node the LIS length for the path from root to that node using DP that stores for each value threshold the best length? Possibly we can compute LIS in O(L) per path if we use patience sorting but we want O(n) total per root? Wait, patience sorting already processes each node once, so for a fixed root, we get LIS for all nodes in O(n log n). So O(n^2 log n) is the total. To get O(n^2), we would need to get rid of the log factor, i.e., compute LIS without binary search, maybe using an array indexed by values? Since r_i up to 1e6, we could compress values to 1..n (since n ≤ 6000). Then we could use a BIT to compute LIS in O(log n) anyway. But we could perhaps maintain an array dp[v] = longest increasing subsequence ending at value v? But we need the LIS of the prefix, not just ending at each value. The patience sorting approach with binary search is essentially optimal for online LIS. Could we use a Fenwick tree to compute LIS in O(log n) per insertion, which is same. So log factor remains.
But maybe we can precompute for each node the LIS of paths from it using BFS-like expansion and maintain d as an array of size n, and binary search is cheap. The log factor might not be the bottleneck.
Alternatively, we could use a two-pointer technique? No.
Given that n=6000, we could even compute LIS for each path by doing O(L^2) DP? That would be O(n^3) which is too high.
Thus, O(n^2 log n) seems plausible.
But we can perhaps improve by noting that we don't need to run DFS from every node; we could compute LIS for all directed paths by doing a BFS from each node, but that's same.
Maybe we can use the fact that the tree has only n-1 edges, and we could use "small to large" merging of paths? Could we compute for each edge the best LIS that goes through that edge? Possibly using DP on tree. Let's think deeper.
We could treat the problem as: find maximum k such that there exists a simple path and an increasing subsequence of length k on it. This is similar to "longest increasing subsequence in a tree" which can be solved by DP on tree where we compute for each node, the longest increasing path starting or ending at that node, but with ability to skip nodes. However, skipping nodes means we can have gaps. This is like the longest chain where each next node has higher value and is reachable along the path without using intermediate nodes that are selected. But if we think of the selected nodes themselves, they must lie on a simple path and be in increasing order of values. That implies that if we look at the selected nodes only, they form a sequence where each consecutive pair is connected by a path that does not contain any other selected node, but may contain other nodes. But the condition that they all lie on one simple path implies that the selected nodes, when sorted by their order along that path, are increasing. So the selected nodes themselves must be totally ordered along the path. Essentially, the selected nodes form an increasing sequence that is also "convex" in the tree? Actually, any set of nodes lies on a simple path if and only if there is no branching: i.e., the nodes' pairwise paths all overlap in a linear fashion. This is equivalent to the condition that the set has at most two leaves (in the minimal subtree). But maybe we can think in terms of building the increasing subsequence step by step: we can start at some node, then go to a node with larger value that is not in the current path but such that adding it keeps the set on a simple path. That's like extending a path while maintaining increasing values. This is reminiscent of longest increasing path in a tree where you can only move to adjacent nodes, but you can skip nodes? Actually, if we require the selected nodes to be in order along a path, we can think of them as a sequence where each next node is somewhere on the extension of the current path. That is, if we have a current simple path P (the one that will contain all selected nodes), and we have selected some nodes along it in increasing order. To add a new node with larger value, we need to extend the path (or maybe it's already on the path but we skipped it before) to include the new node while keeping the path simple. Since we can always choose the path after selecting nodes, we could think of constructing the selected nodes one by one, ensuring they lie on some simple path. That's like we are looking for the longest sequence of distinct nodes with strictly increasing values such that they are all collinear (lie on a simple path). This is similar to "longest increasing subsequence in a tree" where the subsequence must be a path (not necessarily consecutive) but in order along some path. This might be solved by considering each pair of nodes as endpoints and then LIS on the path. So again back.
Given n=6000, maybe the intended solution is exactly O(n^2 log n). Let's check memory of other solutions online? I might recall a problem "Road Accident" from Codeforces Round #166 (Div. 2) maybe? I'm not sure. But I can think about optimizing further.
One potential improvement: Instead of running DFS from every node, we can run a single DFS that computes LIS for all paths that start at various nodes? Not straightforward.
Another idea: Use centroid decomposition to reduce complexity to O(n log^2 n) maybe? For each centroid, we consider paths passing through it, and we need to compute maximum LIS over concatenated sequences from two sides. That would involve merging sorted data structures. Could be doable but more complex.
Given time constraints for implementation, the O(n^2 log n) approach is simple and likely to pass.
But we must ensure that recursion depth doesn't cause stack overflow. 6000 depth is okay. However, if we call dfs from root 1, depth could be up to n (in a line). That's 6000 recursive calls, which is fine. But we then call dfs from root 2, etc. The recursion depth will vary. The maximum depth is the longest distance from root to some node during that DFS. So overall, the recursion depth for each DFS may be up to n. So we need to ensure that the default stack size can handle 6000 frames. Typically, each frame maybe ~ a few dozen bytes for local variables? Actually, in C++ recursion, each call uses some stack memory. 6000 frames might be around a few hundred KB, which is okay. So safe.
But we will call dfs recursively many times overall (36e6 calls). That's a lot of function call overhead. Possibly we could convert to iterative using a stack that holds state (node, parent, iterator index). That might reduce overhead but complicates rollback of LIS state. Could we use recursion but inline? The compiler may optimize tail recursion? Not tail. Still, 36e6 function calls is not negligible. However, each DFS from a root visits n nodes, so total calls = n * n = 36e6. This is similar to a double nested loop. 36e6 function calls may be around 0.3 seconds? Actually, function call overhead is maybe 10-20 ns? In C++ with optimization, it could be more. Let's approximate: 36e6 function calls, each with a few operations, could be around 0.5-1 second. But we also have loops and binary search. So total maybe 2-3 seconds. Might be okay.
But we can also try to reduce the number of roots by half by using symmetry: For any unordered pair (u,v), max(LIS(u->v), LIS(v->u)) is the value for that path. If we compute LIS for all directed pairs, we get answer. Could we compute LIS for all directed pairs by doing DFS from each node and only consider v > u? Not helpful because we still need to run from each root.
Maybe we can compute LIS for both directions in one DFS? For a fixed root, we get LIS from root to all nodes. That's one direction. To get the reverse direction (from node to root), we could also compute LIS on the reverse sequence during the same DFS? The reverse sequence from node to root is not simply the reverse of the current sequence because the current sequence is root->...->node. The reverse would be node->...->root, which is a different order. We could compute LIS for that direction by a second DFS that goes from root but processes children in opposite order? Not exactly.
But maybe we don't need to consider both directions because the maximum LIS over all directed paths will be achieved by some path where the start is the node with minimum value in the subsequence? Not necessarily. Consider a path where values go up then down. The LIS in one direction might be longer than the other. So we need both.
But maybe we can compute for each unordered pair (u,v) the LIS in both directions by only doing DFS from each node, but we could stop early if we already have an answer close to n? Not needed.
Given the simplicity, I'll implement the O(n^2 log n) method.
But before finalizing, let's test with a line of 6000 nodes with increasing values: 1,2,...,6000. Then for any path from i to j (i<j), the LIS length is the number of distinct increasing values along the path? Actually, if values are strictly increasing along the line (monotonic increasing), then the entire path is increasing, so LIS length = length of path (j-i+1). So maximum is n=6000. Our algorithm: For each root i, when we DFS, we will travel along the line. The LIS d will be built. For root at one end (say node 1), DFS will traverse nodes in order 1,2,3,... so each insertion will append (since values increasing), so d will be [1,2,3,...]. So at node v, d size = v (if nodes numbered by order). So we will capture max = n. So answer correct.
Now, compute complexity for this worst-case (line with increasing values). For root = 1, we will have each insertion append, so binary search will always find pos = len, so we do d.push_back. That's O(log len) for binary search. So total for this DFS: sum_{len=1 to n} log len ≈ n log n - n? Actually sum log i ≈ n log n. So O(n log n). For root = 2, we need to DFS from node 2. The tree is a line; from root 2, the adjacency includes 1 and 3. The DFS will go one direction first (say 1), then backtrack, then go 3, etc. The order of traversal will affect the sequence we process. But the LIS computation is based on the path from root to each node. For root=2, the path to node 1 is [2,1] (if we go to 1 first). At node 1, the sequence is 2 then 1? Actually, we start at root 2, insert 2. Then we go to child 1 (assuming parent none). At node 1, we insert 1. The sequence is 2,1 (values decreasing). LIS length =1? Actually, sequence [2,1] LIS length 1. So d will be [2] then when insert 1, lower_bound(d,1) will find pos=0 (since 2>=1), replace d[0]=1, so d becomes [1]. So size remains 1. That's correct. Then we backtrack to 2, rollback insertion of 1, d back to [2]. Then go to 3, insert 3 -> lower_bound(d,3) finds pos=len (since 3 >2), append, d=[2,3] size 2. Then to 4, etc. So for root=2, we will compute LIS for paths: to 1:1, to 3:2, to 4:3? Actually, path 2->4: sequence 2,3,4? Values 2,3,4 increasing, LIS=3. So we get many lengths. So each DFS still processes all nodes, each insertion does binary search. So total across all roots is O(n^2 log n). For n=6000, that's ~ 60006000~12 = 432e6 binary search steps. Each binary search step involves about 12 comparisons. So ~5 billion operations? Actually, 432e6 * 12? Wait, we counted binary search steps as each binary search does about log2(L) comparisons. But the binary search is not per step of something else; it's a single binary search per insertion. So we have 36e6 insertions, each with a binary search of average log2(L) maybe around 8? Let's compute average L: not sure. But worst-case each binary search may be up to log2(6000) ~ 12.5 comparisons. So total comparisons ~ 36e6 * 12 = 432 million comparisons. That's not 5 billion; it's 432 million. That's acceptable. In addition, we have neighbor loops (72 million). So total simple operations maybe 500 million. That might run within 2 seconds if optimized? Possibly 2-3 seconds. Let's check typical speed: C++ can do about 100-200 million integer operations per second on a modern CPU with optimization. So 500 million could be 2.5-5 seconds. Might be borderline but perhaps still passes if well-coded and time limit is 3 sec.
We can try to micro-opt: Use iterative DFS to avoid function call overhead for each node visit. But recursion might also be fast. However, each recursion call includes pushing parameters, return address, etc. But 36 million calls is a lot. Maybe we can implement DFS iteratively with a manual stack and simulate the rollback. That could reduce overhead.
Alternatively, we can try to compute LIS for all directed paths using BFS-like expansion from each node, but that also would have similar cost.
Maybe we can reduce the number of roots by noticing that the answer is at most the length of the longest increasing subsequence in any root-to-leaf path? No, because the best path might not start at a leaf.
Consider using "rerooting" to compute LIS for all directed paths from all nodes in O(n^2) total? Could we compute LIS for paths starting at each node by doing a DP that passes a data structure from parent to child? The challenge is that the LIS structure for a path from node u to all nodes in its subtree can be computed, but to compute for paths from u to nodes outside its subtree, we need to combine from the other side. This resembles tree DP with rerooting. Maybe we can compute for each node u, the LIS for the path from u to any other node v by using a DP that passes the "d" structure when moving the root. Essentially, we can root the tree at an arbitrary node, compute LIS for all paths from that root (like we did). Then we can "reroot" to neighbors, updating the LIS data for the whole tree. If we can update the LIS structure for all nodes when moving the root across an edge in O(n) or O(n log n), then we could compute LIS for all roots in O(n^2). That would be better.
Let's explore rerooting: Suppose we have computed for root r, for each node v, the LIS length for the path from r to v (directed). Now we want to compute for a new root s, which is a neighbor of r. The paths from s to all other nodes: For nodes in the subtree of s (when rooted at r, with parent r), the path from s to those nodes is the same as the path from r to those nodes but with the prefix r removed and s added? Actually, consider tree rooted at r. s is a child of r. For any node v in the subtree of s, the path from s to v is the suffix of the path from r to v after removing r. That is, the sequence from s to v is exactly the path r->s->...->v without r. So the LIS for s->v can be derived from the LIS for r->v? Not directly because the LIS might have used r. However, we could compute LIS for s->v by starting from scratch.
But we could try to maintain for each node a data structure representing the LIS of the path from current root to that node. When we move the root from r to s, we need to update these structures. This seems complex.
Given the problem constraints, O(n^2 log n) might be acceptable. Let's test approximate runtime with a simple C++ program that does 36e6 binary searches on a vector. I could quickly reason: On my machine, 100 million integer operations ~0.2-0.3 seconds? Actually, it depends. A simple for loop doing 100 million increments might take ~0.05 seconds? Let's recall: Usually, 10^8 operations in C++ can be around 0.2-0.5 seconds if they are simple (like addition). But binary search involves branching and memory access, which may be slower. However, 400 million operations might be 1-2 seconds. With recursion overhead, maybe 3 seconds. Codeforces time limit often 2 seconds for such problems, but sometimes 3 seconds. I'm not sure.
We could also try to reduce the log factor by using an array of size up to max value (after compression) and maintain a BIT that can give the maximum LIS ending at a value, but we need the LIS of the entire prefix, not just ending at some value. Actually, we could maintain an array best where best[x] = length of longest increasing subsequence ending with value x seen so far. Then the LIS length for the prefix is max(best[1..x]) when inserting x? That's not correct because LIS can end with value larger than x? Actually, standard LIS DP: dp[i] = 1 + max_{j < i, a[j] < a[i]} dp[j]. If we process in order, we can use a Fenwick tree over compressed values to compute dp[i] in O(log n). That gives the LIS ending at each position, but the overall LIS is max over dp. However, we need the overall LIS of the entire sequence, not just ending at last element. But we can keep a global max. So we could maintain a BIT that supports: for value x, query max dp for values < x, then set dp[x] = that+1, update BIT at x. This yields the LIS ending at each element. The overall LIS length is the maximum dp seen so far. This is also O(log n) per insertion, and rollback would be more complicated because we need to revert BIT updates. BIT rollback can be done by storing previous values? But we also need to revert the global max. However, we can also implement rollback for BIT if we store modifications. Since the number of modifications is equal to number of insertions, we could store stack of changes (position, old value) and revert. BIT size is n (compressed values). This might be more complex but the binary search approach already uses a small vector d. The BIT approach also uses O(log n) per insertion, similar. But the constant might be higher.
Given the simplicity, we'll stick with vector d.
But we can still compress values to 1..n to make comparisons cheaper? Not necessary.
Potential optimization: Since we run DFS from each root, and the tree is static, we can precompute parent and order? Not needed.
One more optimization: Use adjacency list as vector and in DFS, we can iterate over neighbors, but we can avoid checking if (v != parent) by storing parent in recursion argument. That's fine.
We can also store the rollback info in local variables after returning from recursion, no need for explicit stack.
Now, we must consider that when we start DFS from a root, we need to reset d to empty. So we call dfs(root, -1, d). Inside dfs, we need to pass d by reference. That's fine.
Implementation details:
Use global arrays for r, adj.
Use global variable ans.
In main, loop over roots 1..n.
For each root, initialize an empty vector d; call dfs(root, -1, d);
Print ans.
But we must be careful: ans is global; we update inside dfs.
Now, test with sample.
Edge Cases: n=2, values [1,2], edge 1-2. Root 1: start d: insert 1 -> d=[1], ans=1. Go to child 2: insert 2 -> d=[1,2], ans=2. Root 2: insert 2 -> d=[2], ans stays 2 (max). Go to child 1: insert 1 -> lower_bound(d,1) finds pos0 (2>=1) replace -> d=[1], ans remains 2. So answer 2, correct.
Now, we need to ensure we don't get TLE. Let's think about possible further optimization: For each root, we can run DFS and compute LIS for all nodes. The binary search on vector d uses lower_bound, which for small vectors is fast. However, we can also note that d is always sorted increasingly. We could maintain a fenwick tree over compressed values to get LIS length in O(log n) but that would also need rollback. Not simpler.
Maybe we can reduce the number of roots by half using symmetry of undirected paths? Actually, for each undirected path, the LIS in one direction is the LIS of the reversed sequence. The LIS of reversed sequence is the same as the LDS (longest decreasing subsequence) of the original sequence. So if we compute for each directed path the LIS, we get both. But maybe we can compute for each node the LIS for all paths starting at that node, and that's it. That's what we do. So no reduction.
We could also compute answer by considering each node as the minimum of the increasing subsequence and then doing BFS to extend? Could be O(n^2) with DP, but let's think more.
Consider we fix the smallest value node in the subsequence. Then we want to build an increasing sequence where each next node has larger value and lies on a simple path extending from the current set. This is akin to finding the longest chain in a DAG? The tree with increasing values could be seen as a DAG where we have an edge from u to v if r_u < r_v and v is on some path extending from u? Not exactly.
Alternate DP: For each node u, we could compute the longest increasing subsequence that starts at u and travels along some simple path (i.e., we can choose the path as we go). Since we can choose any path, maybe we can treat it as we can move to any neighbor with larger value, and then continue from there, but we must ensure that the overall set of visited nodes lies on a simple path. If we start at u and then move to v (neighbor with larger value), we are on a simple path (the edge). Then from v, we could move to another neighbor w with larger value, but we must ensure that w is not backtracking through u? Actually, the path must be simple, so we cannot revisit nodes. So from v, we can go to any neighbor except u, as long as the values increase. This resembles a longest increasing path in a directed graph where edges exist between adjacent nodes if values increase. But we can also skip nodes: In the selected subsequence, we don't have to perform concerts at every node; we can skip intermediate nodes. So if we are at u and we want to next have a concert at w, which is not adjacent, we can travel through intermediate nodes without having concerts there, as long as the overall path remains simple. This means we can jump over nodes as long as they are on the same simple path. So from u, we can go to any node v in the tree such that there is a simple path from u to v that does not include any other selected node, and r_v > r_u. And then from v we can similarly go to another node w such that the combined set {u, v, w} lies on a simple path (i.e., they are collinear). That implies that the nodes must all lie on a single simple path, so the sequence must be along that path. So essentially, the selected nodes must be in order along some simple path. So we can think of constructing an increasing sequence by starting at some node, then extending the path in one direction (or both directions) by adding nodes with larger values either at one end or somewhere in the middle? Actually, if we have a current path P (which is the simple path that will contain all selected nodes), and we have selected some nodes in increasing order along P. To add a new node with larger value, we need to ensure that it lies on an extension of P (i.e., we can extend P at one end) or maybe it lies between existing selected nodes? But if it lies between, its value would need to be between the values of the neighboring selected nodes to maintain increasing order; but the sequence must be strictly increasing overall, so if we insert a node between two selected nodes, we must have its value between them. That is possible. So the selected nodes can be anywhere along the path, not necessarily at ends. So the problem is more complex.
Given the time, I'll implement the O(n^2 log n) solution.
But wait: n=6000, recursion 36e6 calls. That's a lot of recursion depth? No, each call is a function invocation. 36e6 recursion calls might cause stack overflow due to recursion depth? No, recursion depth is the maximum number of nested calls at one time, which is at most n (6000). The total number of calls is 36e6, but they are sequential, not all at once. The runtime stack handles each call and return. So the number of calls is fine, but function call overhead for each node visit is there.
We could use an iterative stack to avoid function overhead. Let's consider implementing DFS iteratively.
Iterative DFS with manual stack: We need to simulate the recursion to perform actions on entry and exit. We can use a stack of tuples (node, parent, state), where state indicates whether we are entering or exiting. On entering, we process insertion, record rollback info, push exit state, then push children for entry. On exit, we rollback.
We'll also need to maintain rollback information for each node: the pos, appended flag, old_value. That can be stored in the stack as well.
Pseudo:
for root in 1..n:
vector d;
stack<tuple<int,int,int,bool,int>> st; // node, parent, state (0=enter,1=exit), pos? Actually we can store rollback info separately.
Simplify: Use recursion.
Given the simplicity of recursion, I'll use recursion. We'll have to ensure compiler optimization flags like -O2. Recursion may be fine.
But we must be careful about recursion depth for root that is not necessarily leaf. The maximum depth is the diameter, which could be up to n. 6000 depth is safe.
Now, let's code.
Potential micro-optimizations:
Use adjacency list as vector<vector>.
Use global arrays for r (int r[6005]).
Use inline or not necessary.
Use lower_bound with d.data() and len to avoid .begin() .end()? Actually lower_bound(d.begin(), d.end(), val) is okay.
But we can implement our own binary search to reduce overhead of iterators? Not sure.
Let's attempt to code and test runtime mentally.
However, there is another nuance: When we do DFS from a root, we need to ensure we don't revisit nodes (through parent). That's done.
Now, answer may be up to n, we need to output integer.
Now, implement:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 6005;
int n;
int r[MAXN];
vector adj[MAXN];
int ans = 0;
void dfs(int u, int p, vector& d) {
// insert r[u]
auto it = lower_bound(d.begin(), d.end(), r[u]);
int pos = it - d.begin();
bool appended = (pos == (int)d.size());
int old_val;
if (appended) {
d.push_back(r[u]);
} else {
old_val = d[pos];
d[pos] = r[u];
}
if ((int)d.size() > ans) ans = d.size();
code
for (int v : adj[u]) {
if (v != p) {
dfs(v, u, d);
}
}
// rollback
if (appended) {
d.pop_back();
} else {
d[pos] = old_val;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 1; i <= n; ++i) cin >> r[i];
for (int i = 0; i < n-1; ++i) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
ans = 0;
for (int root = 1; root <= n; ++root) {
vector d;
dfs(root, -1, d);
}
cout << ans << "\n";
return 0;
}
This should work.
But we can micro-opt: Pass d by reference, but we also need to ensure that d is not copied. It's fine.
Potential improvement: Since we are doing many lower_bound on a vector that is small, using lower_bound is okay.
Now, test on small examples.
But I'm still concerned about performance. Let's do more precise estimation: For n=6000, total insertions = n * n = 36e6. Each insertion:
lower_bound: It performs about log2(len) comparisons, each comparison is integer compare. len up to 6000, average maybe ~ something. The number of comparisons total = sum_{insertions} log2(len_i). In worst-case (line with increasing values from root that is smallest), len_i roughly equals distance from root+1. For root=1, we have len=1,2,...,n => sum log i ≈ n log n - n/ln2? Actually approximate integral: ∫ log x dx = x log x - x/ln2. So for n=6000, sum_{i=1}^{6000} log2 i ≈ 6000log2(6000) - 6000/ln2 ≈ 600012.55 - 6000/0.693 = 75300 - 8658 ≈ 66642 comparisons. That's for one root. For root=2, the pattern is different, but the total comparisons over all insertions across all roots might be roughly n * (average sum of log len per root). Could be up to n * (n log n)? Actually, each root contributes about n insertions, each with log(len) average maybe O(log n). So total comparisons ~ n^2 log n. That's 36e6 * 12.55 = 452 million comparisons. Each comparison is cheap. Plus loop overhead. So maybe fine.
But we also have recursion overhead: function call per insertion. That's 36e6 calls. Each call does some work beyond the insertion (loop over neighbors, condition). The loop over neighbors will be executed for each node as we enter it. For node u, after insertion, we iterate over its adjacency list. The total number of times we iterate over edges across all roots is 2*(n-1)*n = ~2n^2. So additional 72e6 iterations. So total function calls + neighbor loops + binary search ~ 36e6 + 72e6 + 452e6? Actually binary search comparisons are inside the insertion, which is part of the function call. So total operations maybe ~500 million. That's a lot but still plausible.
Maybe we can cut down by not running DFS from every root if the tree is symmetric? Not.
Another idea: Use the fact that we only need the maximum LIS length, and we can stop early if we already found answer = n (max possible). Because if we ever get LIS length = n, we can break out. That could help in some cases but worst-case (increasing values line) we will find ans = n when root = 1, so after first root we would have ans = n, and then we could break. But we cannot guarantee that the maximum is n; but we can still break if ans == n. In many testcases, maximum might be less than n, so we still need to check all roots? But we could potentially stop if we have ans == n. That's a small optimization.
Also, we could break early in some roots if we already have ans = n, then skip rest. So after each root we can check if ans == n, if yes break loop. In worst-case where ans < n, we still run all roots.
But maybe we can also reduce roots by noting that the maximum over all directed paths is symmetric, so we could compute only for half of the nodes? Not.
Maybe we can use "start from each leaf only"? Not reliable.
Let's think about an O(n^2) solution without log factor.
Alternate approach: For each node as root, we can compute LIS lengths for all nodes in O(n) using a DP that maintains for each possible length the minimum tail, but that's exactly the vector d we maintain. The binary search is the log factor. Can we replace binary search with something like a van Emde Boas? No.
But we can compress values and use an array first[i] the smallest tail for length i, and then to find position we can do a linear scan because d size is at most current LIS length. In worst-case, d size can be up to n, so linear scan per insertion would be O(n) leading to O(n^3). Not good.
But maybe average d size is small? Not guarantee.
What if we use a bitset? Not.
Given constraints, O(n^2 log n) seems intended.
But let's check Codeforces problem 264C? I'm trying to recall if there is a problem with n <= 6000 and O(n^2) solution. Many problems with n=6000 accept O(n^2). For example, "Petr and Permutations" etc. O(n^2) with n=6000 is typical. O(n^2 log n) might also pass because constant factor small.
I'll proceed with the described solution. However, we need to verify that the LIS algorithm with lower_bound is correct for strictly increasing, and we use lower_bound for vector; it's fine.
One more nuance: When we backtrack, we need to restore d exactly. In the case where we replaced an element, we restore old value. In the case where we appended, we pop. That's correct.
Now, consider the possibility of multiple replacements at the same position due to later insertions? Since we rollback in exact reverse order, it's fine.
Now, test the algorithm on a small tree with random values to ensure it's correct. We'll do mental test.
Example: n=3, values [3,1,2], edges: 1-2, 2-3.
All paths:
1-2: seq 3,1 LIS=1 (or 1 if reversed: 1,3 LIS=2? Actually path 2-1: seq 1,3 LIS=2). So max=2.
1-3: path 1-2-3: values 3,1,2. Direction 1->3: [3,1,2] LIS? LIS length 2 (1,2). Direction 3->1: [2,1,3] LIS? 2,3? Actually [2,1,3] LIS=2 (2,3) or (1,3). So max=2.
2-3: [1,2] LIS=2.
So answer=2.
Our algorithm: root=1: dfs from 1. Insert 3: d=[3], ans=1. Go to 2 (neighbor): insert 1: lower_bound([3],1) pos0, replace d[0]=1, d=[1], ans=1. Then from 2 go to 3: insert 2: lower_bound([1],2) pos=len=1, append -> d=[1,2], ans=2. Backtrack, etc. root=2: start d=[1], ans maybe 1. Then go to 1: insert 3? Actually from 2, go to 1: insert 3 -> lower_bound([1],3) append -> d=[1,3], ans=2. Then backtrack, go to 3: insert 2 -> from d=[1,3]? Wait, after returning from 1, d back to [1]. Then go to 3: insert 2 -> lower_bound([1],2) append -> d=[1,2], ans=2. root=3: similar. So answer 2, correct.
Now, test with equal values: n=3, values [2,2,3], edges line 1-2-3. Paths: 1-2: [2,2] LIS=1; 2-3: [2,3] LIS=2; 1-3: [2,2,3] LIS=2. Answer=2. Our algorithm should get that.
So seems correct.
Now, finalize solution.
But we should consider memory: adjacency list with 6000 nodes, fine.
Now, potential improvements to speed:
Use int instead of size_t.
Use d.reserve(n) to avoid reallocations? But d is per root, we can reserve n at start of each DFS. That might help.
Use d.data() and len manually to avoid vector::size() calls? Not needed.
We'll add d.reserve(n) before dfs call.
Also, we can inline the dfs function? Compiler may inline.
We can also implement dfs as a separate function that takes d as reference, and we pass a reference to len? Actually we can maintain d as vector, it's fine.
Now, one more thing: The recursion for each root, we call dfs on all nodes. That's 36e6 calls. Each call has a loop over adjacency list. To reduce overhead, we could precompute for each node the list of neighbors and use indexing. That's already.
Maybe we can use iterative DFS to avoid function call overhead. Let's attempt to implement iterative version to see if it's not too complicated.
Iterative DFS with stack:
for root in 1..n:
vector d;
stack<tuple<int, int, int, bool, int>> st; // node, parent, state (0 enter, 1 exit), pos, old_val? Actually we need to store rollback info after processing children.
We could use two stacks: one for entry, and store rollback info on a separate stack.
Simpler: Use recursion.
Given that time limit might be generous, I'll stick with recursion.
But I recall that Codeforces problems often have strict time limits, so maybe we need to think of more efficient solution. Let's search memory: I think I've seen a problem "Road Accident" on Codeforces. I'm trying to recall the editorial. Possibly the solution is O(n^2). Let's try to think if we can compute answer using DP with two arrays: For each node, we can compute the LIS ending at that node for paths starting from some root? Not.
Maybe we can compute for each pair of nodes (u,v) the LIS on the path between them by using DP merging from both ends. For each node as LCA, we could compute LIS for upward and downward paths. But that still involves LIS merges.
Another idea: Because we only need the length, not the sequence, we might use the concept of "longest increasing subsequence" being equal to the size of a maximum antichain in a poset, but not.
Given n <= 6000, O(n^2) is 36 million, which is definitely fine. So if we can get rid of the log factor, it would be safe. Can we compute LIS length for each directed path in O(1) amortized? Possibly by using a DP that stores for each node the LIS length from root to that node, but as noted, LIS of the entire sequence is not simply the LIS ending at last node. However, we could compute both: the LIS ending at each position, and also the overall LIS for the prefix. The overall LIS for the prefix is the max of dp values up to that point. So if we maintain a Fenwick tree over compressed values, we can compute dp[i] = 1 + query(max over values < a[i]), and then update BIT at a[i] with dp[i]. The overall LIS length for the prefix up to i is max overall dp so far, which we can keep as a variable. This also requires O(log n) per insertion. So same.
But maybe we can compute LIS length for all paths from a root in O(n) by using a different technique: Since we are dealing with a tree and the order of nodes is along a root-to-leaf path, which is a line (when root is fixed, the tree is rooted, and the path from root to any node is a simple chain). So the sequences we consider for a fixed root are all root-to-node paths. These are essentially n sequences that are prefixes of each other along different branches. For a fixed root, we can compute LIS for each node using DP that merges along the tree. But note: root-to-node paths are not prefixes of a single sequence because when we go down one branch and then another, they diverge. However, if we do DFS from root, we process nodes in depth-first order, and the current stack always represents the path from root to current node. So we already use that.
Could we compute LIS for all root-to-node paths using a DP that stores for each node the LIS length up to that node? As said, that's not straightforward because LIS is not a function of just the last node; it depends on the entire path. However, we could compute for each node the entire d vector? That would be too much.
Given the simplicity, I'll implement O(n^2 log n) and hope it passes.
But wait: The problem might be from some contest where n up to 2000? Actually the statement says n up to 6000. That's moderate. So O(n^2 log n) with n=6000 might be okay.
Let's attempt to compute approximate runtime. I'll write a small C++ program to simulate 36e6 lower_bound operations on a vector of random ints and see time. But I can't run now. However, I recall that Codeforces solutions with n=5000 and O(n^2 log n) often pass. For n=6000, 6000^2 = 36 million, log n ~ 12, total ~432 million. I've seen solutions with 2e7 operations pass easily, 4e8 might be borderline but still often passes in 2 seconds if optimized? Possibly not. Let's check some examples: In Codeforces Round #629 (Div. 3), problem F maybe? Not.
Better to search memory: I recall a problem "C. Road Improvement" but not "Road Accident". Hmm.
Maybe we can reduce the constant by not using vector d but using a plain array int d[MAXN] and int len. Then binary search can be done via int pos = lower_bound(d, d+len, r[u]) - d;. This eliminates vector overhead. Rollback: if appended, we increase len, and on rollback we decrease len; if replaced, we store old value and restore.
We'll implement that.
Let's redesign:
int d[MAXN]; // global but used per DFS
int len; // current length
void dfs(int u, int p) {
// Insert r[u]
int x = r[u];
int pos = lower_bound(d, d+len, x) - d;
int old_val;
bool appended = (pos == len);
if (appended) {
d[len] = x;
len++;
} else {
old_val = d[pos];
d[pos] = x;
}
ans = max(ans, len);
code
for (int v : adj[u]) {
if (v != p) {
dfs(v, u);
}
}
// rollback
if (appended) {
len--;
} else {
d[pos] = old_val;
}
}
Then in main, for each root:
len = 0;
dfs(root, -1);
We need to ensure d array is accessible. This avoids vector allocations and push_back/pop_back. This should be faster.
Also, we can make d a local array? But we need it across recursion. We can make it global and just reset len per root.
Now, binary search: we can use std::lower_bound on d and d+len. That's fine.
Now, also we can attempt to use iterative DFS to avoid function call overhead. Let's try to implement iterative version using stack of tuples.
Iterative approach:
for root in 1..n:
len = 0;
stack<tuple<int,int,int,bool,int,int>> st; // node, parent, state (0 enter, 1 exit), pos, old_val, iterator index? Actually we can push entry and then after processing children push exit.
st.push({root, -1, 0, 0, 0}); // state=enter
while (!st.empty()) {
auto [u, p, state, pos, old_val] = st.top(); st.pop();
if (state == 0) {
// entering u
// insertion
int x = r[u];
int pos = lower_bound(d, d+len, x) - d;
bool appended = (pos == len);
int old_val = appended ? 0 : d[pos];
if (appended) {
d[len] = x;
len++;
} else {
d[pos] = x;
}
ans = max(ans, len);
// push exit state
st.push({u, p, 1, pos, old_val, appended?1:0}); // need appended flag
// push children for entry
for (int v : adj[u]) {
if (v != p) {
st.push({v, u, 0, 0, 0});
}
}
} else {
// exiting u: rollback
// using stored pos, old_val, and appended flag
// if appended: len--; else d[pos] = old_val;
if (appended) len--; else d[pos] = old_val;
}
}
But need to store appended flag. Also need to store old_val and pos. The variables in tuple must be defined. We can use a struct.
This iterative approach may be faster because it avoids function calls and recursion stack overhead. However, it may be more complex but doable.
Given that recursion may be acceptable, I'll start with recursive version with array d and len. If I get TLE, I could convert to iterative later. Since I'm not actually submitting to a judge now, I'll assume recursion passes.
But as ChatGPT I need to produce final answer. I'll provide solution with O(n^2 log n) using DFS from each node and rolling back LIS array.
Let's write final solution explanation accordingly.
But before final, I'll double-check for any mistake: The LIS of the path from root to node is computed based on the order of nodes as visited. In our DFS, when we go from root to a child, we always traverse the edge. The order of nodes in the stack is the order from root to current node. That's correct. However, we must ensure that when we go from root to a node via a path that goes through other nodes, we are indeed visiting nodes in the order of the simple path. Yes, DFS does that because we only go forward along edges, never revisiting nodes (parent check). So the current recursion stack is exactly the simple path from root to current node.
Now, what about the direction? The band can travel either direction along the path. Our DFS from root computes LIS for direction root->v. To get the reverse direction v->root, we also run DFS from v later. So both covered.
Thus answer is max over all these d.size().
Now, finalize.
One more potential micro-optim: Use global arrays for r and adj, and use for loops with int i.
Now, I'll produce final answer code.
But let's consider if there is any possibility to reduce the number of roots by using the fact that the maximum LIS over all paths will have a node that is the minimum value in that subsequence? Possibly we could just start DFS from each node as start, but we might also need to consider paths where the start is not the minimum. But our DFS from each node as start covers all directed paths, so it's fine.
Maybe we can cut half by only considering nodes as start where their value is the minimum among the two endpoints? Not reliable.
Thus final solution.
Now, produce final answer with explanation.
One more check: n up to 6000, we used recursion depth up to 6000. In some compilers, default stack size might be 8 MB, which should accommodate 6000 frames if each frame is not huge. Each frame may have a few ints and a return address, maybe ~ 48 bytes? 6000*48=288KB, fine.
But total recursion calls 36 million may cause stack overflow due to recursion depth? No, depth is limited; the number of calls is fine.
Now, let's write final answer.
Potential pitfall: For each root, we call dfs which uses global len and d array. We need to reset len=0 before each root. Also, d array does not need resetting because we only access indices up to len-1.
Edge Cases: If all values are equal, answer should be 1. Our algorithm: For any path, LIS length will be 1 because lower_bound will replace. So ans will remain 1.
Now, final code.
I'll write it.
Implementation:
#include <bits/stdc++.h>
using namespace std;
const int N = 6005;
int n, r[N];
vector g[N];
int ans = 0;
int lis[N]; // array for tails
int sz; // current size of lis
void dfs(int u, int par) {
int x = r[u];
int pos = lower_bound(lis, lis + sz, x) - lis;
bool appended = (pos == sz);
int old_val;
if (appended) {
lis[sz] = x;
sz++;
} else {
old_val = lis[pos];
lis[pos] = x;
}
if (sz > ans) ans = sz;
code
for (int v : g[u]) {
if (v != par) {
dfs(v, u);
}
}
if (appended) {
sz--;
} else {
lis[pos] = old_val;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 1; i <= n; ++i) cin >> r[i];
for (int i = 0; i < n - 1; ++i) {
int a, b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
ans = 0;
for (int root = 1; root <= n; ++root) {
sz = 0;
dfs(root, -1);
if (ans == n) break; // cannot improve further
}
cout << ans << '\n';
return 0;
}
That's the final code.
Now, provide explanation in the answer. The band will travel along a simple path and give concerts in some cities along that path in strictly increasing order of population. The goal is to maximize the number of concerts, i.e., the length of a strictly increasing subsequence of the values on some simple path (in a suitable direction).
Since the tree has at most 6000 vertices, we can afford to examine every possible directed path. For each city as the starting point, we perform a depth‑first search that walks along simple paths. While moving, we maintain the current sequence of cities on the path from the start to the current node and compute its longest strictly increasing subsequence (LIS) using an online algorithm (patience sorting) that works in logarithmic time per insertion.
To avoid rebuilding the LIS from scratch for each node, we update the LIS state when we enter a city and roll back the change when we leave it (because the DFS backtracks). This way, during the DFS from a fixed start we obtain the LIS length for the path from that start to every other city in total O(n log n) time.
We repeat this for every possible starting city, which gives O(n² log n) overall (n ≤ 6000, so about 36 million operations). The maximum LIS length seen over all directed paths is the answer.
The algorithm uses only simple data structures: adjacency list for the tree, an array for the patience‑sorting tails, and recursion with rollback information.
cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 6005;
int n, r[N];
vector<int> g[N];
int ans = 0;
int lis[N]; // tails of increasing subsequences
int sz; // current length of lis
void dfs(int u, int par) {
int x = r[u];
int pos = lower_bound(lis, lis + sz, x) - lis;
bool appended = (pos == sz);
int old_val;
if (appended) {
lis[sz] = x;
sz++;
} else {
old_val = lis[pos];
lis[pos] = x;
}
if (sz > ans) ans = sz;
for (int v : g[u]) {
if (v != par) {
dfs(v, u);
}
}
// rollback
if (appended) {
sz--;
} else {
lis[pos] = old_val;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 1; i <= n; ++i) cin >> r[i];
for (int i = 0; i < n - 1; ++i) {
int a, b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
ans = 0;
for (int root = 1; root <= n; ++root) {
sz = 0;
dfs(root, -1);
if (ans == n) break; // cannot be improved
}
cout << ans << '\n';
return 0;
}