Guest User

Untitled

a guest
Nov 21st, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.12 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6.  
  7. public class Solution {
  8.  
  9. public static void main(String[] args) {
  10. Scanner in = new Scanner(System.in);
  11. int q = in.nextInt(); // number of queries
  12. for(int a0 = 0; a0 < q; a0++){
  13.  
  14. int n = in.nextInt(); // number of cities
  15. int m = in.nextInt(); // number of roads
  16. long c_lib = in.nextLong(); // cost to repair library
  17. long c_road = in.nextLong(); // cost to repair road
  18. HashMap<String, HashSet<Integer>> graph = new HashMap<String, HashSet<Integer>>(n);
  19. for(int a1 = 0; a1 < m; a1++){
  20. int city_1 = in.nextInt();
  21. int city_2 = in.nextInt();
  22. addConnection(graph, city_1, city_2);
  23. addConnection(graph, city_2, city_1);
  24. }
  25.  
  26. boolean fixRoads = true;
  27. if (c_lib <= c_road) {
  28. fixRoads = false;
  29. }
  30.  
  31. BigInteger libraryCost = BigInteger.valueOf(c_lib);
  32. BigInteger roadCost = BigInteger.valueOf(c_road);
  33. BigInteger totalCost = new BigInteger("0");
  34.  
  35. HashSet<Integer> visitedCities = new HashSet<Integer>(n);
  36.  
  37. for (Map.Entry<String, HashSet<Integer>> entry : graph.entrySet()) {
  38. Stack<Integer> searchList = new Stack<Integer>();
  39. Integer startCity = Integer.valueOf(entry.getKey());
  40. if (!visitedCities.contains(startCity)) {
  41. visitedCities.add(startCity);
  42. totalCost = totalCost.add(libraryCost);
  43. if (fixRoads) {
  44. for (Integer nextCity : entry.getValue()) {
  45. searchList.push(nextCity);
  46. }
  47. }
  48. }
  49. while(!searchList.empty()) {
  50. Integer thisCity = searchList.pop();
  51. if (!visitedCities.contains(thisCity)) {
  52. visitedCities.add(thisCity);
  53. totalCost = totalCost.add(roadCost);
  54. HashSet<Integer> adjacentCities = graph.get(String.valueOf(thisCity));
  55. for (Integer nextCity : adjacentCities) {
  56. searchList.push(nextCity);
  57. }
  58. }
  59. }
  60. }
  61.  
  62. BigInteger numLonelyCities = BigInteger.valueOf(n - visitedCities.size());
  63. totalCost = totalCost.add(numLonelyCities.multiply(libraryCost));
  64.  
  65. System.out.println(totalCost);
  66. }
  67. }
  68.  
  69. private static void addConnection(HashMap<String, HashSet<Integer>> graph, int fromCity, int toCity) {
  70. HashSet<Integer> adjacentCities = graph.get(String.valueOf(fromCity));
  71. if(adjacentCities == null) {
  72. adjacentCities = new HashSet<Integer>();
  73. graph.put(String.valueOf(fromCity), adjacentCities);
  74. }
  75. adjacentCities.add(toCity);
  76. }
  77. }
Add Comment
Please, Sign In to add comment