We need to find the length of the longest non-decreasing subsequence (LNDS) of the given array of length n*T, where the array is constructed by repeating the given sequence of length n, T times. n ≤ 100, T ≤ 10^7, a_i ≤ 300. So we cannot generate the whole array. We need to use some combinatorial reasoning.
We want LNDS of a repeated sequence. The repeated sequence is periodic with period n. Observations: For large T, the LNDS can be constructed by taking many whole blocks where we include all occurrences of some values? Because the sequence repeats, the LNDS can include multiple copies of the same values. Since we can take non-decreasing subsequence, we can take elements from different blocks. Since within each block the order is fixed, we can choose to take elements from some positions across blocks.
We can think of the LNDS as a sequence of indices (i1, i2, ...) with i1 < i2 < ... and a_{i1} ≤ a_{i2} ≤ ... The indices are from 1 to n*T. Since the array is periodic, we can write each index as (block, position): block from 0 to T-1, position from 1 to n: index = block * n + pos. Then a = a[pos] (since repetition). So the value depends only on pos, not block.
Thus we have a grid: we have T copies of positions 1..n with values a[pos]. We need to pick a sequence of indices in increasing order (by overall index) such that values are non-decreasing.
Because value only depends on pos, the LNDS can be thought of as picking some positions from each block, with increasing block numbers, and within a block the order is fixed: indices inside a block are in order of positions. So we can model as: we have T blocks, each block has n items in order pos=1..n with values a[pos]. We need to form a non-decreasing subsequence by selecting items from these blocks in order of increasing overall index (i.e., increasing block number, and within same block increasing pos). Equivalent to: we can interleave picks from different blocks, but the ordering constraints: if we pick an item from block b at position p, then next pick must be from a later overall index: either same block with larger position, or a later block with any position.
We need max length.
Classic problem: LNDS of concatenated T copies of a sequence. For large T, often the answer is: LNDS of a single sequence plus (T-1) times the maximum number of elements we can take from a full block while maintaining non-decreasing property when repeated? Actually, think of the following: Since we can take many copies of a value, we might take entire blocks if the block's sequence is non-decreasing? But it's not necessarily. However, we can select a subsequence from each block that is non-decreasing and we can combine them across blocks such that the last value of block b ≤ first value of block b+1 selected. But we are allowed to skip elements within block. Also, we can intermix: you could take some from block b, then some from block b+1, then maybe later come back to block b? No, because indices must increase, so once you move to block b+1 you cannot go back to block b. So the subsequence will be partitioned by blocks: it will consist of selections from blocks in increasing block order, and within each block, the selected positions are increasing.
Thus, the LNDS problem reduces to: We have T blocks, each block i (0-indexed) yields a subsequence (possibly empty) from positions 1..n with increasing positions, with values non-decreasing within the block. And between blocks, the last value of block b must be ≤ first value of block b+1 (if both non-empty). But if block b's subsequence is empty, then we just consider previous non-empty block's last value with next block's first. Actually, we can also have gaps: if we skip a block entirely, the condition only applies between consecutive selected elements, which may be from different blocks. So the condition is that for any two selected elements, if they are from blocks b1 and b2 with b1<b2, then the value of the earlier ≤ later value. But because within blocks we already enforce non-decreasing, the overall condition is just that the whole sequence is non-decreasing. So effectively we are concatenating subsequences from each block in order, and the concatenated sequence must be non-decreasing. That is equivalent to: For each block, we choose a subsequence (possibly empty) such that when concatenated, the resulting infinite sequence (over blocks) is non-decreasing. The maximal total length.
Now since blocks are identical (same sequence a[1..n]), the optimal selection from each block should be the same pattern? Possibly, but with the possibility of varying because the "state" (the last value from previous block) matters.
We can think in terms of DP across blocks. Since T is huge, we need to find some periodicity or use matrix exponentiation. Since n is small (≤100) and a_i ≤ 300, we can consider DP on values? However, the state also includes the last value used, which can be up to 300. Actually a_i in [1,300]. So value domain small.
But we also have the ability to choose subsequence within a block, which may depend on the incoming "lowest allowed value" (or the last value so far). Typically, for a fixed sequence of length n, we can compute for each possible starting threshold (minimum allowed value) the maximum length of a non-decreasing subsequence we can extract from that sequence (in order) with all values ≥ threshold? Actually we need non-decreasing condition: Given that we have a current last value v (the last selected element's value), we can only select subsequent items with value ≥ v. And we want to maximize the number of additional selections we can make from the current block (and possibly subsequent blocks). But we can also skip the block entirely.
This resembles a DP across blocks where state is the current last value (or maybe also the position within block? But we process block as a whole, we can compute transition: given an input value v (the value of the last selected element before the block, or -∞ for start), we process the block's sequence (positions 1..n) and we can decide which elements to take, subject to values ≥ v and non-decreasing. The output will be the new last value after processing the block (which might be v if we take nothing), and the number of elements taken from the block. However, the number of elements taken can depend on v. But note: we also have the possibility to take elements from future blocks. So the DP across blocks: dp[b][v] = maximum length of subsequence from blocks b..T-1 given that the last selected value before block b is v (or no last selected? We can treat v as the last value, and we need to pick elements with values ≥ v). Initially, before first block, we can consider v = -∞ (or 0). At the end, we want max over states.
But T up to 10^7, and v up to 300, so we could potentially do matrix exponentiation if the transition per block is linear and independent of block index (since blocks identical). However, dp state is over v values: 0..300 maybe plus a sentinel for no previous selection (we can treat that as v=0 with the condition that any value >=1 is allowed? Actually a_i >=1, so we can treat v=0 as lower bound). Then the transition function f: for each input v, we compute the best possible outcome: we process the sequence of length n and choose a non-decreasing subsequence where all chosen values >= v, and we also can optionally not take any? But we can also take some and then the output is the last value taken (or remains v if none). And we want to maximize total count added plus future gains from next blocks, which depend on the output last value.
If the transition is deterministic? Not exactly: given v, the optimal way to process a block may not be unique; the best total length from the current block plus rest may depend on which last value we end with after the block. For DP, we need to consider all possibilities: from state v, we can choose a subsequence from the block that yields some output value u (>= v) and adds length k, and then go to state u for next block. So we can define a set of possible transitions (u, gain). Then the DP over many identical blocks is like a longest path in a directed graph with nodes=possible v values, edges with weight = gain (number taken in one block) and change state to u. Since we have many identical blocks, we need to compute the maximum total gain over T blocks, starting from v0=0. This is analogous to finding the maximum weight path of length T (or exactly T steps? Actually we have T blocks, each block we apply one transition. But careful: In each block, we may take a subsequence from that block, but we also have the option to skip the entire block (gain 0, state unchanged). So that's an edge from v to v with weight 0. So the DP is: dp[0][v] = 0? Actually after processing 0 blocks, we are at state v (initial v=0). Then for each block we apply a transition. So after T blocks, we have some state, and total gain is sum of gains. We want max total.
This is like a max-plus algebra (tropical semiring) over state space of size M=301 (0..300). We can define a transition matrix A of size M x M where A[v][u] = maximum gain achievable from one block, starting with state v and ending with state u. Then after T blocks, the maximum total gain starting from initial state 0 is max over u of (A^T)[0][u]. But note that initial state before any block is v0 = 0 (meaning no previous value, or lower bound 0). And we consider that we may have not taken any element yet? But gain counts the elements taken in those blocks. The answer we want is the total number of elements taken from all T blocks, which is the sum of gains. That's exactly the total length of the subsequence. So answer = max_u (A^T)[0][u].
But we need to define A properly. For each v and u, we need the maximum number of elements we can select from a single block such that: starting with last value = v (so we can only pick values >= v), the subsequence we pick from the block (in order) is non-decreasing, and after picking some elements, the final selected value is u (or if we pick none, then u=v and gain 0). This is a classical DP within a block: given a sequence of n numbers, we want to compute for each start bound v and end value u the maximum length. But we must ensure that the subsequence is chosen from positions 1..n in order, and we may also skip. This is similar to: we have the array b[1..n] = a[1..n]. For a given starting lower bound v, we want to pick a non-decreasing subsequence from b where all chosen values >= v, and we track the last value. The maximum gain for each possible ending value u.
We can compute this by DP over the sequence: let f_i(x) = maximum length of subsequence from prefix up to i that ends with value exactly x (or at most x?) Actually we need to incorporate the condition that the last value is exactly u. But maybe we can compute for each possible v the best we can do, and also the resulting state distribution.
Since n is small (≤100) and values up to 300, we could brute-force all possibilities within a block by DP on positions and last value. Specifically, we can define for each block, the DP of processing the block from start to end, with a state representing the last selected value. But since the block is processed only once, we can compute the transition function by considering all possible ways.
Alternatively, we can think of the block as a function that maps an input lower bound to a set of (output last value, count) pairs. Since the block length is small, we can compute for each v (0..300) the best possible (max count) and also for each possible output u we need the best count. But note: For a given v, the optimal total count from the block might not be unique in terms of output u; we might have multiple u with same count? Actually we need for each u the maximum count achievable that ends with u, because later blocks' optimal depends on u. So we need to fill the matrix A[v][u] as the maximum count such that there exists a subsequence from the block starting with lower bound v and ending with last value exactly u.
We can compute A[v][u] by simulating the block: For each v, we run DP over positions with state = last selected value (or none). Since values are ≤300, we can have DP array of size 301. Starting with initial state: before processing any elements in the block, we have last value = v (but if we haven't selected any yet, we may also treat it as "no selection yet", but we need to consider that we might not take any, then output is v and gain 0. Alternatively, we can treat that we have the option to start selecting from the block; when we select the first element, it must be ≥ v. So we can incorporate that.
Let's define state as the last selected value (which is an integer from 1..300, or a special value representing that we haven't selected any yet, but that's equivalent to last = v? Actually careful: before processing the block, we have a constraint: we can only pick values ≥ v, because the last selected value from previous block is v. If we pick none, output is v. If we pick some, the first picked must be ≥ v, and subsequent picks must be ≥ previous. So the last selected value will be some u ≥ v. So we can treat the input state as v, which is also the default output if no picks. So we can set initial DP: before processing the block, we have a hypothetical "last value" = v, but this is not an actual element taken. Then as we iterate through the block's elements, we can decide to take an element if it ≥ current last value. The DP can track the best count for each possible last value after processing some prefix. At the end, we have DP over possible last values (including v, representing no picks). The count associated with last = v is 0 (no picks). For other u, count is number of picks made.
Thus we can compute for each v, the array best_end[u] = maximum count (≥0) achievable ending with last value exactly u. Then A[v][u] = best_end[u].
Now, the block length n ≤ 100, values ≤ 300, so we can compute this for each v (0..300) by a DP that iterates through the n elements, updating an array dp_val[1..300] representing max count for each possible last value. The DP would be: start dp = array of -inf, set dp[v] = 0 (meaning we have not taken any yet, last = v, count=0). Then for each element x in the block (in order), we consider transitions: For each current last value y (y from 1..300, or include v?), we can either skip x: dp_next[y] = max(dp_next[y], dp[y]); or take x if x ≥ y: then new_last = x, new_count = dp[y] + 1; dp_next[x] = max(dp_next[x], new_count). After processing all elements, the final dp gives best_end for each u. Complexity: for each v, we process n * 300, total 301 * 100 * 300 = about 9 million, which is fine.
But careful: v can be 0 as well? We treat v=0 meaning no lower bound; all elements ≥1 are allowed. So we should include v from 0 to 300. However, the values are from 1..300. If v=0, we can take any element as first pick. So we need to treat v=0 as a valid state; in DP, we need to allow last=0? Actually when we set dp[v]=0, if v=0, we need to allow that as a starting last value; but then when taking an element x, condition x≥0 is always true, so it's fine. However, x ranges 1..300, so after picking first element, last becomes x≥1. So we need state values from 0 to 300. That's 301 values (0..300). So total states 301. So DP per v is O(n * 301) if we update efficiently. Actually the transition: for each y, we need to check if x ≥ y, and update dp[x] = max(dp[x], dp[y]+1). This can be done by maintaining the best dp for all y and then for each x, we want to take max over y ≤ x of dp[y] + 1. Since we have to process each x separately, we could maintain a running maximum. But since state size is small, we can just loop over all y each time. Complexity per block: n * 301 * 301? Wait: For each element, we need to compute new dp from old dp. If we iterate over all y (0..300) and for each consider skip or take, that would be O(301) per element, not O(301^2). Actually we need to compute new dp array based on old dp. Standard DP for LIS with small value domain: we have dp[val] = maximum length of subsequence ending with that value, considering elements processed so far. Starting with initial dp: dp[v] = 0, all others -inf. Then for each x, we can update: new_dp = dp copy (skip). For taking: we want to set dp[x] = max(dp[x], max_{y ≤ x} dp[y] + 1). Since dp[y] is for ending with y. That's exactly LIS DP with coordinate compression. So we need to compute max_{y ≤ x} dp[y] efficiently. Since domain size is 301, we can just compute prefix max each time: O(301) per element. So overall per v: O(n * 301). Then for all v (301), it's O(301 * n * 301) = O(301^2 * n) ≈ 9e6, still fine. Actually 301^2 ~ 90601, times n ≤100 => ~9 million, acceptable.
But we need to compute A[v][u] for all v,u. However, we could compute for each v the final dp after processing the block, which gives for each u the maximum count ending with u. That's exactly A[v][u]. So we can compute matrix A of size (301 x 301). However, note that we need to consider that we may also have the option to skip the entire block, which corresponds to ending with u=v and count 0. Our DP will already include that because we start with dp[v]=0 and skipping all elements yields dp[v]=0 at the end. But we must ensure that for u=v, A[v][v] is at least 0; it could be that there is a better sequence that ends with value v? But ending with value v implies the last selected value is v, which could be achieved if we take some elements but the last selected value equals v. However, v is the starting last value; after taking elements, the last value u will be some value picked, so it could be equal to v only if we pick no elements (since if we pick any element, the last value becomes the value of that element, which is at least v but could be equal to v if we pick an element with value v? Yes, if v is a value that appears in the block, we could pick it, and then possibly end with v (if the last picked is v). For example, starting with v=3, if we pick a 3 and then stop, then last value =3, count=1. So A[v][v] could be >0. That's fine.
Now, after we have A, we want to compute the maximum total count over T blocks. This is like computing the max-plus power of A. Since T can be up to 1e7, we need to do exponentiation in O(log T) with matrix multiplication in max-plus semiring, but matrix size 301, which would be 301^3 = about 27 million per multiplication, times log T ~ 24, about 650 million, maybe borderline but possibly okay in C++ with optimizations? 27 million operations per multiplication (each multiplication is max over k of A[i][k] + B[k][j]), that's 301^3 ≈ 27.3 million. Doing 24 such multiplications gives ~650 million operations. In Python it's too slow. We need a better approach.
But note that T can be huge, but n is small. There might be a simpler combinatorial insight: The answer may be something like: longest non-decreasing subsequence of a single block (call L) plus (T-1)*freq of some value? Wait, think about classic problem "Longest Non-Decreasing Subsequence in Repeated Sequence" reminiscent of Codeforces problem "Little Pony and Harmony Chest"? Not exactly. Actually I recall a problem: "Given array a of length n, repeat it T times, find LIS." The solution often uses the fact that after many repetitions, you can take all occurrences of the most frequent element, but you need to consider transitions. Let's think.
Because values are small (≤300), we can compute the frequency of each value in one block. The LNDS can include many copies of the same value across blocks. But the order matters: within a block, the positions are fixed, so you can't just take all copies of a value because they may be interleaved with smaller values? Since non-decreasing, if you want to take many copies of a value, you need to ensure they appear in non-decreasing order, but if they are all equal, that's fine. So you can take all occurrences of value x in each block, provided you can arrange them in order: but the indices order naturally is: all occurrences in block 0 appear before those in block 1, etc. So if we pick all occurrences of value x across all blocks, they will be in non-decreasing order because they are equal. However, we might also mix values. The challenge is within each block, the order of values is fixed, so to include multiple values, we need to respect the order. Also, between blocks, we need non-decreasing: if we pick some value x from block b, then next pick from block b+1 must have value ≥ x. So if we pick a high value early, we might block later lower values. So we typically want to pick increasing values across blocks.
This looks like we can treat each value separately and consider the longest chain of blocks where we take increasing sequences.
Alternate approach: Since n is small, we can try to compress the T blocks by noting that after many blocks, the optimal subsequence will take a pattern that repeats per block, maybe taking a specific subsequence from each block. Because the blocks are identical, the DP across blocks with matrix exponentiation suggests that the optimal policy may become periodic after some point (like the linear recurrence in max-plus algebra). Since the state space is small (301), we could use exponentiation by squaring if we can implement efficient max-plus multiplication. 301^3 ≈ 27M; log2(1e7) ≈ 24. So 27M*24 ≈ 648M operations. In Python, this might be too slow, but perhaps with optimizations and using numpy? But typical Codeforces Python solution might pass if we reduce state size further? Actually values are up to 300, but we can compress to only values that appear in a? Because values that never appear might still be relevant as state (last value) if they are between appearing values? For example, you could have last value = 150 even if 150 never appears, because you might have picked 140 and then want to transition to 160; the state 150 is not used because you never have an element of that value. However, the DP transition might produce state values that are exactly the values of elements taken, which are from the set of values appearing in a. Also input state v can be any value from 0..300, but if we start with 0, and after taking elements we end with some value that appears. So the reachable states are limited to {0} ∪ set of values in a. Since a_i ≤300 and n ≤100, the distinct values are at most 100. So state size could be at most 101. That's much smaller! Indeed, we can map each distinct value that appears, plus 0. However, we also need to consider values that are not in a but could be used as state? For instance, suppose we have v=5, but 5 doesn't appear. Could we end with v=5 after processing a block? Only if we pick an element with value 5; if 5 doesn't appear, then we cannot end with 5 unless we pick none and remain at 5, but we started with 5? But if 5 is not in a, then from a starting state 5, we might be able to take an element with value >=5, say 7, and then end with 7. So state 5 could be reachable as input if it is passed from previous block output? Could previous block output 5? Only if we ended with value 5 after processing previous block. Since 5 not in a, the only way to end with 5 is to have started with 5 and taken no elements. So if we start with a value not in a and not 0, we could remain there without picking anything. But is that useful? Possibly, if we have a value like 5 that is between two values that appear, we could use it as a threshold. For example, suppose a has values 3 and 7. Starting from 0, we might pick 3, then we are at state 3. If we want to later pick 7, we can directly from 3. But if we had state 5, we could not pick 3 because 3 <5, but we could pick 7. So 5 might be an intermediate state that could arise if we skip picking in a block? But state 5 could only arise if we had state 5 before and we didn't pick anything. So if we never have state 5 initially, we can't get it. The only initial state is 0. So any state that is not in the set of values appearing (or 0) cannot be produced from 0 via transitions because to change state you need to pick an element whose value becomes the new state. So the only possible states are 0 and the set of values that appear in a. However, consider the possibility: from state v, you pick an element x >= v, new state = x. So the new state is always either v (if you pick none) or some x that appears in a. Thus reachable states from 0 are subset of {0} ∪ values in a. Therefore we can restrict state space to these distinct values. Let's call S = sorted list of distinct values in a, plus 0. The size m ≤ 101. That's good.
Now we need to compute transition matrix A of size m x m, where A[i][j] = maximum number of elements taken in one block when starting from state v_i and ending with state v_j. We can compute this by DP for each starting state v_i. Since m small, we can do DP for each v_i using the original DP over the block with state size 301, but we can also compress to values in S only? But the DP within block may need to consider intermediate states that are not in S? Actually when we process the block, the last value after picking some elements can be any value that appears among the elements we selected. Since we only select elements from the block, the last value will be one of the a_i values (or possibly the starting value if none selected). So it's safe to only track values in S (including 0). However, during the DP, when we consider taking an element x, we need to compute max over y ≤ x of dp[y] + 1. If we only have dp for values in S, we need to consider y that are not in S but could be between values? But if y is not in S, dp[y] is defined? It would be -inf because we never have state y. But could there be a scenario where the best subsequence uses a last value that is not in S? No, because the last value must be the value of some selected element, which is in a, so it's in S (or starting value 0). So we only need to consider states that are in S. However, the condition x ≥ y: if y is not in S, it's irrelevant because we never have dp[y] non-negative unless y is starting state 0 or some a value. But there might be values between 0 and max that are not in S, but we don't care because we never have them as state.
Thus we can compress the value domain to the set S, and also maintain ordering. For DP within block, we need to compute for each starting v (∈ S) the best count for each ending u (∈ S). Since S size ≤101, we can do DP for each v by iterating over the block and maintaining dp array indexed by S positions (or values). However, the transition "max over y ≤ x" requires considering all y in S that are ≤ x. Since S is sorted, we can compute prefix maximums quickly.
Simplify: Because the value range is small (0..300), we could just keep dp array of size 301 for each v, but we have m ~ up to 101 starting states, so total work 101 * 100 * 300 ≈ 3 million, which is fine. Then we extract A[i][j] by mapping the dp result to the states.
But then we need to compute max-plus matrix power for T blocks. With m up to 101, matrix multiplication O(m^3) ≈ 1e6 per multiply. Times log T ~ 24 gives ~24 million, which is okay in Python if implemented efficiently with loops and maybe using list comprehensions? 1e6 operations per multiplication, 24 multiplications = 24e6, plus overhead, might be okay. However, max-plus multiplication requires nested loops: for i in range(m): for k in range(m): if A[i][k] is not -inf then for j in range(m): C[i][j] = max(C[i][j], A[i][k] + B[k][j]). That's O(m^3). For m=101, that's ~1,030,301 operations per multiplication. Actually 101^3 = 1,030,301. So 24 million operations. That's fine in Python, but we must be careful with -inf handling and avoid too much overhead. Use Python lists of lists, use local variables, maybe use for loops. Could be acceptable.
But wait: T can be up to 10^7, but we need to compute A^T, but note that we might be able to do exponentiation quickly. However, we also need to consider that we may have to handle the fact that the transition is not exactly matrix multiplication? Actually DP over blocks is like: after k blocks, we have best total count for each state: dp_k[u] = max over v (dp_{k-1}[v] + A[v][u]). This is exactly max-plus multiplication: dp_k = dp_{k-1} ⊗ A, where (dp ⊗ A)[u] = max_v dp[v] + A[v][u]. So after T blocks, dp_T = dp_0 ⊗ A^T. dp_0 is initial state: dp_0[0] = 0, others = -inf (since we start with last value =0, no elements taken yet). Then answer = max_u dp_T[u].
So we need to compute A^T in max-plus semiring, then apply to initial vector. Alternatively, we can exponentiate the transition using repeated squaring on the matrix, and then multiply the vector. Since m small, we can do matrix exponentiation.
But we need to be careful: T may be 0? Actually T ≥ 1. So we have at least one block.
Edge cases: n=1, T large. Then the array is all same element repeated. LNDS length = T (since all equal, we can take all). Our method: For block with one element a1. Starting from v=0, we can take that element if a1 ≥0, which is always, so A[0][a1] = 1, also A[0][0] = 0 (skip). For state a1, we can also take? If starting from a1, we can take the element if a1 ≥ a1 (true) so A[a1][a1] = 1? Actually if we start with last value a1, we can take the element (value a1) because it's ≥ a1. That would increase count by 1 and end with a1. So A[a1][a1] = 1. Also we could skip: 0. So matrix. Then exponentiation will give total length = T? Let's test: After T blocks, starting from 0, we could take each block's element, so total = T. Compute: dp_0 = [0, -inf,...]. After one block, dp_1 = max over v dp_0[v] + A[v][u]. dp_1[0] = dp_0[0] + A[0][0] = 0; dp_1[a1] = dp_0[0] + A[0][a1] = 1. After two blocks: dp_2[0] = max( dp_1[0]+A[0][0]=0, dp_1[a1]+A[a1][0]? A[a1][0] probably -inf because can't go to 0 (since ending state after picking cannot be 0 unless you skip; but you can skip, so from a1 you can skip to remain a1? Wait, ending state 0 is only possible if starting state 0 and skip all, because 0 is not a value that can be achieved by picking an element (since values are ≥1). So from a1, if we skip the block, we remain at a1, not 0. So A[a1][0] should be -inf. So dp_2[a1] = max(dp_1[0]+A[0][a1]=1, dp_1[a1]+A[a1][a1]=1+1=2) = 2. So indeed after T blocks, dp_T[a1] = T. So works.
Now we need to compute A matrix accurately.
Compute distinct values: let's get sorted list vals = [0] + sorted(set(a)). But careful: 0 is not in a but we include as starting state. However, we must ensure that 0 is considered less than all positive values. That's fine.
We'll map each value to index 0..m-1, with 0 at index 0 perhaps.
Now, for each start value v in vals (including 0), we compute best_end array (size m) representing max count ending at each u. We'll do DP over the block sequence.
Implementation details for DP for a given start v:
We have n elements: arr[0..n-1] (list of ints). We'll maintain dp array of length m (or perhaps full size 301 for simplicity) initialized to -inf. Set dp[ index_of(v) ] = 0.
But careful: The DP state tracks the last selected value, which must be one of the values in vals. However, when we take an element x, we set new last = x. So we need to map x to its index in vals. Since x is in vals (except maybe not? Actually x is from a, so it's in set(a), which is subset of vals without 0). So mapping exists.
Now for each element x in arr:
We compute new_dp = dp copy (skip case)
Then for each possible current last y (represented by index i, value val_i), if val_i ≤ x, we can take x: candidate = dp[i] + 1, and we compare to new_dp[index_of(x)].
But we also need to consider that we might have multiple y that satisfy val_i ≤ x. To compute efficiently, we can compute prefix maximum over dp for values ≤ x. Since vals is sorted, we can precompute for each x, the range of indices with val ≤ x. Since m small, we can just loop over all i and check condition.
Simplify: For each element x, we can compute best = -inf. For i in range(m):
if vals[i] <= x:
best = max(best, dp[i])
else: break because sorted. Then if best != -inf: new_dp[idx_x] = max(new_dp[idx_x], best + 1).
We also need to consider that we can take x even if we haven't taken any elements? That is covered because dp includes the starting state (v). Also, we must ensure that we are allowed to take x multiple times? Within a block, we cannot take the same element twice, but we can take it if it appears; the DP processes each element sequentially, so it's fine.
After processing all elements, we have final dp. Then for each u in vals, A[start_index][idx_u] = dp[idx_u] (which is max count ending with u). However, note: dp includes the possibility of not taking any (starting state) which gives count 0 at index of v. Also, if there is a better sequence that ends with same value v but with positive count, that will be stored.
But is our DP correct for computing the maximum count achievable ending with exactly u? It should be, as it's standard LIS DP with fixed starting condition. However, one nuance: The DP we described updates new_dp[x] from max over all dp[y] with y ≤ x plus 1. But this also includes the case where we take x and then later take another element with same value? That's fine because non-decreasing allows equal.
But we also need to consider that we might skip some elements and then take later ones. The DP handles that because we carry dp across elements.
Thus, for each start v, we compute dp after processing all n elements.
Complexity: For each start v (m <= 101), we loop over n (<=100) and for each element we loop over m to compute prefix max, so O(m * n * m) = O(n * m^2). With m101, n100 => ~1e6 operations. That's fine.
Alternative: we could compute A more efficiently by leveraging the small value range 0..300 and using array of size 301, but that's also fine.
Now after constructing A (m x m), we need to compute the max-plus matrix power for exponent T. However, note that we have T blocks, but the array length is n * T. Our DP models processing each block one by one with transition A. But is it correct that the transition for each block is identical and independent? Yes, because the blocks are identical and we treat each block separately, and the state (last value) is passed between blocks. The order of processing is block 0, then block 1, ..., block T-1. Since the transitions only depend on the block's sequence and the incoming state, they are identical for each block. So A^T is appropriate.
But we must be careful: The block transition A includes the possibility of taking elements from that block. But does our DP within a block consider that we can pick elements in any order within that block? Yes, we process the block sequentially. And the DP finds the optimal subsequence within that block given the starting state v. However, is it always optimal to treat each block independently? That is, given a global sequence of T blocks, the optimal subsequence can be seen as: for each block, we pick a subsequence (depending on the incoming state) such that the concatenation is non-decreasing. Since the blocks are separated (indices increase), the choices in different blocks are independent except for the state passed. The optimal policy can be determined by DP across blocks, and the per-block optimal decision for a given incoming state is indeed the best we can do in that block, as we computed. Because future blocks only care about the outgoing state (last value). So the DP decomposition is correct.
Thus answer = max_u ( (initial vector e0) * (A^T) )[u] where e0 is vector with 0 at index of 0 and -inf elsewhere.
But we can also compute via exponentiation of A and then multiply, or we can exponentiate using repeated squaring on the vector: start with vec = e0, then while T>0: if T&1: vec = vec ⊗ A; A = A ⊗ A; T>>=1. This is similar to binary exponentiation but with matrix multiplication. The vector-matrix multiplication in max-plus is O(m^2) per multiplication. Since we need to do O(log T) such multiplications, total O(m^2 log T) ~ 101^2 * 24 ≈ 244k, plus matrix squaring O(m^3 log T) for precomputing powers? Actually we can do exponentiation by squaring on the matrix to compute A^T, then apply vector. However, we can avoid full matrix exponentiation by doing vector exponentiation: we can square the matrix while also applying to vector when needed. That would require both matrix multiplication (for squaring) and vector-matrix multiplication. Since we need to square the matrix log T times anyway, we have to do matrix multiplication for squaring (O(m^3 log T)). But we could also use exponentiation by repeated squaring on the matrix and then multiply vector, that also involves O(m^3 log T) for matrix powers. However, if we do the vector approach, we still need to compute A^(2^k) for each k to apply to vector when bit is set. That requires squaring the matrix each step anyway. So we need to do matrix squaring.
But maybe we can do better because m is at most 101, so O(m^3 log T) is about 1e6 * 24 = 24e6, which is okay. We'll implement standard max-plus matrix exponentiation.
We need to define -inf as a sufficiently small number, e.g., -10**18.
Implementation steps:
- Read n, T.
- Read list a of length n.
- Build sorted list of distinct values from a, and prepend 0. Let values = [0] + sorted(set(a)). m = len(values).
- Create mapping val_to_idx: dictionary mapping value to index.
- For each start index s (0..m-1) where start value = values[s], compute dp array after processing the block.
- Initialize dp array of length m with -inf. dp[s] = 0.
- For each x in a:
- idx_x = val_to_idx[x] (since x in a, it's present)
- Compute best = -inf
- For i in range(m):
if values[i] <= x:
best = max(best, dp[i])
else: break (since sorted)
- new_dp = dp[:] (or we can update in place carefully? We need to use old dp for all transitions. So we need to compute new_dp based on old dp.)
- If best != -inf: new_dp[idx_x] = max(new_dp[idx_x], best + 1)
- dp = new_dp
- After loop, A[s][j] = dp[j] for all j.
But is this DP correct for capturing all possibilities? Let's test with a simple example: a = [3,1,4,2], n=4. We'll compute A for start v=0.
We'll do by hand? Later.
One nuance: Within a block, after we take an element x, the state becomes x. However, our DP only allows transitions from state y to x if y <= x, which is correct. But we also need to consider that after taking x, we might later take another element with same value x? That's allowed, and our DP will handle because later when we see another x, we will consider current state = x (or other) and since x <= x, we can take again. However, there's a subtlety: In the DP update, we did new_dp[idx_x] = max(new_dp[idx_x], best+1). But note that best is computed as max over all dp[i] with values[i] <= x. This includes the case where dp[i] corresponds to a state with value y, and we take x. But what about the case where we skip the element? That is handled by new_dp = dp copy (so we keep old dp). Also, what about the case where we take the element and then later we might want to also take another element later that is less than x? Not allowed because sequence must be non-decreasing. So our DP correctly enforces non-decreasing.
But we also need to consider that we might take multiple elements within the same block. The DP as described processes sequentially and updates dp for the state after considering the element. At each step, dp[state] represents the maximum length of a subsequence from processed prefix that ends with that state. The update rule (taking current x) sets dp[x] to max over previous states with value <= x plus 1, which is standard. So this yields the optimal subsequence for the whole block.
Thus, A[s][j] is the maximum length of subsequence from the block that ends with value values[j], given start state values[s].
But note: The start state s might be a value that is not 0. For example, start state = 3. Our initial dp has dp[s]=0. That means we consider that we have already "selected" a value of 3 before the block? Actually the state represents the last selected value before the block. In our DP, we treat that we can start taking elements from the block, and they must be ≥ 3. The DP's initialization with dp[3]=0 means we have a subsequence of length 0 that ends with value 3 (i.e., no elements taken yet, but last value is 3). That's correct.
Now, after computing A, we have a matrix where A[s][j] could be -inf if it's impossible to end with j after processing the block starting from s. For example, if starting value is large, we may not be able to take any element and only end with the same s (by skipping all), so A[s][s] should be at least 0. Also, if we can take some elements, we may end with some j >= s.
Now, we need to compute the result for T blocks. Let's denote M = A.
We want to compute vector v after T steps: v = e0 * (M^T) in max-plus. Where e0 is row vector? Actually typical max-plus multiplication: if we have dp vector as row (size m), then dp_next[u] = max_v dp[v] + M[v][u]. So that's row vector multiplied by matrix on the right. So we can treat v as list of length m, initial v[0]=0, others -inf. Then for each block, we update v = v ⊗ M. After T blocks, we have v_T. Then answer = max(v_T). So we need to apply M T times.
We can exponentiate M: compute M^T via binary exponentiation, then v_T = v0 ⊗ M^T.
Let's define matrix multiplication in max-plus: (A ⊗ B)[i][j] = max_k (A[i][k] + B[k][j]). This is associative. We'll compute M_pow = M^(2^p) for p up to log2(T). Then for each bit of T, we update result vector (or result matrix if we want full power). Typically we do:
result = identity matrix? But we are applying to vector, so we can maintain a vector and square M.
Approach 1: Use exponentiation by squaring on matrix to compute M^T, then multiply vector. We'll need an identity matrix for max-plus: identity I has 0 on diagonal and -inf elsewhere, because v ⊗ I = v. So we can start with res_matrix = I, and while T>0: if T&1: res_matrix = res_matrix ⊗ M; M = M ⊗ M; T>>=1. At the end, compute v = v0 ⊗ res_matrix. This involves matrix multiplication for res_matrix and M. Complexity O(m^3 log T). m ~ 101, log T ≤ 24, so about 24*1e6 = 24e6 operations. Each operation is addition and max, which is okay in Python if optimized.
But we must be careful about -inf values; we need to handle them efficiently to avoid many comparisons. We'll use a large negative number, say NEG = -10**18.
We'll implement matrix multiplication as nested loops: for i in range(m): for k in range(m): if A[i][k] != NEG: aik = A[i][k]; then for j in range(m): tmp = aik + B[k][j]; if tmp > C[i][j]: C[i][j] = tmp. This is typical. Since m is small, we can also use list comprehensions but loops are fine.
Alternatively, we could use the vector approach: keep vector v, and for each bit, if T&1: v = v ⊗ M (O(m^2)); then M = M ⊗ M (O(m^3)). This also requires matrix squaring O(m^3 log T) and vector-matrix multiplications O(m^2 log T). So similar.
Given that m^3 is ~1e6, we can implement straightforwardly.
But there might be an even simpler method: Because T is large, but values are small, perhaps the answer can be computed as: (T - 1) * L + something, where L is the maximum count we can get from a block when we are allowed to "repeat" a state? Actually, after many blocks, the optimal strategy might be to, for each block, take the subsequence that yields the maximum increase per block while keeping the state unchanged? This resembles finding the maximum mean weight cycle in the transition graph? Not exactly.
Consider that we are looking for the maximum total count over T steps, starting from state 0. This is like a longest path problem in a weighted directed graph (states as nodes, edges from v to u with weight A[v][u]) over exactly T steps (since we have T blocks). We can also think of it as: we want to maximize sum of weights along a walk of length T from node 0. This can be solved by exponentiation.
Given the constraints, exponentiation is fine.
But we must be careful about potential overflow or negative infinities.
Now, we should test with sample:
n=4, T=3, a=[3,1,4,2].
First, distinct values: {1,2,3,4} plus 0 => values = [0,1,2,3,4]; m=5.
Compute A for each start.
Let's compute manually to verify result 5.
We'll compute A[0][*], etc.
We need to compute DP for start v=0 (value 0). Process a: [3,1,4,2].
Initialize dp: dp[0]=0 (since index of 0 is 0), others -inf.
Element 3: best over values ≤3: only value 0 (dp[0]=0). So best=0, candidate=1. new_dp = dp copy, set dp[3]=1. dp becomes: idx0:0, idx3:1, others -inf.
Element 1: values ≤1: values 0 (0) and 1? But dp[1] is -inf. So best = max(dp[0]=0, dp[1]? -inf) = 0. candidate=1. new_dp = previous dp copy, then dp[1] = max(existing -inf, 1) = 1. But also we keep previous dp[3]=1. So dp now: idx0:0, idx1:1, idx3:1.
Element 4: values ≤4: all values (0,1,2,3,4). best = max(dp[0]=0, dp[1]=1, dp[2]? -inf, dp[3]=1, dp[4]? -inf) = 1. candidate=2. new_dp: update dp[4] = max(-inf,2) =2. So dp: idx0:0, idx1:1, idx3:1, idx4:2.
Element 2: values ≤2: values 0,1,2. best = max(dp[0]=0, dp[1]=1, dp[2]? -inf) = 1. candidate=2. new_dp: update dp[2] = max(-inf,2) =2. Also we could also consider taking 2 after state 2? But dp[2] initially -inf, but after we might have taken 2 earlier? Not yet. Also we could take 2 after state 0,1? Already considered. So dp final: idx0:0, idx1:1, idx2:2, idx3:1, idx4:2.
Thus A[0][0]=0, A[0][1]=1, A[0][2]=2, A[0][3]=1, A[0][4]=2.
But wait, is it possible to get a subsequence of length 2 ending with 2? Let's check: start with 0, we can take 1 (value 1) then 2 (value 2) => length 2, ending with 2. Indeed that's valid: positions: 1 (value 3) can't because 3>0? Actually sequence: a = [3,1,4,2]. Starting with 0, we can skip 3 (since we can pick it? 3≥0, we could pick 3 but then we may not get longer? Let's see: pick 3 then? Next 1 is less than 3, can't pick. Then 4 can be picked after 3, giving length 2 ending with 4. That's A[0][4]=2 (pick 3 and 4). Alternatively, pick 1 then 2 gives length 2 ending with 2. So A[0][2]=2. Also pick 1 then 4 gives length 2 ending with 4, but we have A[0][4]=2 as well. Pick 3 then 4 gives 2 ending with 4. So okay.
Now compute A for start v=1 (value 1). Starting dp: dp[idx1]=0.
Process elements:
Element 3: values ≤3? 1 ≤3, also maybe 0? But 0 not in state because start state is 1; we have only dp[1]=0. So best = dp[1]=0 => candidate=1 for value 3. So dp[3]=1. Also skip: keep dp[1]=0. So after first: dp[1]=0, dp[3]=1.
Element 1: values ≤1: only value 1? value 1 ≤1, dp[1]=0 => best=0, candidate=1 for value1. So dp[1] becomes max(0,1)=1? Wait careful: We copy old dp to new_dp. new_dp initially copy: dp[1]=0, dp[3]=1. Then for element 1, best=0, candidate=1. So we update new_dp[idx1] = max(existing 0, 1) = 1. So now dp[1]=1, dp[3]=1. This means we can take 1 after having state 1? But we already had state 1 with count 0 (meaning no picks yet but last value 1). Taking 1 gives new state 1 with count 1, which is valid: we pick the element 1, which is equal to current last value 1, so it's allowed, increasing count by 1. So now we have a subsequence of length 1 ending with 1.
Element 4: values ≤4: best = max(dp[1]=1, dp[3]=1, dp[?]) = 1. candidate=2 for value4. So new dp[4] = 2. Also keep others. So dp: 1:1, 3:1, 4:2.
Element 2: values ≤2: values 1 and 2? dp[1]=1, dp[2]? -inf, so best=1. candidate=2 for value2. So dp[2] = 2. Also we might consider taking 2 after state 1? Yes. So final dp: idx1:1, idx2:2, idx3:1, idx4:2. Also note dp[1] = 1 (from taking the 1) and also dp[1] could be 0 from skipping? But we overwritten? Actually after processing all, we kept the copy, so dp[1] is max of skip and take? The skip kept the previous value which was 1 from after element 1? Let's recount: After element 3, dp had [1:0,3:1]. After element 1, we updated dp[1] to 1, so dp became [1:1,3:1]. After element 4, we added dp[4]=2, keep others: [1:1,3:1,4:2]. After element 2, we add dp[2]=2, keep others: [1:1,2:2,3:1,4:2]. So A[1][1]=1, A[1][2]=2, A[1][3]=1, A[1][4]=2. Also A[1][?] For state 0? Not reachable. Also A[1][1] includes skipping all? That would be count 0, but we have count 1 which is better. However, we need to also include the option of skipping all, which would give count 0 ending at 1. But our DP initial dp[1]=0 and we never increased it except by taking. But the skip option is always preserved because we copy old dp each step, so at the end dp[1] still includes the initial 0? Actually after first element, we had dp[1]=0 from skip? Let's simulate correctly:
Initialize dp: all -inf, dp[1]=0.
Element 3:
- new_dp = dp (copy): dp[1]=0, others -inf.
- best = max over y≤3: dp[1]=0 => candidate=1.
- update new_dp[3] = max(-inf,1)=1.
So after element 3: dp[1]=0, dp[3]=1.
Element 1:
- new_dp = dp copy: dp[1]=0, dp[3]=1.
- best over y≤1: only y=1, dp[1]=0 => candidate=1.
- update new_dp[1] = max(0,1) = 1.
So after element 1: dp[1]=1, dp[3]=1. Note that dp[1] now is 1, overwriting the 0. So the 0 is lost because we didn't keep a separate state for "no picks yet"? But we have state representing last value 1 with count 0 (i.e., we haven't taken any, last value is 1). After we take an element 1, we get state 1 with count 1. But we also want to keep the possibility of not taking any element in the block, which would end with state 1 and count 0. However, the DP we defined should allow skipping all elements, resulting in same state as start with count 0. But after processing all elements, we want to consider both possibilities: taking some elements or taking none. In our DP, we start with dp[1]=0 representing the "no picks yet" state. As we process elements, we update dp values. But we never explicitly preserve the option of "skip all" if we later take some element and overwrite dp[1]? Actually, the "skip all" option corresponds to the path where we never take any element, which would keep dp[1]=0 throughout. In our update, at each step, we set new_dp = old dp (skip). This preserves the previous dp values. So after first element, we have dp[1]=0 from skip, dp[3]=1 from take. After second element, we set new_dp = old dp, so we start with dp[1]=0, dp[3]=1. Then we compute best and update new_dp[1] = max(0,1)=1. So after that, dp[1] becomes 1 (from taking the element). The path corresponding to skipping the second element while also having not taken any earlier? But we had dp[1]=0 from skipping first element and not taking it. That path is still present in new_dp[1] before update? Actually new_dp is a copy of old dp, so it includes dp[1]=0. Then we update new_dp[1] to max(0,1)=1. So the value 0 is overwritten by 1. But the path that skipped the second element (and all previous) still results in state 1 with count 0. However, after we process the second element, the state "no picks" still exists: because we haven't taken any elements up