D - Parentheses
Time limit : 2sec / Memory limit : 512MB
Problem Statement
Dave loves strings consisting only of '(' and ')'. Especially, he is interested in balanced strings. Any balanced strings can be constructed using the following rules:
- A string "()" is balanced.
- Concatenation of two balanced strings are balanced.
- If T T is a balanced string, concatenation of '(', T T, and ')' in this order is balanced. For example, "()()" and "(()())" are balanced strings. ")(" and ")()(()" are not balanced strings.
Dave has a string consisting only of '(' and ')'. It satisfies the followings:
- You can make it balanced by swapping adjacent characters exactly A A times.
- For any non-negative integer B (B<A) B (B<A), you cannot make it balanced by B B swaps of adjacent characters.
- It is the shortest of all strings satisfying the above conditions.
Your task is to compute Dave's string. If there are multiple candidates, output the minimum in lexicographic order. As is the case with ASCII, '(' is less than ')'.
Input
The input consists of a single test case, which contains an integer A(1≤A≤109) A(1≤A≤109).
Output
Output Dave's string in one line. If there are multiple candidates, output the minimum in lexicographic order.
Sample Input 1
1
Output for the Sample Input 1
)(
There are infinitely many strings which can be balanced by only one swap. Dave's string is the shortest of them.
Sample Input 2
4
Output for the Sample Input 2
)())((
String "))(()(" can be balanced by 4 4 swaps, but the output should be ")())((" because it is the minimum in lexicographic order.
根据规律
))(( 为2*(2+1)/2次
)))((( 为 3*(3+1)/2次
n个)n个( 为n*(n+1)/2
先找大比n大的数(a+1)*a/2,然后让一个括号向前挪动(a+1)*a/2-n个
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int a;
int main()
{
int n=0,k;
scanf("%d",&a);
while(1)
{
if(n*(n+1)/2>=a)
break;
n++;
}
k = n*(n+1)/2-a;
for(int i=0;i<n - k;i++)
printf(")");
printf("(");
for(int i=0;i<k;i++)
printf(")");
for(int i=0;i<n-1;i++)
printf("(");
printf("\n");
return 0;
}