CodeForces - 918C(匹配问题)

本文介绍了一种用于计算字符串中括号对数目的算法。通过遍历字符串并追踪左括号及可变括号的数量,该算法能有效地找出所有合法括号对。代码中详细解释了实现过程。

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

题意:给你一个字符串,有多少对符合规则的左右括号-----》比如()   (())   ((?)   (?))  这里的?可以换为左括号或者右括号


在这个题中,我们可以去找左括号和?的个数,先暂时把?看为右括号。这样,我们在找的时候,就可以很好的去匹配了。

作者的解释基本都在代码里注释了。这就不做过多解释了。

 

代码:

#include<set>
#include<map>
#include<stack>
#include<bitset>
#include<math.h>
#include<string>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
#define close ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N=1000000+50;
const int INF=0x3f3f3f3f;
const double EPS = 1e-10;
ll mod = 1e9+7;

string s;
int len,ans;

int main(){
	cin>>s;
	ans = 0;
	len = s.length();
	for(int i = 0; i < len; i++){
		int lt = 0, rt = 0; //rt代表将?看为);
		for(int j = i; j < len; j++){
			if(s[j] == '(') lt++;
			else if(s[j] == '?'){
				if(lt == rt) lt++;
				else rt++;
			}
			else{
				if(lt == rt) rt--;  //如果此时多出了一个右括号,那么让?为左括号 
				else lt--;
				if(lt < 0) break;
				if(rt < 0) break;
			}
			if((j - i + 1) % 2 == 0 && rt == lt){
				ans++;
			}
		} 
	}
	cout<<ans<<endl;
 	return 0;
}

/*
                ********
               ************
               ####....#.
             #..###.....##....
             ###.......######              ###            ###
                ...........               #...#          #...#
               ##*#######                 #.#.#          #.#.#
            ####*******######             #.#.#          #.#.#
           ...#***.****.*###....          #...#          #...#
           ....**********##.....           ###            ###
           ....****    *****....
             ####        ####
           ######        ######
##############################################################
#...#......#.##...#......#.##...#......#.##------------------#
###########################################------------------#
#..#....#....##..#....#....##..#....#....#####################
##########################################    #----------#
#.....#......##.....#......##.....#......#    #----------#
##########################################    #----------#
#.#..#....#..##.#..#....#..##.#..#....#..#    #----------#
##########################################    ############
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吃货智

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值