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;
    }
  • 相关阅读:
    jquery操作checkbox方法(全选、全不选、至少选择一个、选择值/文本)
    如何设置tomcat服务器编码为utf-8编码
    eclipse创建文件package,source folder和folder区别及相互转换
    git常用命令
    Java程序员最常犯的错误盘点之Top 10
    最有用的java面试题
    Java面试进阶部分集合
    Java面试基础部分合集
    python作为计算器(数学用法)
    phthon入门介绍
  • 原文地址:https://www.cnblogs.com/zbtrs/p/7954784.html
Copyright © 2011-2022 走看看