CF917A: The Monster 题解

本文解析了CodeForces竞赛中一道关于字符串匹配的问题(C题),介绍了判断字符串是否为pretty的三个必要条件,并通过C++代码实现了这一逻辑。

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

题目链接: http://codeforces.com/contest/918/problem/C

分析

一个长度为|s|的字符串是pretty的充要条件如下:
1. |s| is even.
2. 0 ≤ s[1..i].count(‘(‘) + s[1..i].count(‘?’) - s[1..i].count(‘)’) for each 1 ≤ i ≤ |s|.
3. 0 ≤ s[i..|s|].count(‘)’) + s[i..|s|].count(‘?’) - s[i..|s|].count(‘(‘) for each 1 ≤ i ≤ |s|.
证明略.

代码

#include<bits/stdc++.h>
#define x first
#define y second
#define ok puts("ok");
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const double PI = acos(-1.0);
const int INF=0x3f3f3f3f;
const ll LINF=0x3f3f3f3f3f3f3f3f;
const int N=1e5+9;
const int shift=1e3+9;
const double Eps=1e-7;

string s;
bool f[5009][5009], g[5009][5009];

int main(void) {
    if(fopen("in", "r")!=NULL) {freopen("in", "r", stdin); freopen("out", "w", stdout);}
    while(cin >> s) {
        int len = s.length();
        for(int i = 0; i < len; i++) {
            bool flag = true;
            int cnt = 0;
            for(int j = i; j < len; j++) {
                if(s[j] == ')')
                    cnt--;
                else
                    cnt++;
                if(cnt < 0) flag = false;
                f[i][j] = flag;
            }
        }
        for(int i = 0; i < len; i++) {
            bool flag = true;
            int cnt = 0;
            for(int j = i; j >= 0; j--) {
                if(s[j] == '(')
                    cnt--;
                else
                    cnt++;
                if(cnt < 0) flag = false;
                g[j][i] = flag;
            }
        }
        int ans = 0;
        for(int i = 0; i < len; i++) {
            for(int j = 0; j < len; j++) {
                if((j-i+1)%2 == 0 && f[i][j] && g[i][j])
                    ans++;
            }
        }
        printf("%d\n", ans);

    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值