Quote:
When I debug the code I'm getting runtime error bcz of these 2 lines-ans[a]++ and ans[b]++.
Try
ans[a-1]++;
ans[b-1]++;
In C++, arrays and vectors are 0 based: a vector of size n goes from 0 to n-1.
Nodes in your graph goes from 1 to n.
Beware, here, n is number of nodes, not number of edges.