zoukankan      html  css  js  c++  java
  • Codeforces Round #459 (Div. 2)The Monster[匹配问题]

    题意

    给一个序列,包含(,),?,?可以被当做(或者),问你这个序列有多少合法的子序列。

    分析

    n^2枚举每一个子序列,暂时将每个?都当做右括号,在枚举右端点的时候同时记录两个信息:当前左括号多余多少个(top),已经将多少个?变成了右括号(cnt)。
    如果当前是(,top++.
    如果当前是),top--.
    如果当前是?,top--,cnt++;
    如果top<0,我们需要判断一下当前还有没有之前被当做右括号的?,如果有的话,我们将其变为左括号,如果没有的话,意味着可以跳出循环了,之后都不会再合法了。
    如果任何时刻top==0,那么意味着当前区间合法,ans++。
    巧妙地贪心

    代码

    #include <bits/stdc++.h>
    using namespace std;
    
    #define ll long long
    
    char s[5050];
    
    int main(int argc, char const *argv[])
    {
    	scanf("%s",s);
    	int ans=0;
    	for(int i=0;s[i]!='';++i)
    	{
    		int left=0,cnt=0;
    		for(int j=i;s[j]!='';++j)
    		{
    			if(s[j]=='(') left++;
    			if(s[j]==')') left--;
    			if(s[j]=='?') left--,cnt++;
    			if(left<0&&cnt) left+=2,cnt--;
    			if(left==0) ans++;
    			if(left<0&&!cnt) break;
    		}
    	}
    	printf("%d
    ",ans );
    	return 0;
    }
    
  • 相关阅读:
    Vue生命周期
    Vue-Router
    Vue组件
    Vue基础以及指令
    ES6 常用语法
    缓存、序列化、信号
    四、全局事务的commit和rollback
    三、全局事务begin请求GlobalBeginRequest
    二、分布式事务协调者DefaultCoordinator
    一、seata-server的main启动方法
  • 原文地址:https://www.cnblogs.com/chendl111/p/8391196.html
Copyright © 2011-2022 走看看