我正在对hackerrank进行编码问题,我的代码在我的系统上成功运行,但在提交解决方案时出现了分段错误 . 请帮帮我 . 已经坚持了几个小时 . 但无法找到问题 .
HackerRank问题:https://www.hackerrank.com/challenges/torque-and-development
这是我的代码:
#include <bits/stdc++.h>
using namespace std;
int n,m,cRoad,cLib;
void initialize(bool visited[])
{
int i ;
for(i=0;i<=n;i++)
{
visited[i] = false ;
}
}
void dfs(vector <int> arr[],bool visited[],int node,int &numOfNodes)
{
int i,j;
for(i=0;i<arr[node].size();i++)
{
if(visited[arr[node][i] ] == false )
{
visited[arr[node][i] ] = true ;
dfs(arr,visited,arr[node][i],numOfNodes);
}
}
numOfNodes ++ ;
}
int minCost(vector <int> arr[],bool visited[])
{
int cost = 0;
int i , connectedComponents =0;
if(cLib < cRoad)
return (n * cLib);
else
{
for(i=1;i<=n;i++)
{
int numOfNodes = 0 ;
if(visited[i]==false)
{
dfs(arr,visited,i,numOfNodes);
connectedComponents++;
cost += (numOfNodes - 1 ) * cRoad + cLib ;
}
}
return cost ;
}
}
int main()
{
int q,u,v,i,j;
scanf("%d",&q);
while(q--)
{
scanf("%d %d %d %d",&n,&m,&cLib ,&cRoad);
vector <int> arr[n];
bool visited[n];
initialize(visited);
for(i=0;i<m;i++)
{
scanf("%d %d",&u,&v);
arr[u].push_back(v);
arr[v].push_back(u);
}
cout<<minCost(arr,visited);
}
}
样本输入:
2
3 3 2 1
1 2
3 1
2 3
6 6 2 5
1 3
3 4
2 4
1 2
2 3
5 6
样本输出:
4
12
Hackerrank出错:
GDB跟踪:从解决方案中读取符号...完成 . [新LWP 14235]核心由“解决方案”生成 . 程序以信号SIGSEGV,分段故障终止 . /#0 0x00000000004009d9 in gnu_cxx :: new_allocator :: construct(this = 0x7ffdbd2b9738, p = 0x1)at / usr / include / c /6/ext/new_allocator.h:120 120 {:: new((void *)__ p) _up(标准::向前<_args>(参数)...); } /#0 0x00000000004009d9 in gnu_cxx :: new_allocator :: construct(this = 0x7ffdbd2b9738, p = 0x1)at / usr / include / c /6/ext/new_allocator.h:120 /#1 std :: allocator_traits> :: construct (a = ..., p = 0x1)/ usr / include / c /6/bits/alloc_traits.h:455 / #std :: vector> :: push_back( x = @ 0x7ffdbd2b9754:1,this = 0x7ffdbd2b9738 )at / usr / include / c /6/bits/stl_vector.h:918 /#3 main()at solution.cc:76
2 回答
我弄错了 . 我做了一些非常小的错误,比如声明大小为n的数组,但我应该声明它的大小为n 1 .
如果您提供了hackerrank分配或记录了您的代码或命名变量,而不是q,u,v,i,j,那么理解代码会更容易 . 从我看到你正在尝试
哪个应该初始化数组 . 但是,您正在使用静态数组并尝试动态初始化它 . 因此,您应该使用动态数组(动态分配内存),或者更确切地说使用足够的固定数组,因为它在竞争性编程中很常见,或者使用容器,例如vector,它封装了所有动态内存管理 .
我还在你的代码中看到了各种循环:
那里可能有一个bug . 我会在整个程序中使用0索引1索引(有些人实际上在竞争性编程中使用1) .
如果使用-Wall -pedantic标志编译代码,则会收到以下警告:
你得到分段错误的原因是你要走出数组边界 . 拥有3个元素的数组,并且您尝试在索引3(这是第4个元素)访问它 . 它可以在您的PC上成功运行,因为访问(之前)数组后面的内存将产生未定义的行为 .
顺便说一句,最好在尽可能晚的时候声明变量,在你要使用它们的地方 . 在函数的求求时不需要声明i(循环控制变量) . 最好只在for循环中使用它,这样它就不会超出范围 .