题解-CF2143E
首先注意到,任何合法括号序列长度必须是偶数,每个前缀中 ( 的数量都不小于 ) 的数量,且最后总数相等。在我们的变换中,每次操作都会改变左右括号的总数:从 (( 变 )) 时,( 个数减 2,) 个数加 2;从 )) 变 ( ( 时,则相反。因此,( 与 ) 的总数量差值会改变 4 的倍数,但无法改变 2 的奇偶性。由此得到必要条件:字符串长度 ( 和 ) 个数之差必须是 ( 与 ) 个数相等,应直接输出 -1。
进一步分析可知,还有一个 奇偶位分布 不变量。记奇数位置(( 个数为 ( 个数为 ( 的数量。令 (,并且目标序列的奇位上 ( 个数 ( 个数
由此解得 -1。尤其注意,第一个字符必须是 ((否则前缀为负),而
符合这些条件后,剩下的任务就是构造一个合法序列,使其在奇数位置上恰有 (,偶数位置上恰有 (。
我们使用贪心从左到右构造目标序列。用 cnt 表示当前扫描前缀的未匹配的 ( 数量(初始为 0),用 ol、el 分别记录还剩下多少个 ( 需要放在奇位和偶位上。用 or、er 记录当前及其后面还剩多少奇位、偶位位置。对每个位置 ( 还是 ):
- 如果
i 是奇数位置:- 如果
ol == or,表示剩余的所有奇位都必须放(,否则放不下,因此这里放(。 - 否则如果
ol == 0,说明不需要再在奇位放(,只能放)。 - 否则如果
cnt == 0(当前没有未匹配的(),为了不让序列前缀失配,也必须放(。 - 否则(都不受约束时)我们尽量放
((因为把尽量多的(放在前面通常可以保证余下位置可放下剩余的(并且保持平衡)。因此若此时还有ol > 0,则放(,否则放)。
- 如果
- 如果
i 是偶数位置:同理地,优先考虑是否必须放(或)。若无强制约束,则优先尝试放((只要el > 0)。
每次放 ( 就 cnt++,放 ) 则 cnt--。整个过程中若 cnt 变为负,则构造失败(说明路径选择错了);否则若最后 cnt 恰好为 0 且用完了所有的 ol,el,则构造成功。
Code :
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int maxn=1e6+9;
int T;
int n;
string s;
void solve()
{
cin>>n>>s;
if(n%2==1)
{
cout<<"-1\n";
return;
}
int cntl=0,cntr=0;
for(char c:s)
{
if(c=='(') cntl++;
else cntr++;
}
if((cntl-cntr)%4!=0)
{
cout<<"-1\n";
return;
}
int o=0,e=0;
for(int i=0;i<n;i++)
{
if((i+1)%2==1&&s[i]=='(') o++;
if((i+1)%2==0&&s[i]=='(') e++;
}
int D=o-e;
if((n+2*D)%4!=0)
{
cout<<"-1\n";
return;
}
int ol=(n+2*D)/4;
int el=n/2-ol;
if(ol<=0||el<0)
{
cout<<"-1\n";
return;
}
string t(n,'?');
int cnt=0;
int Or=n/2,er=n/2;
bool fl=true;
for(int i=1;i<=n;i++)
{
if(i%2==1)
{
if(ol==Or)
{
t[i-1]='(';
ol--;cnt++;
}
else if(ol==0)
{
t[i-1]=')';
cnt--;
}
else if(cnt==0)
{
t[i-1]='(';
ol--;cnt++;
}
else
{
if(ol>0)
{
t[i-1]='(';
ol--;cnt++;
}
else
{
t[i-1]=')';
cnt--;
}
}
Or--;
}
else
{
if(el==er)
{
t[i-1]='(';
el--;cnt++;
}
else if(el==0)
{
t[i-1]=')';
cnt--;
}
else if(cnt==0)
{
t[i-1]='(';
el--;cnt++;
}
else
{
if(el>0)
{
t[i-1]='(';
el--;cnt++;
}
else
{
t[i-1]=')';
cnt--;
}
}
er--;
}
if(cnt<0)
{
fl=false;
break;
}
}
if(!fl||cnt!=0||ol!=0||el!=0) cout<<"-1\n";
else cout<<t<<"\n";
}
signed main()
{
//freopen("test.in","r",stdin);
//freopen("test.out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>T;
while(T--) solve();
return 0;
}
还有你怎么知道第二天早上起来改了两行赛时的就过了,我的 IM perf 啊 /ll