Thursday 10 March 2016

c++ - Code running fine on my system but segmentation fault on HackerRank submission

I'm doing a coding problem on hackerrank and my code is running successfully on my system but giving segmentation fault while submitting the solution. Please help me out. Have stuck for hours in it. But not able to find the issue.





HackerRank Question:
https://www.hackerrank.com/challenges/torque-and-development




This is my code:



#include 

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 arr[],bool visited[],int node,int &numOfNodes)
{
int i,j;
for(i=0;i {
if(visited[arr[node][i] ] == false )
{
visited[arr[node][i] ] = true ;
dfs(arr,visited,arr[node][i],numOfNodes);

}

}
numOfNodes ++ ;
}

int minCost(vector 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 arr[n];
bool visited[n];
initialize(visited);


for(i=0;i {
scanf("%d %d",&u,&v);
arr[u].push_back(v);
arr[v].push_back(u);
}
cout< }
}



Sample Input:



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


Sample Output:




4
12


Error on Hackerrank:




GDB trace:



Reading symbols from solution...done.




[New LWP 14235]



Core was generated by `solution'.



Program terminated with signal SIGSEGV, Segmentation fault.



/#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(std::forward<_Args>(__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) at /usr/include/c++/6/bits/alloc_traits.h:455



/#2 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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...