Codeforces508 E. Arthur and Brackets(括号匹配,贪心)

题意:

在这里插入图片描述

解法:
栈维护左括号,
由于只有当栈顶的左括号被匹配后才能继续匹配之后的左括号.
同时每个左括号有一个要求的区间,发现越早匹配一定不会别影响之后的匹配.
因此能匹配则匹配就行了.
code:
#include<bits/stdc++.h>
// #define MULTI_CASE
#define SYNC_OFF
#define PI pair<int,int>
#define ll long long
// #define int long long
using namespace std;
// const int mod=998244353;
const int mod=1e9+7;
const int maxm=2e6+5;
struct Node{
    int pos,l,r;
};
int n;
void solve(){
    cin>>n;
    string ans;
    stack<Node>s;
    for(int i=1;i<=n;i++){
        int l,r;cin>>l>>r;
        s.push({(int)ans.size()+1,l,r});
        ans+='(';
        while(s.size()){
            Node x=s.top();
            int now=(ans.size()+1)-x.pos;
            if(now>=x.l&&now<=x.r){//能匹配则匹配
                ans+=')';s.pop();
            }else break;
        }
    }
    if(s.size())cout<<"IMPOSSIBLE"<<endl;
    else cout<<ans<<endl;
}
void Main(){
    #ifdef MULTI_CASE
    int T;cin>>T;while(T--)
    #endif
    solve();
}
void Init(){
    #ifdef SYNC_OFF
    ios::sync_with_stdio(0);cin.tie(0);
    #endif
    #ifndef ONLINE_JUDGE
    freopen("../in.txt","r",stdin);
    freopen("../out.txt","w",stdout);
    #endif
}
signed main(){
    Init();
    Main();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值