-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRoads.java
58 lines (45 loc) · 1.54 KB
/
Roads.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
54
55
56
57
58
package day4;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.PriorityQueue;
public class Roads {
long sum = 0;
public long maximumImportance(int n, int[][] roads) {
// n = 5, roads = [[0,3],[2,4],[1,3]]
List<List<Integer>> adj = new ArrayList<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
for (int i = 0; i < n; i++)
adj.add(new ArrayList<>());
for (int[] road : roads) {
adj.get(road[0]).add(road[1]);
adj.get(road[1]).add(road[0]);
}
for (int index = 0; index < n; index++) {
int e = adj.get(index).size();
maxHeap.add(e);
}
HashMap<Integer, Integer> map = new HashMap<>();
boolean vis[] = new boolean[n];
int k = n;
while (maxHeap.size() > 0) {
map.put(k--, maxHeap.poll());
}
return dfs(0, map, adj, vis);
}
private long dfs(int i, HashMap<Integer, Integer> map, List<List<Integer>> adj, boolean[] vis) {
vis[i] = true;
for (int j = 0; j < adj.get(i).size(); j++) {
int element = adj.get(i).get(j);
int weight = map.get(element);
if (!vis[element]) {
sum = +dfs(adj.get(i).get(j), map, adj, vis);
}
}
return 0;
}
public static void main(String[] args) {
Roads roads = new Roads();
roads.maximumImportance(5, new int[][] { { 0, 3 }, { 2, 4 }, { 1, 3 } });
}
}