C ++匹配支架解决方案

时间:2018-10-25 07:35:54

标签: c++

我为此处链接的问题编写了此代码。 https://www.codechef.com/ZCOPRAC/problems/ZCO12001

即使我使用他们提到的示例输入来运行我的代码,当我在他们的网站上提交我的代码时,我也会得到WA。

#include <iostream> 

int main() {
    int n;
    std::cin >> n;
    int arr[n];
    for (int i = 0; i <n ;++i) {
        std::cin >> arr[i];
    }
    int c_depth , max_depth = 0 , max_pos;

    for (int i = 0; i < n; ++i) {
        if (arr[i] == 1) {
            ++c_depth;
            if (c_depth > max_depth) {
                max_depth = c_depth;
                max_pos = i+1;
            }

        }
        else {
            --c_depth;
        }
    }
    int a_long = 0,max_long = 0,max_long_pos = 0,two_count = 0,c_long = 0;
    for (int i = 0;i < n; ++i) {
        if (arr[i] == 1) {
            a_long += 2;
            two_count += 1;
        }
        else if (arr[i] == 2){
            a_long -= 1;
            two_count -= 1;
        }
        if (two_count == 0) {
            c_long = a_long * 2;
            if (c_long > max_long) {
                max_long  = c_long;
                max_long_pos = i+1;
            }
            c_long = 0;
            a_long = 0;
        }
    }
    max_long_pos = (max_long_pos - max_long) + 1;
    std::cout << max_depth << " " << max_pos << " " << max_long << " "<< max_long_pos;
    std::cout << "\n";
    return 0;

}

对于这个问题,我使用输入的每个数字作为计数器,期望要输入多少个二进制数字。查找深度的代码可以很好地工作,但是寻找最长匹配括号的目的是根据前面提到的计数对输入进行划分。

编辑: 我的一些变量未初始化n。将它们全部初始化为0可以解决问题

1 个答案:

答案 0 :(得分:1)

有一个简单的算法可以很容易地解决您的问题。只需使用堆栈(C ++的STL库有效地实现了堆栈)。对于Evere开放式括号'(',推入堆栈,对于每个闭合的括号,从堆栈弹出。如果末尾的堆栈为空,则序列有效,如果为空,则我们看到了一个)括号;如果不为空,则我们什么也没看到,这是不匹配的。对于嵌套深度,您可以简单地保留变量current_nesting depths=0total_nesting_depth=0。对每个'(',您连续看到的')保持current_nesting深度递增,直到到达')'。然后更新total_nesting_depth=max(total_nesting_depth,current_nesting depths)和刷新current_nesting depths=0并重做此过程,直到字符串结尾。很抱歉回答很快。稍后,我将查看您的代码,看看是否能找到您出错的地方。

相关问题