C++Matching Brackets 2解决方案不起作用
C++ Matching Brackets 2 Solution not working
这个问题与我在这里解决的另一个问题类似,但它给了我一个错误的答案,尽管算法适用于示例案例。这次我已经初始化了所有的变量,它适用于我以前算法的修改版本。
#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++
吗?
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- C++Matching Brackets 2解决方案不起作用
- 为什么这段代码不起作用,我该如何解决?
- N-queen问题:无法弄清楚为什么我的解决方案不起作用
- EOF有更安全的替代方案吗?它在我的情况下不起作用
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 在qt QFileDialog中设置后缀在linux中不起作用,如何解决?
- C++:传递临时值不起作用,如何解决?
- 为什么针对给定挑战的此解决方案不起作用?
- 解决方案在两个日期之间的天数内不起作用
- VS为我提供了对构造函数的另一个解决方案,但我想知道为什么我的工作不起作用
- C++迭代时删除列表成员:标准解决方案不起作用
- LeetCode TwoSum解决方案不起作用
- Strchr不起作用,或者我需要一个替代方案来检查给定字符串中的任何字符是否是另一个字符串的一部分
- C# COM-Interop dll for C++ COM dll 在 2 个解决方案之间不起作用
- RUSAGE_THREAD不起作用,正在寻找解决方案/替代方案
- Qt4,QPainterPath的直接分配不起作用(未解决的外部)