-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path107. MinimumWeightCycle.java
More file actions
107 lines (77 loc) · 2.56 KB
/
107. MinimumWeightCycle.java
File metadata and controls
107 lines (77 loc) · 2.56 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
class Pair implements Comparable<Pair> {
int node, weight;
Pair(int node, int weight) {
this.node = node;
this.weight = weight;
}
static Pair of(int node, int weight) {
return new Pair(node, weight);
}
@Override
public int hashCode() {
return this.node * 31 + this.weight;
}
@Override
public boolean equals(Object o) {
if(o == null) return false;
if(!(o instanceof Pair)) return false;
Pair p = (Pair)o;
return this.node == p.node && this.weight == p.weight;
}
@Override
public int compareTo(Pair p) {
return this.weight - p.weight;
}
}
class Solution {
private int dijkstra(int src, int dest, int V, List<Set<Pair>> adj) {
int dist[] = new int[V];
int MAX = 100000000;
Arrays.fill(dist, MAX);
dist[src] = 0;
PriorityQueue<Pair> pq = new PriorityQueue<>();
pq.add(Pair.of(src, 0));
while(!pq.isEmpty()) {
Pair p = pq.poll();
for(Pair nei : adj.get(p.node)) {
if(dist[nei.node] > dist[p.node] + nei.weight) {
dist[nei.node] = dist[p.node] + nei.weight;
pq.add(Pair.of(nei.node, dist[nei.node]));
}
}
}
return dist[dest];
}
public int findMinCycle(int V, int[][] edges) {
// code here
List<Set<Pair>> adj = new ArrayList<>();
for(int i=0; i<V; i++) {
adj.add(new HashSet<>());
}
for(int edge[] : edges) {
int u = edge[0];
int v = edge[1];
int w = edge[2];
adj.get(u).add(Pair.of(v, w));
adj.get(v).add(Pair.of(u, w));
}
int ans = Integer.MAX_VALUE;
// Remove each edge and check the min weight of cycle
for(int edge[] : edges) {
int u = edge[0];
int v = edge[1];
int w = edge[2];
// Remove edge
adj.get(u).remove(Pair.of(v, w));
adj.get(v).remove(Pair.of(u, w));
int minDist = dijkstra(u, v, V, adj);
if(minDist + w < ans) {
ans = minDist + w;
}
// Add edge back
adj.get(u).add(Pair.of(v, w));
adj.get(v).add(Pair.of(u, w));
}
return ans;
}
};