zoukankan      html  css  js  c++  java
  • CF508E Arthur and Brackets(贪心+栈)(来自洛谷)

    洛谷地址:https://www.luogu.com.cn/problem/CF508E

    题意:

    给出n对L,R

    第i个左括号,与它匹配的右括号与左括号的距离范围为:[L,R]

    求是否有序列满足,否则:IMPOSSIBLE

    解析:

    看了不少题解,勉强搞懂。

    对于括号匹配问题,应该优先想到栈。因为括号的匹配符合先进后出,所以用stack来进行模拟。

    栈顶的括号进行优先匹配,

    如果它的左括号位置+L>cnt,位置留下,供下一个左括号使用。

    左括号位置+R<cnt,已经没有多余位置匹配右括号了,这个时候一定不满足条件。

    #include<iostream>
    #include<cstring>
    #include<stack>
    using namespace std;
    typedef long long ll;
    const int maxn=605;
    int l[maxn],r[maxn];
    char ch[3*maxn];
    int pos[maxn];
    int main()
    {
        int n;
        scanf("%d",&n);
        memset(pos,0,sizeof(pos));
        stack<int>s;
        int cnt=0,ok=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d%d",&l[i],&r[i]);
            pos[i]=cnt;
            ch[cnt++]='(';
            s.push(i);
            while(!s.empty())
            {
                int u=s.top();
                if(l[u]+pos[u]>cnt)    break;
                if(r[u]+pos[u]<cnt)
                {
                    ok=1;break;
                }
                ch[cnt++]=')';
                s.pop();
            }
        }
        if(!ok&&s.empty())
            printf("%s
    ",ch);
        else
            printf("IMPOSSIBLE
    ");
    }
  • 相关阅读:
    计算机硬件基础
    元类
    内置函数
    单例模式的三种实现方式
    字符编码
    odoo权限
    odoo api介绍
    odoo 二次开发小记不定时更新
    js与jQuery区别
    Cookie, LocalStorage 与 SessionStorage说明
  • 原文地址:https://www.cnblogs.com/liyexin/p/13441558.html
Copyright © 2011-2022 走看看