JZOJ5893. 【NOIP2018模拟10.4】括号序列

在这里插入图片描述
在这里插入图片描述

题解

维护一个栈,如果这个栈为空,就得到了一个答案。
考虑到如果某两个位置栈里面完全一样,这也可以说明他们两个之间的栈里面是没有任何元素。
于是可以用一个哈希值来表示一个栈里面的元素。

code

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#define N 1000003
#define ll long long
#define G getchar
using namespace std;

const ll mo=123456787654321;
const int w=31,M=10000007; 
int n,g[M],z[N],top,t;
ll h[M],s[N],ans;
char ch;

int hash(ll s)
{
	int x=s%M;
	for(;h[x]!=0 && h[x]!=s;x=x%M+1);
	return x;
}

int main()
{
	freopen("bracket.in","r",stdin);
	freopen("bracket.out","w",stdout);
	
	for(ch=G();ch<'a' && ch>'z';ch=G());
	for(n=0;'a'<=ch && ch<='z';ch=G())
	{
		t=ch-'a'+1;
		if(t==z[top])top--;
			else z[++top]=t,s[top]=(s[top-1]*w+t)%mo;
		if(top==0)ans++;
		t=hash(s[top]);h[t]=s[top];ans=ans+g[t];g[t]++;
	}
	
	printf("%lld",ans);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/lijf2001/article/details/82949841