CodeForces - 1323A - Unusual Competitions(思维)

题目链接
官方题解
  这次只是对官方题解做一下简化...
  我们首先先看一下dalao画的图:

  其实如果能画出来这张图那么思路已经很清晰了...
  1.因为每一个'('都要有一个')'来匹配,所以说无论是对于一个正确的区间,还是对于一个错误的、但是可以重新排序的区间,它的左右端点都应该是0,如果不存在任意的一个区间左右端点大于0,那就没法重新排序。
  2.因为'('必须在')'前面,所以我们设一个'('可以让函数值+1,一个')'可以让函数值-1,那么对于一个左右端点为0的区间来说,如果它是正确的,那么它的区间内所有的值都应该不小于0,同样,对于一个错误的区间,
它的区间内一定有至少一个值小于0。
  所以我们要做的就是统计错误区间的长度(红线)。

//https://www.cnblogs.com/shuitiangong/
#include<set>
#include<map>
#include<list>
#include<stack>
#include<queue>
#include<cmath>
#include<cstdio>
#include<cctype>
#include<string>
#include<vector>
#include<climits>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define endl '\n'
#define rtl rt<<1
#define rtr rt<<1|1
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
#define zero(a) memset(a, 0, sizeof(a))
#define INF(a) memset(a, 0x3f, sizeof(a))
#define IOS ios::sync_with_stdio(false)
#define _test printf("==================================================\n")
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<ll, ll> P2;
const double pi = acos(-1.0);
const double eps = 1e-7;
const ll MOD =  1000000009;
const int INF = 0x3f3f3f3f;
template<typename T> void read(T &x){
    x = 0;char ch = getchar();ll f = 1;
    while(!isdigit(ch)){if(ch == '-')f*=-1;ch=getchar();}
    while(isdigit(ch)){x = x*10+ch-48;ch=getchar();}x*=f;
}
const int maxn = 1e6+10;
char str[maxn];
int main(void) {
    int n;
    while(~scanf("%d %s", &n, str)) {
        int ans = 0, tot = 0;
        for (int i = 0, t = 0; i<n; ++i) {
            if (str[i]=='(') {
                ++tot;
                if (!tot) {
                    ans += i-t+1;
                    t = 0;
                }
            }
            else {
                if (!tot) t = i;
                --tot;
            }
        }
        printf("%d\n", !tot ? ans : -1);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/shuitiangong/p/12551246.html