【发布时间】:2018-09-10 20:57:22
【问题描述】:
这是我要解决的问题,在最后一部分中,我尝试将所有问题放在一起。
我能够通过 11 个测试用例,但提交抱怨使用非常大的 n 和 m 的测试用例出现分段错误。 https://www.hackerrank.com/challenges/crush/problem
简而言之,这个问题需要根据查询向量中的元素在 init_array 中添加元素。
这是我解决问题的代码。注意:我将数据类型“int”更改为“long unsigned int”,因为一些输出结果 > 32,767。
// Complete the arrayManipulation function below.
unsigned long int arrayManipulation(unsigned long int n,
vector<vector<unsigned long int>> queries) {
unsigned long int init_array[n+1]={0};
unsigned long int max = init_array[0];
for(unsigned long int i=0; i<queries.size();++i)//m
{
for(unsigned long int j=queries.at(i).at(0); j<=queries.at(i).at(1); ++j)
{
init_array[j-1]+=queries.at(i).at(2);
if(init_array[j-1] > max)
max = init_array[j-1];
}
}
return max;
}
我的代码失败的测试用例之一:
输入:
10000000 100000
1449932 7787270 51019
912262 3955862 23367
720355 6300425 44414
4058050 4109759 82390
630827 1992079 83163
4595878 6289869 37323
6117634 7440834 53818
3577465 5755968 89549
611287 4779893 49153
6118450 8290500 9271
6328120 8594121 59202
695492 2549982 71464
1366758 8035211 8170
5476516 5979625 82571
2378367 9984946 13398
4580824 5961530 19618
3214809 9215205 60451
1487128 5985376 37916
574925 6267020 65554
2340430 4901822 56053
749701 1229941 50173
1925432 3125256 16506
2476995 6413072 83263
972971 2937594 59778
3351338 3520166 61075
1829219 7249916 41898
1044424 7269534 73058
4729986 9546151 60185
121075 8284254 27205
2449808 2461505 29026
5727557 7422213 75318
988738 1369164 17102
7105244 7782235 94096
719829 7104859 67066
2580989 6756346 18403
4006261 8042064 47622
600315 3792146 8397
1038483 6373373 54547
3633559 9322736 91973
4288895 7160764 69829
1711107 8106142 97386
281460 5216196 66549
2321439 6898562 65136
5992658 9426297 1316
2007285 8576077 57661
2565701 4510
>
预期输出:
2484930878
此代码适用于小的 n 和 m,分别为 ~ 4000 和 30000。为什么我会看到大 n 或 m 的分段错误问题?
上述算法的复杂度是多少?平均为 O(m log n)?对于每个“m”次迭代,我只在“n”个索引的子集上运行第二个循环。
【问题讨论】:
-
可能是堆栈溢出。尝试使用
std::vector而不是数组。 -
"unsigned long int init_array[n+1]={0}" 在 C++ 中没有 C 可变长度数组这种东西
-
无关:
vector<vector<unsigned long int>>由于空间局部性差,速度可能会慢得惊人。如果内部维度的大小已知,您可能会从vector<array<unsigned long int, SIZE>>中找到性能改进
标签: c++ arrays segmentation-fault