1970A1.md (2476B)
1 Source: https://codeforces.com/problemset/problem/1970/A1 2 3 A1. Balanced Shuffle (Easy) 4 5 time limit per test 6 7 2 seconds 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 A parentheses sequence is a string consisting of characters "(" and ")", for example "(()((". 22 23 A balanced parentheses sequence is a parentheses sequence which can become a valid mathematical expression after inserting numbers and operations into it, for example "(()(()))". 24 25 The balance of a parentheses sequence is defined as the number of opening parentheses "(" minus the number of closing parentheses ")". For example, the balance of the sequence "(()((" is 3. 26 27 A balanced parentheses sequence can also be defined as a parentheses sequence with balance 0 such that each of its prefixes has a non-negative balance. 28 29 We define the balanced shuffle operation that takes a parentheses sequence and returns a parentheses sequence as follows: first, for every character of the input sequence, we compute the balance of the prefix of the sequence before that character and write those down in a table together with the positions of the characters in the input sequence, for example: 30 31 | | | | | | | | | | 32 | --- | --- | --- | --- | --- | --- | --- | --- | --- | 33 | Prefix balance | 0 | 1 | 2 | 1 | 2 | 3 | 2 | 1 | 34 | Position | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 35 | Character | ( | ( | ) | ( | ( | ) | ) | ) | 36 37 Then, we sort the columns of this table in increasing order of prefix balance, breaking ties in decreasing order of position. In the above example, we get: 38 39 | | | | | | | | | | 40 | --- | --- | --- | --- | --- | --- | --- | --- | --- | 41 | Prefix balance | 0 | 1 | 1 | 1 | 2 | 2 | 2 | 3 | 42 | Position | 1 | 8 | 4 | 2 | 7 | 5 | 3 | 6 | 43 | Character | ( | ) | ( | ( | ) | ( | ) | ) | 44 45 The last row of this table forms another parentheses sequence, in this case "()(()())". This sequence is called the result of applying the balanced shuffle operation to the input sequence, or in short just the balanced shuffle of the input sequence. 46 47 You are given a balanced parentheses sequence. Print its balanced shuffle. 48 49 Input 50 51 The only line of input contains a string $s$ consisting only of characters "(" and ")". This string is guaranteed to be a non-empty balanced parentheses sequence with its length not exceeding $500\,000$. 52 53 Output 54 55 Print the parentheses sequence $t$ — the balanced shuffle of $s$. 56 57 Example 58 59 Input 60 61 ``` 62 (()(())) 63 ``` 64 65 Output 66 67 ``` 68 ()(()()) 69 ```