bzoj 4936: [Ceoi2016]match

题意:

按照要求构造一个最小字典序的括号序列,对于两两匹配的括号,在给出的串中对应位置的字母也要相同。

题解:

一开始看错题了,写了个ZZ代码
然后就什么也不会了。
只知道判断有没有答案就是弄个栈搞搞。
orz:题解
code:

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<cstring>
#include<map>
#include<stack>
#include<algorithm>
#define LL long long
using namespace std;
const LL hash=10037;
const LL mod=1000000007;
char s[100005];
stack<int> S;
map<int,int> R[30];
LL n,p[100005],L[100005];
LL pre[100005];
LL ans[100005];
void solve(LL l,LL r)
{
    if(l>r) return;
    ans[l]=1;
    LL x=s[l]-'a'+1,pos=R[x][pre[l-1]];
    while(ans[pos]!=-1) pos=L[pos];
    R[x][pre[l-1]]=L[pos];
    ans[pos]=2;
    solve(pos+1,r);solve(l+1,pos-1);
}
int main()
{
    scanf("%s",s+1);
    n=strlen(s+1);
    p[0]=1;for(LL i=1;i<=n;i++) p[i]=p[i-1]*hash%mod;
    LL now=0;
    for(LL i=1;i<=n;i++)
    {
        LL c=s[i]-'a'+1;
        if(S.empty()||s[S.top()]!=s[i])
        {
            S.push(i);
            now=(now+p[S.size()]*c%mod)%mod;
        }
        else now=(now-p[S.size()]*c%mod+mod)%mod,S.pop();
        pre[i]=now;
    }
    if(!S.empty()) {printf("-1");return 0;}
    for(LL i=1;i<=n;i++)
    {
        LL c=s[i]-'a'+1;
        L[i]=R[c][pre[i]];
        R[c][pre[i]]=i;
    }
    memset(ans,-1,sizeof(ans));
    solve(1,n);
    for (LL i=1;i<=n;i++)
    {
        if (ans[i]==1) printf("(");
        else printf(")");
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值