bzoj 4936: [Ceoi2016]match hash+构造

题意

给你一个由小写字母组成的字符串s,要你构造一个字典序最小的(认为左括号的字典序比右括号小)合法的括号序列与这个字符串匹配,字符串和括号序列匹配定义为:首先长度必须相等,其次对于一对匹配的左括号和右括号i,j,必须有s[i]==s[j]。无解输出-1
n<=100000

分析

一道脑洞比较大的题。

设f[i,j]=0/1表示[i,j]这一段是否能组成一个合法的括号序。
首先考虑如何判-1。我们可以把元素逐个放入一个栈内,若栈顶两个元素相同则出栈。显然若最后栈不为空则必然没有合法方案,反之则必然存在合法方案。
我们设hash[i]表示把前i个元素放入栈后那个栈的hash值。
显然若f[i,j]==1则必有hash[i-1]==hash[j]
我们设过程solve(l,r)表示给[l,r]这一段构造一个字典序最小的方案。显然l一定是左括号,设l匹配的位置为pos,那么有pos={max(x)|s[x]==s[l]且f[x+1,r]==1}
由于f[x+1,r]==1等价于hash[x]==hash[r],也就是说我们要找到一个最大的x满足s[x]==s[l]且hash[x]==hash[r]。
问题在于如何找pos。我们可以用map来维护一个指针,然后先递归solve(pos+1,r),这样的话所有的指针都移到了[l,pos],然后再递归solve(l+1,pos-1)即可。

代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;

typedef long long LL;

const int N=100005;
const int MOD1=1000000007;
const int MOD2=998244353;

int n,mi1[N],mi2[N],sta[N],top,lef[N],ans[N],s[N];
pair<int,int> hash[N];
map<pair<int,int>,int> w[27];
char ch[N];

void solve(int l,int r)
{
    if (l>r) return;
    ans[l]=1;
    int pos=w[s[l]][hash[r]];
    while (ans[pos]) pos=lef[pos];
    w[s[l]][hash[r]]=lef[pos];
    ans[pos]=2;
    solve(pos+1,r);solve(l+1,pos-1);
}

int main()
{
    scanf("%s",ch+1);
    n=strlen(ch+1);
    for (int i=1;i<=n;i++) s[i]=ch[i]-'a'+1;
    mi1[0]=mi2[0]=1;
    LL now1=0,now2=0;
    for (int i=1;i<=n;i++)
    {
        mi1[i]=(LL)mi1[i-1]*26%MOD1;
        mi2[i]=(LL)mi2[i-1]*26%MOD2;
        if (top&&s[sta[top]]==s[i])
        {
            (now1-=(LL)mi1[top-1]*s[sta[top]])%=MOD1;
            (now2-=(LL)mi2[top-1]*s[sta[top]])%=MOD2;
            if (now1<0) now1+=MOD1;
            if (now2<0) now2+=MOD2;
            top--;
        }
        else
        {
            sta[++top]=i;
            (now1+=(LL)mi1[top-1]*s[i])%=MOD1;
            (now2+=(LL)mi2[top-1]*s[i])%=MOD2;
        }
        hash[i]=make_pair((int)now1,(int)now2);
        lef[i]=w[s[i]][hash[i]];
        w[s[i]][hash[i]]=i;
    }
    if (hash[n].first||hash[n].second)
    {
        puts("-1");
        return 0;
    }
    solve(1,n);
    for (int i=1;i<=n;i++) putchar(ans[i]==1?'(':')');
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值