why i am getting sigsegv in hackerearth easy problem?

Problem Link-https://www.hackerearth.com/practice/algorithms/graphs/graph-representation/practice-problems/algorithm/monk-in-the-real-estate/

Solution->I know i am accessing something wrong,Please suggest me changes.

#include
#include
#define li long int
using namespace std;
vector< vector > graph(10001);

int main()

{
li t=0;

cin>>t;

while(t!=0)

{

    li x=0;li y=0;

 li n;cin>>n;

li ans=0;

for(int i=1;i<=n;i++)

{

    cin>>x;

    cin>>y;
    
    if(graph[x][y]==0 )

   {

        graph[x].push_back(y);
        graph[y].push_back(x);

   }

}

for(int i=1;i<=n;i++)

{

       ans=ans+graph[i].size();

}

cout<<ans<<endl;

graph.clear();

t--;}

return 0;

}

1 Like

if(graph[x][y]==0)
You cannot access something that does not exist. g[x] exists but it is initially empty, hence you cannot access g[x][y].

Also please wrap your code in a <pre> block or provide a link to it, it is quite hard to read.

1 Like

but im getting error after entering 1 x and y(not after loop(i=1 to n)) why?

then i have to use array for already visited vertices?

There is no question of visiting vertices. You are simply taking the edges as input. You do not need the if statement there.

You are checking graph [x][y] even before taking any input in it. So it is not present there, that is why it is giving sigsegv

if input is 1,1 1,1 1,1 then why i need to insert 1,1 three times? basically im asking for how to check if this edges is already existed? please help me

To check if edge already exists you can use a map (or simply an array if limits allow) for this.

You will not usually need to do that because problems do not provide duplicate edges as input (what’s the point?). But if you are facing such a situation, use std::set instead of std::vector to store the neighbours of a vertex. A set does not allow duplicate elements, so even if you insert the same value multiple times, the set will store only one copy.

nice…i will

if i use list?