2043C.md (2218B)
1 Source: https://codeforces.com/problemset/problem/2043/C 2 3 C. Sums on Segments 4 5 time limit per test 6 7 1 second 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 standard input 16 17 output 18 19 standard output 20 21 You are given an array $a$ of $n$ integers, where all elements except for at most one are equal to $-1$ or $1$. The remaining element $x$ satisfies $-10^9 \le x \le 10^9$. 22 23 Find all possible sums of subarrays of $a$, including the empty subarray, whose sum is defined as $0$. In other words, find all integers $x$ such that the array $a$ has at least one subarray (possibly empty) with sum equal to $x$. A subarray is a contiguous subsegment of an array. 24 25 Output these sums in ascending order. Each sum should be printed only once, even if it is achieved by multiple subarrays. 26 27 Input 28 29 The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then, $t$ test cases follow. 30 31 Each test case consists of two lines: 32 33 * The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the size of the array. 34 * The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9$) — the elements of the array $a$. In the array $a$, there is at most one element that is neither $1$ nor $-1$. 35 36 Additional constraint on the input: the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$. 37 38 Output 39 40 For each test case, output two lines: 41 42 * In the first line, print a single integer — the number of distinct subarray sums. 43 * In the second line, print these sums in ascending order. 44 45 Each sum should be printed only once, even if it is produced by multiple subarrays. 46 47 Example 48 49 Input 50 51 ``` 52 5 53 54 5 55 56 1 -1 10 1 1 57 58 5 59 60 -1 -1 -1 -1 -1 61 62 2 63 64 -1 2 65 66 2 67 68 7 1 69 70 3 71 72 1 4 -1 73 ``` 74 75 Output 76 77 ``` 78 8 79 -1 0 1 2 9 10 11 12 80 6 81 -5 -4 -3 -2 -1 0 82 4 83 -1 0 1 2 84 4 85 0 1 7 8 86 6 87 -1 0 1 3 4 5 88 ``` 89 90 Note 91 92 Let's define $a[i,j]$ as the subarray of $a$ from position $i$ to position $j$. 93 94 Consider the first test case of the example: 95 96 * $-1$ is produced by $a[2,2]$; 97 * $0$ is produced by the empty subarray; 98 * $1$ is produced by $a[4,4]$; 99 * $2$ is produced by $a[4,5]$; 100 * $9$ is produced by $a[2,3]$; 101 * $10$ is produced by $a[1,3]$; 102 * $11$ is produced by $a[3,4]$; 103 * $12$ is produced by $a[3,5]$.