Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.
This problem is similar to a standard problem but it has a different format and constraints.
In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.
But in this problem you are given n small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.
For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.
Can you help Mostafa solve this problem?
Input
The first line contains two integers n and m, n is the number of the small arrays (1 ≤ n ≤ 50), and m is the number of indexes in the big array (1 ≤ m ≤ 250000). Then follow n lines, the i-th line starts with one integer l which is the size of the i-th array (1 ≤ l ≤ 5000), followed by l integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains m integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to n.
The small arrays are numbered from 1 to n in the same order as given in the input. Some of the given small arrays may not be used in big array.
Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded.
Output
Print one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty.
Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).
We need to find maximum sum of contiguous subarray in a big array formed by concatenating given small arrays (each has length up to 5000, but total concatenated array can be huge, m up to 250k small arrays, each small array length up to 5000 so total elements could be up to 1.25e9, too large). So we need an efficient method that avoids constructing the whole array.
We are given n small arrays, each of length l_i and their elements a_{i,1..l_i}. The big array is a sequence of m indices (1-indexed) i_1, i_2, ..., i_m. The actual big array B is concatenation A[i_1] + A[i_2] + ... + A[i_m], each A[i] is an array. We need max subarray sum in B.
We can treat each small array as a segment with known properties: total sum, maximum prefix sum, maximum suffix sum, and maximum subarray sum within the segment. Then we need to combine these segments in order, but not all segments are identical; they may appear many times with the same index, but since there are only n distinct small arrays, we can precompute these properties for each small array.
But m can be large (250k), but n is small (<=50). So we can process the sequence of indices and maintain a running "combined" state similar to Kadane's algorithm but over segments. Usually to compute max subarray sum for an array, you can do: cur = max(a, cur + a) for each element. For segments, we could treat each segment as a "macro-element" with certain transformation on the current best sum. However, because each segment is an array, we need to apply the internal structure.
We can think of the problem as: We have a list of blocks (segments) B1, B2, ..., Bm, where each block is an array. We need to compute overall max subarray sum. This can be done by scanning blocks sequentially and maintaining:
best: overall maximum sum so far (candidate answer)
cur: maximum sum of a subarray that ends at the current position (i.e., at the end of the last processed block). But when we finish a block, cur can be either entirely within the block, or span across previous blocks and possibly include the whole block or part of it.
In typical Kadane's algorithm, as we iterate elements, we update cur = max(current_element, cur + current_element). For a block, we need to process its elements one by one. However, we cannot afford to iterate through all elements of all blocks because total elements could be huge. But we can treat the block's effect on cur and best in a compact way if we know certain properties of the block and the incoming cur (which is the maximum sum ending at the end of previous block). Specifically, given cur (the best suffix sum up to the end of previous block), after processing block A (length L, values), what will be the new cur (best sum ending at the end of this block) and updated best? This is similar to "function composition" where the block acts as a transformation on the pair (cur, best). But careful: best is global, but cur interacts with block.
If we think about processing block A:
We have a starting cur_in (which is the maximum sum of a subarray that ends exactly at the end of previous block; can be negative? Usually we allow negative, but the recurrence cur = max(x, cur + x) ensures cur is at least the current element, which may be negative. So cur could be negative if all numbers are negative; but the answer must be at least one element, so we may keep negative cur if all are negative. But it's easier to allow cur to be any value, representing the best sum ending at the previous position.
Now we process the block's elements sequentially. For each element x in A, we update:
cur = max(x, cur + x)
best = max(best, cur)
If we apply this for all elements, we get new cur_out and new best_out.
Given cur_in (before block), we can compute cur_out and best_out as functions of cur_in. Since the block is fixed, the mapping from cur_in to (cur_out, best_out) can be precomputed for each block. However, cur_in is a real number (could be any integer). The function may be piecewise linear? Actually it's a composition of many operations of the form f(x) = max(ai, x+ai). The composition of such functions is known to be of the form f(x) = max(alpha, x + beta) for some constants alpha and beta? Let's check: For a single element a, transformation on cur: cur_out = max(a, cur_in + a) = a + max(0, cur_in). That's not linear but is piecewise: if cur_in >= 0, cur_out = cur_in + a; else cur_out = a. That's of the form cur_out = max(a, cur_in + a). For two elements a1, a2, we can compose: after first: cur1 = max(a1, cur_in + a1). Then second: cur2 = max(a2, cur1 + a2). So cur2 = max(a2, max(a1, cur_in + a1) + a2). This expands to cur2 = max(a2, a1 + a2, cur_in + a1 + a2). More generally, after processing a sequence of numbers, cur_out = max( max_suffix sums? Actually it's known that the effect of a segment on the Kadane state can be captured by three values: total sum of the segment, maximum prefix sum, and maximum suffix sum, but also maybe the maximum subarray sum inside? Let's derive formally.
We want to compute cur_out given cur_in, and also track best which is the maximum of cur values observed during the block plus possibly previous best. best_out = max(best_in, something), where something is the maximum cur achieved during processing of the block, which could be an internal maximum or cur_in + something.
This is reminiscent of "Kadane with segments" where we can treat each block as having:
total sum S
maximum prefix sum P (starting from leftmost)
maximum suffix sum Suf (ending at rightmost)
maximum subarray sum inside M (internal).
But these alone are not enough to combine with an incoming cur_in? Actually, if we want to combine two blocks (previous concatenated blocks as one, and new block), we can compute overall properties: For concatenation of two blocks X and Y, we know:
Total sum = S_X + S_Y.
Max prefix = max(P_X, S_X + P_Y)
Max suffix = max(Suf_Y, Suf_X + S_Y)
Max subarray = max(M_X, M_Y, Suf_X + P_Y)
That is for computing the overall maximum subarray sum of the whole array if we treat blocks as atomic with these four values. But this works only if we want the overall maximum subarray sum for the whole array as a single number. However, we need to process a long chain of blocks sequentially, and we can compute the aggregate block for the prefix up to current point, using the combine operation. Since we have m up to 250k, and n is small, we can combine the blocks one by one using the four-value representation: each block has (sum, pref, suf, max). Then we start with identity? Actually we need to build the aggregate for the entire list of blocks, but note that the max subarray sum for the entire array is exactly the max field of the aggregate after combining all blocks. However, careful: The aggregate combine operation defined above (for two blocks) yields a block representing the concatenated array, with the four metrics computed correctly. So if we have a list of blocks, we can reduce them by combining left to right to get a single block representing the whole big array, then output its max. This would give us the answer. And this operation is associative. So we can compute:
For each small array i, precompute (sum_i, pref_i, suf_i, max_i) from its elements.
Then for each index in the big array sequence, we have a block (the small array's properties). Combine them sequentially using the combine operation to get overall (sum_total, pref_total, suf_total, max_total). Then answer is max_total.
But is that correct? Let's check: The combine rule for two blocks A and B (A first then B) to form C = A+B is:
Yes, that's standard for maximum subarray sum using divide and conquer. This yields the maximum sum of any contiguous subarray within the concatenated array. So if we combine all blocks in order, we get the global max. So this seems straightforward.
Complexity: O(m) combinations, each combination is O(1) arithmetic operations. m up to 250k, which is fine. n up to 50, but we precompute each small array's properties in O(total length of all small arrays). The total length of all small arrays is sum of l_i, which could be up to n * 5000 = 250k (since n <= 50, max total is 250k). Actually worst-case: each l_i up to 5000, n=50 => sum up to 250,000. That's acceptable. So the overall solution is simple.
But wait: There is a catch: The values can be negative, and the answer must be at least one element, so max may be negative if all elements are negative. The combine formulas still work, because for a single block we compute max (which may be negative). For pref, we need to compute maximum prefix sum: if all elements are negative, the maximum prefix is the least negative (i.e., the maximum of the prefix sums, which are cumulative sums). Similarly for suffix and max. So formulas hold.
Therefore the solution is:
Read n, m.
For i from 1 to n: read l, then l integers. Compute:
sum_i = sum of all elements.
pref_i: maximum over prefix sums (starting from first). Initialize cur_pref = 0, best_pref = -inf; after each element add value, best_pref = max(best_pref, cur_pref) but careful: prefix sum from first element includes at least first element? Usually prefix sum of first k elements, with k>=1. We can compute: running sum = 0; max_pref = -inf; for each x in array: running_sum += x; max_pref = max(max_pref, running_sum). That gives the maximum sum of a prefix (including possibly empty? Starting from empty prefix sum =0? In maximum subarray context, we need at least one element for pref and suf? Actually for combine formulas, when we combine two blocks, we need A.pref to be the maximum sum of a contiguous subarray that starts at the leftmost element of A (i.e., prefix of A). This subarray must be non-empty because we must choose at least one element. So pref_i should be the maximum over all prefixes of A (length >=1). Similarly suf_i is maximum over suffixes (length >=1). And max_i is maximum subarray within A (non-empty). So we need to ensure we don't consider empty prefix. Using running sum and taking max after adding each x ensures that we consider prefixes that end at each position, which are non-empty. Also need to handle negative values: if all are negative, the max prefix is the least negative (i.e., the maximum of the individual elements?). Actually prefix sums are cumulative, the maximum might be the first element if later become more negative? Example: [-5, -2]. Prefix sums: -5, -7. Maximum is -5. So that's fine. If we allowed empty prefix sum 0, then max would be 0 (if 0 > all negatives), but that would be incorrect for our formulas because the subarray must be non-empty. So we must not include empty prefix. So initialize max_pref to the first element's prefix sum? We can set max_pref = -inf and after each x update running sum and then max_pref = max(max_pref, running_sum). This works because after first element, running_sum is the sum of first element, which is considered.
Similarly, for suffix: we can compute by scanning from right: running_suf = 0; max_suf = -inf; for each x from right to left: running_suf += x; max_suf = max(max_suf, running_suf).
For max_i: we can compute Kadane: cur = 0? Actually we need at least one element, so Kadane with initialization cur = -inf? Standard: max_ending_here = max_so_far = first element? Alternatively use typical: cur = 0, best = -inf; for each x: cur = max(x, cur + x); best = max(best, cur). This works even if all negative: cur will be the current element each time, and best will be the maximum element. So we can compute that.
Also compute sum_i.
Then read the m indices (big array). We'll maintain an aggregate block (sum, pref, suf, max) initialized to the first block's properties? Actually we can start with identity? There's no identity because the combine operation expects non-empty blocks? But we can start with the first block's properties and then for each subsequent index, combine current aggregate with the next block: aggregate = combine(aggregate, block_i). However careful: The combine operation defined for two non-empty blocks yields correct overall properties. So we can set aggregate = block for first index. Then for i from 2 to m: aggregate = combine(aggregate, block[index_i]).
But we need to ensure that the combine operation is associative, which it is. So this yields final aggregate of the whole big array.
Edge cases: m = 1 => answer is max of that small array.
Now check with example: small arrays: A1: [1,6,-2]; A2: [3,3]; A3: [-5,1]. Compute:
A1: sum=5, pref: max prefix sums: 1, 7, 5 => max=7? Actually prefix sums: 1, 7, 5 -> max = 7. suf: max suffix sums: from right: -2? Actually compute: suffixes: [-2] sum -2; [6,-2] sum 4; [1,6,-2] sum 5 -> max = 5? Wait suffix includes last element; so max suffix sum is max of [-2], [6,-2], [1,6,-2] => max is 5 (sum of all) because 5 > 4 > -2. So suf1 = 5. max: maximum subarray: likely 7 (1+6). So max1 = 7.
A3: [-5,1]: sum=-4, pref: prefix sums: -5, -4 => max = -4? Actually -4 > -5, so max = -4. But note that prefix must be non-empty; the max prefix sum is -4 (sum of both). However, is it allowed to take both elements? Yes, it's a contiguous subarray starting at first element. So pref3 = -4. suf: suffixes: [1] sum 1; [-5,1] sum -4 => max = 1. max: max subarray? Possibly 1 (just the last element) => max3 = 1.
Now big array indices: [2,3,1,3]. Process:
Start with block2: (6,6,6,6). Combine with block3: A= (6,6,6,6) and B=(-4, -4, 1, 1). Compute:
Combine with block1: A=(2,6,2,6), B=(5,7,5,7)?? Wait A1 sum=5, pref=7, suf=5, max=7. But careful: In earlier compute, A1 sum=5? 1+6-2=5. yes. Actually sum1=5. pref1=7, suf1=5, max1=7.
Now combine:
sum = 2+5 = 7.
pref = max(A.pref=6, A.sum=2 + B.pref=7 => 9) = 9.
suf = max(B.suf=5, A.suf=2 + B.sum=5 => 7) = 7.
max = max(A.max=6, B.max=7, A.suf=2 + B.pref=7 => 9) = 9.
So max becomes 9.
Combine with block3 again: A=(7,9,7,9) from previous? Actually after three blocks we have (7,9,7,9) (I computed sum=7, pref=9, suf=7, max=9). Now combine with B=block3: (-4, -4, 1, 1).
But is there any nuance? The total number of blocks m is 250k, which is fine. However, each combine involves arithmetic on 64-bit integers because sums can be large: each element up to 1000 in absolute, length of each small array up to 5000, sum per small array up to 5e6 in absolute. Number of blocks up to 250k, total sum up to about 1.25e12, fits in 64-bit signed (2^63-1 ~9e18). So we need 64-bit integers (long long). So use long long.
Now we need to be careful: For each small array we compute pref, suf, max. We must compute them correctly, especially for negative values. Use typical approach:
pref: max prefix sum (non-empty). Compute: running = 0; best = -inf. For each x: running += x; if (running > best) best = running. However, if we start best = -inf and running starts at 0, after first addition best becomes first element. This is fine. Similarly for suffix: running = 0; best = -inf; iterate from end: running += a[j]; if (running > best) best = running.
max: cur = 0? Actually typical Kadane that allows negative numbers and requires non-empty subarray: Initialize cur = 0, best = -inf; then for each x: cur = max(x, cur + x); best = max(best, cur). If all negative, cur will become the current x each step (since max(x, cur + x) with cur negative might yield something, but cur + x might be less than x? Actually if cur is negative, cur + x might be < x? For negative numbers: e.g., cur = -5, x = -3: cur + x = -8, max(-3, -8) = -3, so cur becomes -3. So after each step, cur is the maximum sum ending at current element (which is at least the element itself). At the end, best will be the maximum element (if all negative) or higher sum. So that works.
But there is also a nuance: If we use Kadane with cur starting at -inf? That's not needed.
Now, does the combine formula require pref and suf to be the maximum sum starting/ending at the boundary, with the subarray allowed to be the whole block? Yes, we computed as described.
Thus the solution is straightforward.
But the problem statement mentions: "The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array." They also say the array is very big, you cannot build it. So our approach is valid.
However, need to consider that small arrays lengths can be up to 5000, and n up to 50, so sum of lengths is at most 250k, which is acceptable to read and compute properties.
We need to read m indices; m up to 250k, that's fine. So overall time O(total small array length + m). Memory: store properties for n small arrays; store m indices as we read them sequentially, but we don't need to store them all; we can process on the fly: read the first index, set aggregate to that block's properties, then for each subsequent index read, combine with its block.
We must read the last line containing m integers. Since m can be large, we need efficient input. Use scanf or fast I/O.
Now the output is the max field of the final aggregate.
Potential pitfalls:
Ensure that we compute pref, suf, max correctly for each small array, especially when all negative.
For combine: We need to compute new pref = max(A.pref, A.sum + B.pref). But is this always correct for non-empty prefixes? Consider when B.pref is negative and A.sum is positive, A.sum+B.pref might be less than A.pref. That's fine. However, is it possible that the maximum prefix of the concatenated array is a prefix that includes all of A and part of B, but the part of B taken is not a prefix of B? Actually by definition, prefix of concatenated array is some number of elements from the start. If it includes B, it must include the entire A plus some prefix of B. So the best prefix sum is either best within A (which is A.pref) or entire A plus the best prefix of B (A.sum + B.pref). Because B.pref is the best sum of a non-empty prefix of B, but what if taking no elements from B yields a larger prefix? That's covered by A.pref. If we take some but not all of B's prefix, the sum is A.sum + (some prefix sum of B). The maximum of those is A.sum + B.pref because B.pref is the maximum over all non-empty prefixes of B. But is it allowed to take an empty prefix of B? That would be just A entirely, which sum is A.sum, but is A.sum considered as a prefix? Actually the prefix of concatenated array that ends exactly at the end of A is A itself; its sum is A.sum. However, A.pref is the maximum sum of any prefix of A, not necessarily A.sum (unless A.sum is the maximum prefix). But A.sum may be less than A.pref if A.pref occurs earlier. So the prefix sum for whole A is A.sum, but it's not necessarily the maximum prefix of A. However, when considering prefixes that extend into B, we need to consider the sum of all of A plus a prefix of B. The maximum of such sums is A.sum + B.pref if B.pref >? But is there a case where the best prefix of concatenated array is A.sum + something less than B.pref? No, because B.pref is the maximum prefix sum of B; adding A.sum to it yields the maximum sum among A.sum + (prefix sum of B). However, what about prefix that includes all of A and none of B? That's A.sum; but A.sum may be greater than A.pref? Actually A.pref is the max prefix sum of A, which could be less than A.sum if later elements are negative? Wait, consider A = [5, -10]. A.sum = -5. A.pref = max(5, -5) = 5. So the prefix that ends at the end of A has sum -5, which is less than A.pref. So the maximum prefix of the concatenated array might be the prefix that ends within A (i.e., A.pref) or if we go into B, we have A.sum + B.pref. But is it possible that A.sum + B.pref is greater than A.pref even if B.pref is negative? e.g., A.pref = 5, A.sum = -5, B.pref = -2 => A.sum+B.pref = -7, less than 5. So fine. So the formula works.
Now for suffix: similar.
For max: max( A.max, B.max, A.suf + B.pref ). This covers subarrays that cross the boundary.
Thus we are good.
Implementation steps:
Parse input.
For i in 1..n:
read l_i.
allocate vector of ints or just process on the fly.
compute sum_i, pref_i, suf_i, max_i.
To compute suf_i, we need to know the elements. Could store them temporarily? But we can compute all four in one pass? Not directly for suffix because we need to traverse from right. Options:
read the elements into a temporary vector of length l_i, then compute sum, pref, max, and then compute suffix by scanning from right.
Or we can compute sum, pref, max in first pass, and also compute suffix using a second pass after storing. Since total elements are at most 250k, storing temporarily per array is fine. We can read into a vector (or list) of length l_i, compute sum, pref, max (Kadane) while reading, then after reading all, compute suffix by reverse scan. That's okay. Even simpler: we can compute suffix without storing by using a trick? Possibly not; but storing is fine given limits.
For each small array, we'll create a struct with fields: sum (long long), pref (long long), suf (long long), max (long long). We'll store in array blockProps[n+1] (1-indexed).
Then read the m indices. Since indices are 1-based, we can store them as integers.
Approach: read first index idx; set aggregate = blockProps[idx]; then for i=2..m: read idx, aggregate = combine(aggregate, blockProps[idx]); after loop, output aggregate.max.
But we must be careful: The combine operation we defined works for two blocks representing non-empty arrays. So starting with first block is fine.
But we need to consider that m could be 0? But constraints say m >= 1. So fine.
Now check for negative values: Suppose all elements negative. The answer should be the maximum (least negative) element. Our method should produce that. For a single block with all negatives, max = maximum element. For multiple blocks, if all are negative, the overall max should be the maximum among all block max values, because any cross-boundary sum would be even more negative (sum of two negatives). The formula max( A.max, B.max, A.suf + B.pref ) would pick the max among those. Since A.suf and B.pref are the best suffix/prefix (which are the least negative in each block, possibly single elements), their sum is more negative than either individually because negative + negative < each (since both negative). So the max will be max(A.max, B.max). So works.
So m=1, only index 1. So answer should be max subarray sum in small array 1. Compute small array 1: length 4, values 0 8 -3 -10. sum = -5? Actually 0+8-3-10 = -5. pref: prefix sums: 0, 8, 5, -5 => max=8. suf: suffix sums: -10, -13? Let's compute: from right: -10, -3-10=-13, 8-3-10=-5, 0+8-3-10=-5? Actually suffixes: last element -10 sum -10; last two -3-10 = -13; last three 8-3-10 = -5; all four = -5. So max suffix = -5? Wait -5 > -10, > -13, so max = -5? But the maximum element maybe? The suffix max should be the maximum sum of a suffix (non-empty). The suffix could be just the last element -10, or the last two -13, or last three -5, or all four -5. So best is -5. However, we might also consider suffix of length 1 of element 8? That's not a suffix because suffix must end at last element, so it includes the last element. So max suffix = -5? But check typical Kadane: The maximum subarray sum is 8 (0+8? Actually 8 alone or 0+8 yields 8). So max=8. So answer 8. That matches sample output 8. So our method for a single block yields max=8. So output 8.
Now sample2 output is 8, matches.
Thus the solution is straightforward.
But we must consider potential overflow? Use long long (64-bit). The sums can be up to 250k * 5e6? Actually worst-case: each small array sum up to 5e6 (if all 1000 and length 5000 gives sum=5e6). m=250k, total sum up to 1.25e12. So within 2^63.
Now implement.
Implementation details:
Define struct Block { long long sum, pref, suf, best; } maybe use best for max.
read l, then vector arr(l); read l integers. While reading, compute sum, pref, and Kadane max.
For sum: accumulate.
For pref: maintain running = 0; pref = -inf (maybe LLONG_MIN). For each x: running += x; if running > pref) pref = running.
For Kadane: cur = 0? Actually we need to compute max ending here and overall best. As described: cur = 0; best_in = -inf; for each x: cur = max(x, cur + x); best_in = max(best_in, cur). This works even if all negative: cur will be set to x if cur + x < x, which for negative cur (starting cur=0) first x negative: cur = max(x, 0 + x) = max(x, x) = x; best_in = max(-inf, x) = x. So after all, best_in is max element. For positive values, works.
But careful: if we start cur = 0, for first element x (negative), cur = max(x, 0+x) = x (since 0+x = x), okay. For positive, cur = max(x, x) = x, then later positive, cur will increase.
Alternative: set cur = -inf, but not needed.
For suffix: after reading all elements, we can compute suf by scanning from right: running = 0; suf = -inf; for i from l-1 down to 0: running += arr[i]; if running > suf) suf = running.
Store block.
For the big array indices: We'll read the line of m integers. Since m up to 250k, using scanf in loop is fine. But careful: the indices may be on a single line but can be many, we just read sequentially.
We'll read the first integer (idx1). Set result = blockProps[idx1]. Then for i=2..m: read idx; result = combine(result, blockProps[idx]).
Finally, print result.best.
But is there any case where using combine sequentially yields the same as combining all blocks? Yes, because combine is associative.
Now let's test with some edge cases:
Single block: result = blockProps[idx1] -> best is correct.
Two blocks both negative: e.g., A = [-5], B = [-3]. A: sum=-5, pref=-5, suf=-5, best=-5. B: sum=-3, pref=-3, suf=-3, best=-3. combine: sum=-8, pref=max(-5, -5+(-3)=-8) => -5, suf=max(-3, -5+(-3)=-8?) Actually A.suf=-5 + B.sum=-3 = -8, vs B.suf=-3 => max(-3, -8) = -3, best = max(-5, -3, -5+(-3)=-8) = -3. So overall best = -3 (the higher element), correct.
Mix positive and negative: Works.
Now we need to ensure the reading of indices is correct. The last line contains m integers. It's possible there are multiple lines? The description says "The last line contains m integers" but often they may be split across lines for large m. Safer to just read m integers using a loop with scanf, ignoring line breaks.
Now constraints: n up to 50, l up to 5000, total small array elements <= 250k (50*5000). So storing all small arrays temporarily is fine.
Potential pitfall: For the combine, we need to use long long for all operations. Use max function with initializer list.
Now the answer is the best field.
But we should also consider if there is any scenario where the maximum subarray sum might be larger than any individual block's max but less than sum of some prefix+suffix? Already covered.
Thus solution is O(total small array size + m).
But wait: The problem statement says: "The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array." So indeed we combine in that order.
Now, is there any trick about multiple instances? No, each time we just use the block properties.
Now think about the potential of using divide-and-conquer or segment tree if we need to answer many queries, but here we just need one answer for the whole sequence.
Thus final answer.
But we need to output a single number. For C++, use cout with long long.
For each i 1..n:
int l; cin >> l;
vector arr(l);
ll sum = 0;
ll pref = LLONG_MIN;
ll running = 0;
ll cur = 0; // for Kadane cur
ll best = LLONG_MIN;
// Actually for Kadane we need cur and best. But we can compute Kadane using the typical method.
// I'll compute sum and pref and Kadane in one pass.
// For suffix later need arr, so store arr.
for (int j=0; j<l; j++) {
int x; scanf("%d", &x); // or cin
arr[j] = x;
sum += x;
running += x;
if (running > pref) pref = running;
// Kadane:
if (j == 0) cur = x;
else cur = max((ll)x, cur + x);
// Actually we can compute cur properly: cur = max(x, cur + x) for each step, starting with cur = x for first? Actually can start cur=0 and then inside loop do cur = max(x, cur + x); best = max(best, cur); But if we start cur=0, for first element x: cur = max(x, 0+x) = x; best = max(best, x) works.
// So simpler: at beginning cur=0, best = -inf; then for each x: cur = max(x, cur + x); best = max(best, cur);
// We'll compute after reading all? Actually we can compute on the fly.
}
But we need to compute best (max subarray) on the fly as well. So we'll use that.
Let's restructure:
For each small array:
read l.
vector arr(l);
ll sum=0, pref=LLONG_MIN, suf, best=LLONG_MIN;
ll running_pref=0;
ll kadane_cur=0, kadane_best=LLONG_MIN; // but kadane_cur=0 works.
for j=0; j<l; j++) {
int x; scanf("%d",&x);
arr[j]=x;
sum += x;
running_pref += x;
if (running_pref > pref) pref = running_pref;
// kadane:
if (kadane_cur <= 0) kadane_cur = x;
else kadane_cur = kadane_cur + x;
// Actually standard: cur = max(x, cur+x)
// So we can do:
// cur = max(x, cur + x);
// But using if is fine.
// Let's use:
kadane_cur = max((ll)x, kadane_cur + x);
if (kadane_cur > kadane_best) kadane_best = kadane_cur;
}
best = kadane_best;
// Now compute suffix:
ll running_suf = 0;
suf = LLONG_MIN;
for (int j=l-1; j>=0; j--) {
running_suf += arr[j];
if (running_suf > suf) suf = running_suf;
}
blockProps[i] = {sum, pref, suf, best};
But careful: pref computed as max over prefix sums. For a non-empty prefix, we start running_pref = 0 then add each x; after first addition, running_pref becomes x. So pref will be at least x. That's correct.
However, if all elements negative, pref will be the maximum prefix sum, which is the least negative. That's fine.
For suffix similarly.
Now reading indices:
int first; scanf("%d", &first);
Block res = blockProps[first];
for (int i=1; i<m; i++) {
int idx; scanf("%d", &idx);
res = combine(res, blockProps[idx]);
}
printf("%lld\n", res.best); // but careful: on Windows, maybe %I64d; but we can use cout.
Use cout for safety.
Now check with sample:
Input:
3 4
3 1 6 -2
2 3 3
2 -5 1
2 3 1 3
We compute blockProps as above, combine, get 9.
Now, what if the small arrays are huge? l up to 5000, but only 50 arrays, total up to 250k elements, which is fine.
Now memory: blockProps size 51, each store 4 long longs. Indices read sequentially, no storage needed. So memory usage low.
Now we must be cautious with integer overflow in intermediate calculations? Use long long, and all sums are within 64-bit.
But there is a nuance: The combine formulas use a.suf + b.pref. a.suf and b.pref could be as large as about 5e6 (max sum of a block) if all positives. So sum up to 1e7, fine.
Now what about the running prefix sum for pref? For large l up to 5000, sum could be up to 5e6, fits in long long.
Now is there any tricky part where the Kadane algorithm using cur=0 might cause overflow? No.
Now time complexity: O(total small array length + m). total small array length <= 250k, m <= 250k => total operations ~500k, very fast.
But wait: total small array length could be up to 50 * 5000 = 250k, that's fine. However, the problem might allow n=50, each l=5000 => 250k. Plus m=250k => total ~500k. That's trivial.
But hold on: The constraints say l ≤ 5000, n ≤ 50, so total small array elements ≤ 250,000. And m ≤ 250,000. So total input numbers is at most 250k (small array elements) + 250k (indices) + some small numbers = about 500k numbers. That's not huge. So reading with scanf is fine.
But the problem statement says "Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded." That's because the big array could be up to 250k blocks * average length (maybe 2500) = up to 625 million elements, which is indeed huge. But our method avoids that.
Thus solution is correct.
But is there any pitfall where the block's pref, suf, max might be incorrectly computed if we use the same running_pref for pref and also for sum? No.
Now check for empty block: No, l ≥ 1, so each block is non-empty.
Now what about indexing: We used 1-indexed for blocks.
Now we might consider using faster I/O: std::ios::sync_with_stdio(false); cin.tie(0); but then using cin for integers might be okay for 500k numbers. But to be safe, we can use scanf.
Now produce final code.
But before finalizing, let's double-check the combine formulas for correctness in all cases, especially when best is derived from a.suf + b.pref, but best might also be from a.pref or b.suf? The formula we used: overall max = max( a.max, b.max, a.suf + b.pref ). That is standard for two concatenated arrays. Is there any scenario where the overall max could be a combination that includes part of a and part of b but not necessarily aligning with a.suf and b.pref? For any crossing subarray, it consists of a suffix of A and a prefix of B. The maximum sum of such a crossing subarray is the maximum over suffixes of A and prefixes of B of (suffix_sum_A + prefix_sum_B). Since suffix_sum_A is maximized by a.suf (maximum suffix sum of A), and prefix_sum_B is maximized by b.pref (maximum prefix sum of B), then the maximum of the sum is a.suf + b.pref if both are chosen independently? But careful: The suffix and prefix are independent; we can choose the best suffix of A (which may be the whole array) and the best prefix of B (which may be the whole array). However, is it always true that the best crossing subarray is the concatenation of the best suffix of A and the best prefix of B? Not always, because the best suffix of A and best prefix of B might overlap in some sense? They are separate blocks; we can choose any suffix of A and any prefix of B. The sum of a particular suffix and prefix is simply suffix_sum + prefix_sum. Since the sum is additive and the suffix and prefix are independent, the maximum possible sum is indeed max_{suffix of A} suffix_sum + max_{prefix of B} prefix_sum, because both terms are independent and non-negative? Wait, but suffix_sum could be negative, and prefix_sum could be negative. If both are negative, then picking the largest (least negative) suffix and largest prefix might not give the maximum of their sum because you could pick a less negative suffix and a more negative prefix? Actually we need to maximize S = s + p, where s is any suffix sum of A, p is any prefix sum of B. Since s and p are independent variables, the maximum of s+p is (max_s s) + (max_p p). Because for any s and p, s+p <= max_s s + max_p p if both max_s and max_p are the maximum values? But if max_s is negative and max_p is negative, then s+p could be less than max_s + max_p? Actually if s <= max_s and p <= max_p, then s+p <= max_s + max_p. So the sum of the maxima is an upper bound, and it's achievable by taking the specific suffix achieving max_s and the specific prefix achieving max_p. So yes, the crossing max is a.suf + b.pref. So formula holds.
One subtlety: a.suf is maximum sum of a suffix of A (non-empty), b.pref is maximum sum of a prefix of B (non-empty). This yields a valid crossing subarray that includes at least the last element of A and the first element of B? Actually the suffix must end at the last element of A, and the prefix must start at the first element of B. So indeed the concatenation of a specific suffix (which ends at the end of A) and a specific prefix (which starts at the start of B) yields a contiguous subarray that spans the boundary. So if we take the suffix achieving a.suf and the prefix achieving b.pref, we get a contiguous subarray. However, there is a catch: What if the best suffix of A is not the entire array? That's fine, it ends at the last element, but may start somewhere inside A. Similarly, the best prefix of B may end somewhere inside B. Their concatenation is valid.
Thus the combine formulas are correct.
Now we should also verify that we handle the case where the max subarray could be entirely within A or B or crossing.
Now check the initial combine step: Starting with first block, we have its properties. That's fine.
But is there any scenario where the maximum subarray sum could be from a segment that includes multiple blocks but not necessarily aligned with the block boundaries? The combine operation recursively builds the overall block representation, which is exact. So it's fine.
Now we are done.
But wait: There's an alternative: Could there be an issue when the small array's pref or suf are computed with non-empty subarray but the combine formulas assume that? Yes.
Thus solution is solid.
Now test with a custom case:
n=2, arrays: A1: [ -1, -2 ] => sum=-3, pref = max(-1,-3) = -1, suf = max(-2,-3) = -2? Actually suffix: last element -2, both -3 => max = -2. max = max subarray = -1 (since -1 > -2). A2: [ 3 ] => sum=3, pref=3, suf=3, max=3.
Indices: [1,2] -> big array = [-1,-2,3]. The max subarray sum is 3? Or maybe -1+ -2 +3 =0? Actually 3 is max. Let's compute combine: A=(-3,-1,-2,-1) B=(3,3,3,3) -> sum=0, pref = max(-1, -3+3=0)=0, suf = max(3, -2+3=1) = 3? Actually A.suf=-2, B.sum=3 -> sum=1, max(3,1)=3, best = max(-1,3, -2+3=1)=3. So answer 3. Correct.
What about crossing with positive: A1: [5, -10] -> sum=-5, pref=5, suf = max(-10, -5) = -5? Actually suffixes: last element -10, both -5 => max = -5? Wait: suffix sums: from right: -10, then 5-10=-5. So max = -5. max subarray =5. A2: [4] -> sum=4, pref=4, suf=4, max=4. Big array = [5,-10,4]. Max subarray could be 5 alone or 4 alone, maybe 5? But also 5-10+4=-1. So max=5. Combine: A sum=-5, pref=5, suf=-5, best=5. B sum=4, pref=4, suf=4, best=4. Combine: sum=-1, pref = max(5, -5+4=-1) =5, suf = max(4, -5+4=-1) =4, best = max(5,4, -5+4=-1) =5. So 5.
What about crossing that gives higher: A1: [2, -1, 3] sum=4, pref = max(2,1,4) = 4, suf = max(3,2,4) = 4? Actually suffixes: 3, -1+3=2, 2-1+3=4 => max=4, max subarray: could be 2-1+3=4 or just 3? max=4. A2: [5, -2, 1] sum=4, pref=5? Let's compute: A2: values 5,-2,1 => sum=4, pref: 5, 3, 4 => max=5; suf: from right: 1, -2+1=-1, 5-2+1=4 => max=4? Actually suffix sums: last:1; last two:-2+1=-1; all:4 => max=4? But also suffix of length 1 is 1, length 2 is -1, length 3 is 4. So max=4. max subarray: maybe 5? Actually compute: subarrays: 5, 5-2=3,5-2+1=4, -2, -2+1=-1, 1 -> best=5. So block2: sum=4, pref=5, suf=4, best=5. Combine: A+B => big array: [2,-1,3,5,-2,1]. max subarray could be 2-1+3+5=9? Actually 2-1+3+5 =9, then -2+1 =? 9-2+1=8, so best =9? Let's compute manually: all positives: 2-1+3+5-2+1 = 8. But maybe 3+5 =8? Actually 3+5=8. Or 2-1+3+5 =9. Yes 9. So answer 9. Combine using formulas: A: sum=4, pref=4, suf=4, best=4 (But earlier we said max subarray of A is 4, correct). B: sum=4, pref=5, suf=4, best=5. Combine: sum=8, pref = max(4, 4+5=9) =>9, suf = max(4, 4+4=8) =>8, best = max(4,5, 4+5=9) =>9. So correct.
Thus works.
Now check edge case: all negative but many blocks: works.
Now consider case where the maximum sum is from a long range that spans many blocks. Our sequential combine will eventually capture it because the combine operation essentially builds the overall block's properties, and max is computed via crossing contributions at each step. Since combine is associative, it's fine.
Now confirm that the combine operation we defined is indeed associative. That is, for blocks A, B, C, (A+B)+C = A+(B+C). This holds because the properties are derived from the array concatenation, which is associative. So we can combine sequentially.
Now one more nuance: The initial cur value in Kadane algorithm isn't needed; we are using block-level reduction.
Thus final code.
Now think about memory and time for input: Use fast reading for integers. In C++, using cin with ios::sync_with_stdio(false); cin.tie(0); is usually fast enough for 500k numbers. But to be safe, scanf.
Now I'll write final solution.
But before final, consider potential overflow in sum of pref and suf? pref and suf can be up to max prefix sum which is at most sum of all positives. But sum may be up to 5e6 per block. Multiply by many blocks (but we don't multiply; we add sums but pref and suf are computed per block and then combined; in combine, we compute a.sum + b.pref which may be up to total sum up to that point, which is at most 1.25e12, still fits in 64-bit.
Now final answer.
Now I'll produce explanation for solution: Using four-values reduction.
Now produce final code.
But also consider if the small arrays have length up to 5000, but we might want to compute suffix without storing the whole array: we could compute prefix and max and also compute suffix by scanning from right. But we need the array stored to scan from right; that's fine. Alternatively, we could compute suffix on the fly if we read into an array. We'll store in a temporary vector.
Implementation details:
For each i from 1 to n:
read l
vector arr(l);
for j=0; j<l; j++) scanf("%d", &arr[j]);
Compute sum, pref, max, suffix.
Use long long.
For pref:
ll running = 0;
ll pref = LLONG_MIN;
for (int x : arr) { running += x; if (running > pref) pref = running; }
For sum: accumulate.
For max (best):
ll cur = 0; // or better: cur = 0; but we need to allow negative? Actually cur should start as 0, but that yields correct.
ll best = LLONG_MIN;
for (int x : arr) {
cur = max((ll)x, cur + x);
if (cur > best) best = cur;
}
For suffix:
ll running = 0;
ll suf = LLONG_MIN;
for (int j = l-1; j>=0; j--) {
running += arr[j];
if (running > suf) suf = running;
}
blockProps[i] = {sum, pref, suf, best};
But careful: For pref, we might also want to consider that the maximum prefix might be the sum of all if that is highest, but that's captured.
Now about cur starting at 0: For first element x negative, cur = max(x, 0+x) = x, correct. For first element x positive, cur = max(x, 0+x) = x, correct. So it's fine.
Now we can optionally avoid storing arr by computing suffix in second pass if we store values in a temporary vector; that's fine.
But we could also compute suffix without storing by reading into an array first. Since l ≤ 5000, we can store.
Now about LLONG_MIN: include or . We'll #include <bits/stdc++.h>.
Now for output: cout << res.best << endl;
Now test with sample.
Now, there is a possible subtlety: In the combine operation, when we compute pref = max(a.pref, a.sum + b.pref). Suppose b.pref is negative, and a.sum is positive, a.sum + b.pref might be less than a.pref but possibly larger if a.pref is negative? That's fine.
Now consider case where a.pref is negative and a.sum + b.pref is also negative, and maybe b.pref is negative but a.sum is positive but not enough. Works.
Now consider case where a.pref is from a prefix that is not the whole A. That's fine.
Now one more: In the combine for suf: max(b.suf, a.suf + b.sum). This is correct.
Now final code.
But wait: The problem says "Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d)." So we can use cout.
Now I'll implement.
But we need to ensure to use long long consistently.
Now I'd like to double-check the computation of max subarray within a block using Kadane method starting cur=0. In some implementations, if all numbers are negative, cur after each step becomes x (since cur + x < x when cur is negative? Actually if cur starts 0, for first negative x, cur = max(x, 0+x) = x. Then for second negative y, cur = max(y, x + y). Since x is negative and y is negative, x+y is more negative than y (assuming both negative), so max(y, x+y) = y. So cur becomes y (the current element). So best becomes max(x, y) which is the maximum element. That's correct.
If there are zeros? Works.
Now check if cur might become 0 after some steps? For example, if we have positive and then negative that cancel to zero: cur might become 0? For instance, [2, -2]. Start cur=0? Actually: first x=2: cur = max(2, 0+2) = 2, best=2. second x=-2: cur = max(-2, 2 + -2 = 0) = 0, best remains 2. That's fine; cur can be 0, but best is 2. The max subarray is 2, not 0. So works.
Now compute suffix: After processing [2,-2], suffix sums: from right: -2, then 2+(-2)=0 => max suffix = 0? But is that correct? The maximum suffix sum (non-empty) should be the maximum of -2 and 0 = 0. But note that the suffix of length 2 has sum 0, which is greater than -2. So suf=0. That's fine.
Now pref for [2,-2]: prefix sums: 2, 0 => max pref = 2.
Now blockProps: sum=0, pref=2, suf=0, best=2. That's consistent.
Now combine two such blocks: A and B both [2,-2]. Combine: sum=0, pref = max(2, 0+2=2) = 2, suf = max(0, 0+0=0) = 0? Wait B.suf=0, A.suf=0, B.sum=0, so A.suf + B.sum = 0; max(0,0) = 0. best = max(2,2, 0+2=2) = 2. So overall max=2, but the big array would be [2,-2,2,-2]. Maximum subarray could be 2 (from first 2) or maybe 2 from third 2, or maybe 2+(-2)+2 =2? Actually compute: possible subarrays: first 2; 2-2=0; 2-2+2=2; 2-2+2-2=0; -2+2=0; -2+2-2=-2; etc. So max is 2. So correct.
Now consider [2,-1] block: sum=1, pref=2, suf = max(-1, 1) =1? Actually suffixes: -1, then 2-1=1 => max=1. best = max(2, -1, 2-1=1) = 2. So block: (1,2,1,2). Combine two: A and B same. big array: [2,-1,2,-1]. Potential max: 2-1+2=3? Let's see: subarray: first two:1; first three: 2-1+2=3; all four:2-1+2-1=2; second two: -1+2=1; second three: -1+2-1=0; etc. So max is 3. Our combine: A=(1,2,1,2), B=(1,2,1,2). Combine: sum=2, pref = max(2, 1+2=3) =>3, suf = max(1, 1+1=2) =>2? Actually B.suf=1, A.suf=1, B.sum=1 => A.suf+B.sum=1+1=2, max(1,2)=2. best = max(2,2, 1+2=3) =>3. So answer 3. Works.
Now test with negative crossing that could be better? If both a.suf and b.pref are negative, but maybe a.suf (some less negative) + b.pref (some less negative) might be less negative than each individually? Actually if both negative, sum is more negative (since negative + negative). So crossing never improves if both negative. So max will be max of individual max's.
Now all good.
Thus solution is ready.
Now we need to consider that m can be up to 250000, and we need to combine each index. This is O(m). Fine.
Now we can finalize.
One more check: In the input format, after the n lines of small arrays, the last line contains m integers. But the problem statement says "The last line contains m integers which are the indexes". However, it might be that m is large and the indices could be spread across multiple lines? The phrase "the last line" might be ambiguous; often in programming contests, the list of indices might be on one line, but for large m they may be split across lines. Safer to just read all m integers regardless of line breaks.
Thus we can read using scanf in a loop for m ints.
Now we also need to consider that the small arrays lines contain l integers plus l. So we need to parse accordingly.
Now code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 9e18; // but use LLONG_MIN from .
#define LLONG_MIN (-9223372036854775807LL - 1)
But I can use numeric_limits::min() or simply initialize with -1e18? But better to use LLONG_MIN from . Include .
But for safety, we can use -1e18 if values can't be that low: min possible sum? Each element at least -1000, l up to 5000, so min sum per block -5e6. Over m blocks up to 250k, total sum min about -1.25e12. So -1e18 is safe lower bound. But using LLONG_MIN is fine for comparisons; just ensure we don't do arithmetic with it (like add to something). In our computations, we only assign initial values and compare; we never add LLONG_MIN to something. In Kadane, cur = max(x, cur + x) where cur might be LLONG_MIN initially? We don't start cur with LLONG_MIN; we start with 0. So that's fine. For pref and suf, we start with LLONG_MIN and then compare with running sum; we never add LLONG_MIN. So it's okay.
But careful: When computing pref, we set pref = LLONG_MIN. Then running = 0; for each x: running += x; if (running > pref) pref = running. That's okay even if running can be negative; LLONG_MIN is the most negative, so first running will be greater, so pref becomes that running. So fine.
Now, for suffix similarly.
Now, for best (Kadane) we start best = LLONG_MIN; cur = 0; then for each x: cur = max((ll)x, cur + x); best = max(best, cur). That's fine.
Now about combine: we need to compute max of three values. Use std::max with initializer list or two max calls. So we can do:
Now check: a.suf + b.pref could be very low (negative) but that's okay.
Now, we need to ensure that we use long long for all.
Now implement.
But there is one more nuance: When we combine, the order is important: we are combining left to right. So we need to ensure that we are using the correct orientation. The combine function as defined (A then B) expects A to be left block, B right block. In our loop, we start with result = block of first index, then for each next index idx, we do result = combine(result, blockProps[idx]), where result is the aggregate of all previous blocks (left) and the new block is right. That's correct.
Now we need to think about potential overflow in a.sum + b.pref: a.sum could be up to about 1.25e12, b.pref up to 5e6, so sum about 1.250005e12, within 64-bit.
Now, test with maximum values to be safe: Let's create a worst-case scenario: n=1, l=5000 all 1000. block: sum=5e6, pref=5e6, suf=5e6, best=5e6. Then m=250000 all index=1. So we combine the same block 250k times. The total sum after many combines becomes 5e6 * 250k = 1.25e12. pref after many combines: For each combine, pref = max(prev_pref, prev_sum + block.pref). Since block.pref = 5e6 and prev_sum grows, after many, pref becomes something like total sum? Let's simulate: start: result = block (5e6,5e6,5e6,5e6). After second: sum=10e6, pref = max(5e6, 5e6+5e6=10e6) => 10e6, suf = max(5e6, 5e6+5e6=10e6) =>10e6, best = max(5e6,5e6,5e6+5e6=10e6)=>10e6. After third: sum=15e6, pref = max(10e6,10e6+5e6=15e6)=>15e6, etc. So eventually pref = total sum, best = total sum. That's correct because the entire array is all positive, max subarray sum is total sum. So answer = 1.25e12, fits in 64-bit.
Now check negative max: all -1000, l=5000, block sum = -5e6, pref = max prefix = -1000? Actually best prefix is -1000 (if we take just first element? But the prefix sum of first element is -1000; of first two is -2000; so max prefix is -1000). suf = -1000 (last element). best = -1000 (max element). So combine many: after two blocks, sum = -10e6, pref = max(-1000, -5e6 + -1000 = -5.001e6) => -1000, suf = max(-1000, -1000 + -5e6 = -5.001e6) => -1000, best = max(-1000, -1000, -1000 + -1000 = -2000) => -1000. So answer remains -1000. Good.
Now we should also consider if the answer could be a large positive sum from a crossing that doesn't include full prefix but uses partial. The combine formula covers that.
Thus everything is correct.
Now we should also verify that we are not missing the case where the best subarray lies entirely within a small array, but that's covered by the max field of that block. The combine takes max of a.max, b.max, crossing.
Thus solution is done.
Now we can implement.
One more optimization: Since n is small, we could precompute block properties once.
Now think about reading: For each small array, we need to read l integers. Use scanf.
Now some potential pitfalls: The array of indices for big array may be given on multiple lines, but we read them with scanf in a loop, which will skip whitespace, so fine.
Now finalize code.
Edge case: n=1, m=1. Works.
Edge case: n=1, m=250000. Works.
Now test with small example:
n=1, l=3, values: -1 -2 -3, m=3, indices: 1 1 1. The big array: -1 -2 -3 -1 -2 -3 -1 -2 -3. The max subarray sum is -1 (the largest element). Our method: block: sum=-6, pref = -1, suf = -3? Actually compute: arr [-1,-2,-3]. sum=-6, pref: running: -1 -> -1, -3 -> -3, -6 -> -6, max pref = -1. suf: from right: -3 -> -3, -5 -> -5, -6 -> -6, max suf = -3? Wait, suffixes: last -3 (max -3), last two -2-3=-5, all three -6 => max = -3. best = -1. So block = (-6, -1, -3, -1). Combine three times: first combine with second: sum=-12, pref = max(-1, -6 + -1 = -7) = -1, suf = max(-3, -3 + -6 = -9) = -3? Actually for A (first) and B (same): A.suf = -3, B.sum = -6 => -9, B.suf = -3, max = -3. best = max(-1, -1, -3 + -1 = -4) = -1. So remains -1. After third: same. So answer -1. Correct.
Now test with mix: n=2, A1: [1, -5, 3], A2: [4, -1]. Compute manually: block1: values: 1,-5,3. sum=-1? 1-5+3=-1? Actually 1-5=-4, -4+3=-1. pref: 1, -4, -1 => max=1. suf: from right: 3, -5+3=-2, 1-5+3=-1 => max=3. best: subarrays: 1,1-5=-4,1-5+3=-1, -5, -5+3=-2,3 => max=3. So block1 = (-1,1,3,3). block2: [4,-1]: sum=3, pref:4,3 => max=4. suf: -1, 3 => max=3? Wait suffixes: -1, 4-1=3 => max=3. best: 4 (since 4 > 3). So block2 = (3,4,3,4). Sequence: [1, -5, 3, 4, -1]. Max subarray: possibly 3+4=7? Actually subarray from 3 (third element) to 4 (fourth) gives 3+4=7; maybe also 1-5+3+4=3? That's 3? Actually 1-5+3+4 = 3? 1-5=-4, -4+3=-1, -1+4=3, not 7. Check: 3+4=7, and then -1 makes 6. So max is 7. Also maybe 4 alone is 4. So 7 is max. Our combine: result after two blocks: sum = -1+3=2, pref = max(1, -1+4=3) = 3? Wait compute: A=block1, B=block2: sum = -1+3=2. pref = max(1, -1+4=3) => 3. suf = max(B.suf=3, A.suf=3 + B.sum=3? Actually A.suf=3, B.sum=3 => 3+3=6, max(3,6)=6. best = max(3,4, A.suf=3 + B.pref=4 = 7) => 7. So result = (2,3,6,7). So answer 7. Good.
Now confirm that pref and suf are correct: pref of combined array: maximum prefix sum could be starting from left: prefix sums: 1, -4, -1, 3, 2? Actually elements: 1, -5, 3, 4, -1. Prefix sums: 1, -4, -1, 3, 2. Max is 3. So pref=3. Suffix sums: from right: -1, 3 (4-1?), Actually from right: last -1, second last 4-1=3, third last 3+4-1=6, etc. So max suffix is 6 (from third last element 3 to end: 3+4-1=6). So suf=6. best=7. Works.
Thus combine formulas correct.
Now implement.
Now ensure to use proper data types: ll = long long.
Now coding.
Potential micro-optimizations: not needed.
Now final code.
But before final, think about whether we need to handle the case where the big array might be empty? m>=1 so not needed.
Now one more nuance: The combine operation can be done with a loop, but we might also consider using binary exponentiation if we have repeated consecutive same index to combine faster? But m is only 250k, and n small, so not needed.
But there is a twist: The indices array length m could be up to 250k, but each small array can be up to length 5000, so total actual elements could be huge, but our method is O(m). So fine.
Now I'm ready.
But I'll also consider if we can precompute block properties for each small array. That's done.
Now we need to read the small arrays. The input format: each line: first integer l, then l integers. Could be many numbers per line; we just read sequentially.
We can read with scanf.
Pseudo:
int n, m;
scanf("%d %d", &n, &m);
vector blocks(n+1);
for (int i=1; i<=n; i++) {
int l;
scanf("%d", &l);
vector arr(l);
for (int j=0; j<l; j++) {
scanf("%d", &arr[j]);
}
// compute sum, pref, suf, best
ll sum = 0;
for (int x : arr) sum += x;
code
ll pref = LLONG_MIN;
ll running = 0;
for (int x : arr) {
running += x;
if (running > pref) pref = running;
}
ll suf = LLONG_MIN;
running = 0;
for (int j=l-1; j>=0; j--) {
running += arr[j];
if (running > suf) suf = running;
}
ll best = LLONG_MIN;
ll cur = 0;
for (int x : arr) {
cur = max((ll)x, cur + x);
if (cur > best) best = cur;
}
blocks[i] = {sum, pref, suf, best};
}
// read big array indices
int idx;
scanf("%d", &idx);
Block res = blocks[idx];
for (int i=1; i<m; i++) {
scanf("%d", &idx);
res = combine(res, blocks[idx]);
}
cout << res.best << endl;
Now we need to define combine function.
Now ensure that we handle negative values in cur: Starting cur=0 works.
Now check if the computed pref and suf can be less than the best? That's fine.
Now run sample:
Input:
3 4
3 1 6 -2
2 3 3
2 -5 1
2 3 1 3
Compute:
i=1: l=3, arr[1,6,-2]. sum=5, pref: running:1=>1>LLONG_MIN->pref=1; 1+6=7>1->pref=7; 7-2=5<7, pref stays 7. suf: from right: -2 => -2; -2+6=4> -2->suf=4; 4+1=5>4->suf=5. best: cur: start cur=0; x=1: cur=max(1,0+1)=1, best=1; x=6: cur=max(6,1+6=7)=7, best=7; x=-2: cur=max(-2,7-2=5)=5, best stays 7. So block1: (5,7,5,7)? Wait suf we computed 5? Actually we got suf=5, which matches earlier. So (5,7,5,7).
i=3: arr[-5,1]. sum=-4, pref: -5 -> -5; -4 -> -4; pref = -4 (since -4 > -5). suf: from right: 1 ->1; 1-5=-4 -> -4; max = 1. best: cur: -5 -> cur = max(-5,0-5=-5) = -5, best=-5; x=1: cur = max(1, -5+1=-4) = 1, best = max(-5,1)=1. So block3: (-4, -4, 1, 1).
Now combine as described yields 9.
Now output 9.
Second sample: works.
Thus final answer.
Now, we might consider using integer arrays for blockProps.
Now confirm that combine's max of three numbers is computed correctly.
Now I'm ready to produce final solution.
But before finalizing, I want to consider if there's any possibility that the answer is not simply the max field after combining all blocks because the answer must be the maximum sum of a contiguous subarray, which we compute exactly via the block reduction. That is correct.
Now I'll think about potential alternative interpretations: The problem statement says "you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array." That matches.
Now the standard problem is maximum subarray sum.
Thus solution is correct.
Now code.
One more nuance: The small arrays may not be used at all? The indices array uses only some; but we have properties for all.
Now output.
Now finalize.
But there's a catch: In the combine operation, we treat each block as having its own pref, suf, max, sum. However, is it correct to use these values directly in combine for blocks that are themselves the result of combining many blocks? Yes, because those properties are exactly the aggregate properties of the concatenated array up to that point. So combining sequentially yields correct aggregate for the whole.
Now verify associativity formally: The combine operation we defined computes the four metrics for the concatenation of two arrays based solely on those metrics of the two parts. This is a well-known result: these four metrics form a monoid.
Thus we are good.
Now ensure we use the correct types: all long long.
Now I'll implement with some minor optimizations: Not storing arr if we compute suffix in a separate loop after reading; we need arr for suffix, so we store in a temporary vector. That's fine.
But we could also compute suffix without storing by reading the numbers into an array then computing. That's what we do.
Now reading: For each small array, we do:
int l; scanf("%d", &l);
vector arr(l);
for (int j=0; j<l; ++j) scanf("%d", &arr[j]);
This reads l ints. That's fine.
But note that the sum of l's across all small arrays can be up to 250k, and each integer up to 1000. So this loop is fine.
Now we can consider that we might not need to store the entire array if we compute suffix while reading backwards? Could read into vector anyway.
Now for the big array indices, we read m ints. That's okay.
Now total runtime: O(250k + 250k) = 0.5M operations, very fast.
Now we output.
Now final code.
But I think we should also handle the case where m is 0? Not needed.
Now I'm satisfied.
Thus final answer is to compute block monoid and reduce.
Now I'll craft final message with solution explanation and code.
Now final output. We can solve the problem by treating each small array as a block with four values: total sum, maximum prefix sum, maximum suffix sum, and maximum subarray sum inside the block. For the whole big array (concatenation of blocks), these four values can be obtained by combining the blocks in order using an associative operation. Thus we precompute the four values for each small array, then scan the list of indices and combine them sequentially. The answer is the max field of the final combined block.
The combination of two blocks A (left) and B (right) into C is:
C.sum = A.sum + B.sum
C.pref = max(A.pref, A.sum + B.pref)
C.suf = max(B.suf, A.suf + B.sum)
C.best = max( A.best, B.best, A.suf + B.pref )
This works because any maximum subarray either lies completely in A, completely in B, or crosses the boundary (a suffix of A plus a prefix of B).
Since n ≤ 50 and the total length of all small arrays is at most 250000, we can easily precompute their block values. Then we process the m indices (m ≤ 250000) in one pass, combining the current aggregate with the next block. The total time is linear in the input size, and memory usage is minimal.
cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
struct Block {
ll sum, pref, suf, best;
};
Block combine(const Block& a, const Block& b) {
Block c;
c.sum = a.sum + b.sum;
c.pref = max(a.pref, a.sum + b.pref);
c.suf = max(b.suf, a.suf + b.sum);
c.best = max({a.best, b.best, a.suf + b.pref});
return c;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<Block> blocks(n + 1);
for (int i = 1; i <= n; ++i) {
int l;
cin >> l;
vector<int> arr(l);
for (int j = 0; j < l; ++j) {
cin >> arr[j];
}
// total sum
ll sum = 0;
for (int x : arr) sum += x;
// maximum prefix sum (non‑empty)
ll pref = -INF, running = 0;
for (int x : arr) {
running += x;
if (running > pref) pref = running;
}
// maximum suffix sum (non‑empty)
ll suf = -INF;
running = 0;
for (int j = l - 1; j >= 0; --j) {
running += arr[j];
if (running > suf) suf = running;
}
// maximum subarray sum inside the block (Kadane)
ll best = -INF, cur = 0;
for (int x : arr) {
cur = max((ll)x, cur + x);
if (cur > best) best = cur;
}
blocks[i] = {sum, pref, suf, best};
}
// read the big array indices and combine
int idx;
cin >> idx;
Block res = blocks[idx];
for (int i = 1; i < m; ++i) {
cin >> idx;
res = combine(res, blocks[idx]);
}
cout << res.best << '\n';
return 0;
}
But what about best? kadane_best will be the max subarray sum, which for all negatives will be the maximum element, which could be greater than pref (since pref is a prefix that could include more negatives). That's okay.