Codeforces Round #459 (Div. 2) - C. The Monster(贪心)

本文介绍了一种解决CodeForces 918C问题的算法,该问题要求计算字符串中合法括号序列的数量。通过遍历字符串并使用计数器来跟踪括号匹配情况,遇到不匹配时调整问号实现括号平衡。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://codeforces.com/contest/918/problem/C


题意:

给你一串?(),让你求有几组[l,r],l-r中的括号是匹配的。

POINT:

2 ≤ |s| ≤ 5000,可以遍历l,然后往前判断是否匹配。

遇"(" , now++.

  ")",now--.

先把"?"全部当成")",然后当temp<0的时候,把"?"(之前变为了")")变回“(”,

如果没有?了那就break了。


#include <string>
#include <string.h>
#include <iostream>
#include <queue>
#include <cmath>
#include <stdio.h>
#include <algorithm>
using namespace std;
typedef long long LL;
#define lt x<<1
#define rt x<<1|1
const LL maxn = 200000;
const LL mod = 9901;
string s;
queue<int>q;
int main()
{
	cin>>s;
	int len=s.length();
	int ans = 0;
	for(int i=0;i<len;i++){
		int now = 0;
		int temp = 0;
		for(int j=i;j<len;j++){
			if(s[j]=='('){
				now++;
			}else{
				now--;
				if(s[j]=='?')
					temp++;
			}
			if(now<0){
				if(!temp) break;
				temp--;
				now+=2;
			}
			if(now==0){
				ans++;
			}
		}
	}
	printf("%d\n",ans);

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值