I recognised that it was a disjoint data structure...
I guess I got TLE because I used an array indexes instead of pointers, and forgot to use the rank optimisation.
Just wondering what were the values on N for each test case?

I'll be posting solutions over this weekend. I am super busy with assignments and exams. I will say that the intended solution for this problem was Union Find. The link antybash provided is a good read. I'll explain the details in the solutions (and release the testdata).