Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- import java.text.*;
- import java.math.*;
- import java.util.regex.*;
- public class Solution {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int q = in.nextInt(); // number of queries
- for(int a0 = 0; a0 < q; a0++){
- int n = in.nextInt(); // number of cities
- int m = in.nextInt(); // number of roads
- long c_lib = in.nextLong(); // cost to repair library
- long c_road = in.nextLong(); // cost to repair road
- HashMap<String, HashSet<Integer>> graph = new HashMap<String, HashSet<Integer>>(n);
- for(int a1 = 0; a1 < m; a1++){
- int city_1 = in.nextInt();
- int city_2 = in.nextInt();
- addConnection(graph, city_1, city_2);
- addConnection(graph, city_2, city_1);
- }
- boolean fixRoads = true;
- if (c_lib <= c_road) {
- fixRoads = false;
- }
- BigInteger libraryCost = BigInteger.valueOf(c_lib);
- BigInteger roadCost = BigInteger.valueOf(c_road);
- BigInteger totalCost = new BigInteger("0");
- HashSet<Integer> visitedCities = new HashSet<Integer>(n);
- for (Map.Entry<String, HashSet<Integer>> entry : graph.entrySet()) {
- Stack<Integer> searchList = new Stack<Integer>();
- Integer startCity = Integer.valueOf(entry.getKey());
- if (!visitedCities.contains(startCity)) {
- visitedCities.add(startCity);
- totalCost = totalCost.add(libraryCost);
- if (fixRoads) {
- for (Integer nextCity : entry.getValue()) {
- searchList.push(nextCity);
- }
- }
- }
- while(!searchList.empty()) {
- Integer thisCity = searchList.pop();
- if (!visitedCities.contains(thisCity)) {
- visitedCities.add(thisCity);
- totalCost = totalCost.add(roadCost);
- HashSet<Integer> adjacentCities = graph.get(String.valueOf(thisCity));
- for (Integer nextCity : adjacentCities) {
- searchList.push(nextCity);
- }
- }
- }
- }
- BigInteger numLonelyCities = BigInteger.valueOf(n - visitedCities.size());
- totalCost = totalCost.add(numLonelyCities.multiply(libraryCost));
- System.out.println(totalCost);
- }
- }
- private static void addConnection(HashMap<String, HashSet<Integer>> graph, int fromCity, int toCity) {
- HashSet<Integer> adjacentCities = graph.get(String.valueOf(fromCity));
- if(adjacentCities == null) {
- adjacentCities = new HashSet<Integer>();
- graph.put(String.valueOf(fromCity), adjacentCities);
- }
- adjacentCities.add(toCity);
- }
- }
Add Comment
Please, Sign In to add comment