Trying to solve 862B about the maximum number of edges one can add to a certain tree so that it's still a bipartite graph. I went with the "let's code everything ourselves" approach and limited myself to C. Here's my code.
I looked at others' submissions and they used similar approaches but almost all of them used the vector class in C++. My code works fine on most tests including ones with n = 100k, running them in <50 ms, but then there's a test where one node has loads of edges and it times out at >2000 ms. Why? Even if you use a vector, the amount of recursive calls should still be the same, which should be the limiting factor here in terms of speed, right? Do I have an infinite loop?
List uses pointers to access adjacent elements. While vector uses indexing just like an array. Due to direct access vector is comparatively much faster as compared to list.
Thanks!
Your insertEdge takes too long finding list's tail. Each call takes O(size) time and if all edges are adjacent to same vertex you spend O(n^2) which is too much. You should either store tail or push front.