1. 程式人生 > 其它 >CF5 C. Longest Regular Bracket Sequence

CF5 C. Longest Regular Bracket Sequence

題目傳送門:https://codeforces.com/problemset/problem/5/C

題目大意:
給定一串括號序列,求最長合法括號序列的長度及出現次數


考慮將 '(' 變成 1,將 ')' 變成 -1,故合法括號序列的累加和必然為0

考慮求其字首和,由於括號序列是一一匹配的,故我們可以用vector記錄字首和為 \(k\) 的一系列位置,匹配完後將 '(' 的位置刪除即可

/*program from Wolfycz*/
#include<map>
#include<cmath>
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#define Fi first
#define Se second
#define ll_inf 1e18
#define MK make_pair
#define sqr(x) ((x)*(x))
#define pii pair<int,int>
#define int_inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline char gc(){
	static char buf[1000000],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
template<typename T>inline T frd(T x){
	int f=1; char ch=gc();
	for (;ch<'0'||ch>'9';ch=gc())	if (ch=='-')    f=-1;
	for (;ch>='0'&&ch<='9';ch=gc())	x=(x<<1)+(x<<3)+ch-'0';
	return x*f;
}
template<typename T>inline T read(T x){
	int f=1; char ch=getchar();
	for (;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')	f=-1;
	for (;ch>='0'&&ch<='9';ch=getchar())	x=(x<<1)+(x<<3)+ch-'0';
	return x*f;
}
inline void print(int x){
	if (x<0)	putchar('-'),x=-x;
	if (x>9)	print(x/10);
	putchar(x%10+'0');
}
const int N=1e6;
char s[N+10];
vector<int>pos[N+10];
void init(){for (int i=0;!pos[i].empty();i++)	pos[i].clear();}
int main(){
//	freopen(".in","r",stdin);
//	freopen(".out","w",stdout);
	scanf("%s",s+1);
	int n=strlen(s+1),sum=0;
	int Max=0,Cnt=0;
	pos[0].push_back(0);
	for (int i=1;i<=n;i++){
		sum+=s[i]=='('?1:-1;
		if (sum<0){
			init(); sum=0;
			pos[sum].push_back(i);
			continue;
		}
		if (pos[sum].empty())	pos[sum].push_back(i);
		else{
			int len=i-pos[sum].back();
			if (len>Max)	Max=len,Cnt=0;
			Cnt+=(len==Max);
			pos[sum+1].clear();
		}
	}
	printf("%d %d\n",Max,!Max?1:Cnt);
	return 0;
}