-
Notifications
You must be signed in to change notification settings - Fork 2
/
Road_library.java
53 lines (46 loc) · 1.2 KB
/
Road_library.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package easy;
/*
Road and Libraries
by- Divyanshu Sharma
*/
import java.util.*;
public class Road_library {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
HashMap<Integer, ArrayList<Integer>> cityMap = new HashMap<>();
int n = scan.nextInt();
int m = scan.nextInt();
int libraryCost = scan.nextInt();
int roadCost = scan.nextInt();
for (int i = 1; i <= n; i++) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(i);
cityMap.put(i, list);
}
for (int a1 = 0; a1 < m; a1++) {
int x = scan.nextInt();
int y = scan.nextInt();
ArrayList<Integer> list1 = cityMap.get(x);
ArrayList<Integer> list2 = cityMap.get(y);
if (list1 != list2) {
list1.addAll(list2);
list2.forEach(i -> cityMap.put(i, list1));
}
}
if (libraryCost < roadCost)
System.out.println((long) n * libraryCost);
else {
long cost = 0;
for (ArrayList<Integer> list : cityMap.values()) {
int size = list.size();
if (size > 0) {
cost += libraryCost;
cost += (size - 1) * roadCost;
list.removeIf(i -> true);
}
}
System.out.println(cost);
}
scan.close();
}
}