【规律】Parentheses

Parentheses

题目描述
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 is a balanced string, concatenation of '(', 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 satises the followings:

You can make it balanced by swapping adjacent characters exactly A times.
For any non-negative integer B (B<A), you cannot make it balanced by 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 ')'.

 

输入
The input consists of a single test case, which contains an integer A (1≤A≤109).

 

输出
Output Dave's string in one line. If there are multiple candidates, output the minimum in lexicographic order.

 

样例输入

1
样例输出
)(

 

提示

There are infinitely many strings which can be balanced by only one swap. Dave's string is the shortest of them.

 


 

【题意】

  请大家找到一个通过交换两个位置的操作,经过n次这样操作,能把括号序列变成合法。

  首先保证最短,其次保证字典序最小。

 

【题解】

  1:  ")("

  3:  "))(("

  6:  ")))((("

  10:  "))))(((("

 

  2:  ")()("

  4:  "))()(("

  5:  ")())(("

  

根据上面的情况找出的规律是:

  等差数列的位置必定是  " )))((("这样的,但是如果不是等差数列则需要在某个位置上交换一下。

  “)())((”

  "))()(("


 

 

 1 #pragma GCC optimize(2)
 2 #include <bits/stdc++.h>
 3 using namespace std;
 4 typedef long long ll;
 5 const ll mod = 998244353;
 6 typedef pair<ll,ll> pii;
 7 inline ll read(){ll x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();return x*f;}
 8  
 9 const int N=1e7+10;
10  
11  
12 int main()
13 {
14     ll n;
15     scanf("%lld",&n);
16     int pos = sqrt(2*n);
17     while(pos*(pos+1) > 2*n) pos--;
18     //cout<<pos<<endl;
19     if(pos*(pos+1)/2 == n){
20         for(int i=1;i<=pos;i++) printf(")");
21         for(int i=1;i<=pos;i++) printf("(");
22         printf("\n");
23         //main();
24         return 0;
25     }
26     int dis = n - pos*(pos+1)/2;
27     //cout<<dis<<endl;
28  
29     for(int i=1;i<=dis;i++) printf(")");
30     printf("(");
31     for(int i=dis;i<=pos;i++) printf(")");
32     for(int i=1;i<=pos;i++) printf("(");
33     printf("\n");
34     //main();
35     return 0;
36 }
37  
View Code

 

 

转载于:https://www.cnblogs.com/Osea/p/11455852.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值