hackercup / 2012 /round1 /recover_the_sequence.html
wjomlex's picture
2012 Problems
91a79e0 verified
raw
history blame contribute delete
No virus
2.81 kB
<p>Merge sort is one of the classic sorting algorithms. It divides the input array into two halves, recursively sorts each half, then merges the two sorted halves.</p>
<p>In this problem merge sort is used to sort an array of integers in ascending order. The exact behavior is given by the following pseudo-code:</p>
<pre>function merge_sort(arr):
n = arr.length()
if n <= 1:
return arr
// arr is indexed 0 through n-1, inclusive
mid = floor(n/2)
first_half = merge_sort(arr[0..mid-1])
second_half = merge_sort(arr[mid..n-1])
return merge(first_half, second_half)
function merge(arr1, arr2):
result = []
while arr1.length() > 0 and arr2.length() > 0:
if arr1[0] < arr2[0]:
print '1' // for debugging
result.append(arr1[0])
arr1.remove_first()
else:
print '2' // for debugging
result.append(arr2[0])
arr2.remove_first()
result.append(arr1)
result.append(arr2)
return result</pre>
<p>A very important permutation of the integers 1 through <strong>N</strong> was lost to a hard drive failure. Luckily, that sequence had been sorted by the above algorithm and the debug sequence of 1s and 2s was recorded on a different disk. You will be given the length <strong>N</strong> of the original sequence, and the debug sequence. Recover the original sequence of integers.</p>
<h3>Input</h3>
<p>The first line of the input file contains an integer <strong>T</strong>. This is followed by <strong>T</strong> test cases, each of which has two lines. The first line of each test case contains the length of the original sequence, <strong>N</strong>. The second line contains a string of 1s and 2s, the debug sequence produced by merge sort while sorting the original sequence. Lines are separated using Unix-style ("\n") line endings.</p>
<h3>Output</h3>
<p>To avoid having to upload the entire original sequence, output an integer checksum of the original sequence, calculated by the following algorithm:</p>
<pre>function checksum(arr):
result = 1
for i=0 to arr.length()-1:
result = (31 * result + arr[i]) mod 1000003
return result</pre>
<h3>Constraints</h3>
<p>
5 &le; <strong>T</strong> &le; 20<br/>
2 &le; N &le; 10,000
</p>
<h3>Examples</h3>
<p>In the first example, N is 2 and the debug sequence is <tt>1</tt>. The original sequence was 1 2 or 2 1. The debug sequence tells us that the first number was smaller than the second so we know the sequence was 1 2. The checksum is 994.</p>
<p>In the second example, N is 2 and the debug sequence is <tt>2</tt>. This time the original sequence is 2 1.</p>
<p>In the third example, N is 4 and the debug sequence is <tt>12212</tt>. The original sequence is 2 4 3 1.</p>