Passing all test cases except 3, which are giving TLE


import java.util.*;

public class Main
{
public static void main(String [] args)
{
Scanner scn = new Scanner(System.in);

    int T = scn.nextInt();
    
    while(T-- != 0)
    {
        int n, m;
        long a, b;
        
        //no. of cities
        n = scn.nextInt();
        
        //no. of temples
        m = scn.nextInt();
        
        //cost of building a temple
        a = scn.nextInt();
        
        //cost of repairing 
        //existing road
        b = scn.nextInt();
        
        
        //graph
        HashMap <Integer, HashSet<Integer>> graph = new HashMap <> ();
        
        for(int i = 1; i<=n; i++)
            graph.put(i, new HashSet <Integer> ());
            
        for(int i = 1; i<=m; i++)
        {
            int x = scn.nextInt();
            int y = scn.nextInt();
            
            graph.get(x).add(y);
            graph.get(y).add(x);
        }
        
        
        
        System.out.println(getMinCost(graph,a,b));
        
    }
    
}



public static long getMinCost(HashMap <Integer, HashSet<Integer>> graph, long a, long b)
{
    Queue <Integer> q = new LinkedList <> ();
    
    long finalAns = 0;
    int ans;
    
    HashMap <Integer, Boolean> visited = new HashMap <> ();
    
    for(Integer key : graph.keySet())
    {
        if(visited.containsKey(key))
            continue;
        
        
        //applying bfs
        q.add(key);
        ans = 0;
        
        while(!q.isEmpty())
        {
            int rp = q.remove();
            
            if(visited.containsKey(rp))
                continue;
                
            visited.put(rp,true);
            ans++;
            
            for(Integer nbr : graph.get(rp))
            {
                if(!visited.containsKey(nbr))
                    q.add(nbr);
            }
            
        }
        
        long templeOnly = ans*a;
        long roadAndOneTemple = (ans-1)*b + a;
        
        finalAns += Math.min(templeOnly, roadAndOneTemple);
    }
    
    return finalAns;
}

}