zoukankan      html  css  js  c++  java
  • SGU179 Brackets light

    179. Brackets light

    time limit per test: 0.25 sec. 
    memory limit per test: 131072 KB
    input: standard 
    output: standard
    There is a correct brackets sequence. It's length doesn't exceed 10000 symbols. 
    Your task is to find next (in lexicographic order) correct brackets sequence with the same length. You may assume that '(' < ')'.
    Input
    The first line of the input contains correct brackets sequence. There are only '(' and ')' symbols in the input.
    Output
    Write sought sequence in the single line of the output or 'No solution' if solution doesn't exist.
    Sample test(s)
    Input
    (())()
    Output
    ()(())
    题目大意:给你一个括号序列,规定(小于),求当前括号序列的下一个字典序的合法的括号序列.
    分析:比较麻烦的是要求合法.生成下一个字典序的括号序列可以用类似生成下一个全排列的思想:每次从后往前找第一个单调上升的位置,那么后面的就都是单调下降的了.把这个位置的数和它前面的那一个数互换,再把它后面的所有数翻转,这就是具体的思想.那么如何满足合法的要求呢?不断地求下一个序列,直到满足要求为止.那么这样就有一个问题了,怎么判断一个序列一定都够变成有解的呢?找特征!把不能满足要求的序列打个表,就可以发现如果初始序列长成这样:()()()(),那么是无解的,剩下的情况全都有解.
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    char s[10010];
    int len, cnt;
    bool flag = false;
    
    void update()
    {
        for (int i = len; i >= 1; i--)
            if (s[i] > s[i - 1])
            {
                swap(s[i], s[i - 1]);
                reverse(s + i + 1, s + len + 1);
                break;
            }
    }
    
    bool check()
    {
        cnt = 0;
        for (int i = 1; i <= len; i++)
        {
            if (s[i] == '(')
                cnt++;
            else
            {
                if (cnt == 0)
                    return false;
                else
                    cnt--;
            }
        }
        if (cnt)
            return false;
        return true;
    }
    
    int main()
    {
        while (scanf("%s", s + 1) != EOF)
        {
            len = strlen(s + 1);
            flag = false;
            for (int i = 1; i <= len; i++)
                if (s[i] == '(' && s[i + 1] != ')')
                {
                    flag = true;
                    break;
                }
            if (!flag)
                puts("No solution");
            else
            {
                while (1)
                {
                    update();
                    if (check())
                        break;
                }
                for (int i = 1; i <= len; i++)
                    printf("%c", s[i]);
                printf("
    ");
            }
        }
    
        return 0;
    }
  • 相关阅读:
    android 中webview的屏幕适配问题
    Mongo Delete-19
    Android开发初体验
    Mybatis: 插件及分页
    紧急寻人:十三岁男孩昨日出走至今未回,大家帮忙扩散寻找!
    iOS 9,为前端世界都带来了些什么?「译」
    修改 Cucumber HTML 报告
    Android多模块混淆的问题
    吴裕雄--天生自然 诗经:村居
    吴裕雄--天生自然 诗经:太虚幻境
  • 原文地址:https://www.cnblogs.com/zbtrs/p/7954784.html
Copyright © 2011-2022 走看看