C++Matching Brackets 2解决方案不起作用

C++ Matching Brackets 2 Solution not working

本文关键字:不起作用 解决方案 Brackets C++Matching      更新时间:2023-10-16

这个问题与我在这里解决的另一个问题类似,但它给了我一个错误的答案,尽管算法适用于示例案例。这次我已经初始化了所有的变量,它适用于我以前算法的修改版本。

#include <iostream> 
int main() {
int n;
std::cin >> n;
int arr[n];
for (int i = 0; i <n ;++i) {
std::cin >> arr[i];
}
int four_count = 0, two_count = 0, three_long=0, one_long = 0 , max1_long = 0 ,max3_long = 0,a_depth = 0,max_depth = 0;
for (int i = 0; i < n; ++i) {
if (arr[i] == 3) {
if (arr[i+1] == 1) {
++a_depth;
if (a_depth > max_depth) {
max_depth = a_depth;
} 
}
++four_count;
three_long += 2; 
}
if (arr[i] == 1) {
if (arr[i+1] == 3) {
++a_depth;
if (a_depth > max_depth) {
max_depth = a_depth;
} 
}
++two_count;
one_long += 2 ; 
}
if (arr[i] == 2) {
if (arr[i+1] == 4 && i < n-1) {
--a_depth;
}
--two_count;  
}
if (arr[i] == 4) {
if (arr[i+1] == 2 && i < n-1){
--a_depth;
}
--four_count;
}
if (four_count == 0 && two_count == 0) {
if (three_long >= one_long) {
if (three_long > max3_long) {
max3_long = three_long+one_long;
}
three_long = 0;
one_long = 0; 
}
else {
if (one_long > max1_long) {
max1_long = one_long+three_long;
}
one_long = 0;
three_long = 0;
}
}
} 
std::cout << max_depth*2 << " " << max1_long << " " << max3_long;
std::cout << "n";
return 0;
}

以下是问题的链接:

https://www.codechef.com/ZCOPRAC/problems/ZCO12003

在下面的代码中:

for (int i = 0; i < n; ++i) {
if (arr[i] == 3) {
if (arr[i+1] == 1) {

i到达n-1时,arr[i+1]变为arr[n],导致越界内存访问,这将导致未定义的行为。

假设n等于5。这意味着数组arr具有最大索引4,因为第一个索引是0

在你的循环

for (int i = 0; i < n; ++i)
{ if (arr[i] == 3) {
if (arr[i+1] == 1) {

在某个时刻,i变成n-1,所以i == 4,然后你尝试arr[i+1],意思是arr[5],这是越界的。

请注意,在对p.W帖子的评论中,您尝试了if (arr[i+1] == 1 && i < n-1)来修复此问题。这不会起作用,因为还有一个arr[i+1]正在执行。你可以通过使用来解决这个问题

if(i < n-1) { 
if(arr[i+1]) {

但这意味着你的ifs会嵌套得更深。你可能应该重新思考你解决给定问题的方法。

编辑:你确定你指的是++i而不是i++吗?