I have implemented this using disjoint set. I united all x and y as given in question. Then for each city I called its superparent and found what is the size of that component.
AS many cities may have same super parent so I used set. If a compnent has 4 cities then
for i=1 to 4
{cost=min(cost,(Ai +B(n-i)));}
total ans+=cost.
I need to minimize my cost function which is either build road or temple. If a tample is build I can reduce on e road or vice versa.
sample cases passed and 1 final test case also.