import
java.util.*;
class
Graph {
private
int
V;
private
List<List<iPair> > adj;
public
Graph(
int
V)
{
this
.V = V;
adj =
new
ArrayList<>();
for
(
int
i =
0
; i < V; i++) {
adj.add(
new
ArrayList<>());
}
}
public
void
addEdge(
int
u,
int
v,
int
w)
{
adj.get(v).add(
new
iPair(u, w));
}
public
void
shortestPath(
int
src, List<Integer> dist)
{
PriorityQueue<iPair> pq =
new
PriorityQueue<>(
Comparator.comparingInt(ip -> ip.first));
pq.add(
new
iPair(
0
, src));
dist.set(src,
0
);
while
(!pq.isEmpty()) {
int
u = pq.poll().second;
for
(iPair i : adj.get(u)) {
int
v = i.first;
int
weight = i.second;
if
(dist.get(v) > dist.get(u) + weight) {
dist.set(v, dist.get(u) + weight);
pq.add(
new
iPair(dist.get(v), v));
}
}
}
}
}
class
iPair {
int
first, second;
public
iPair(
int
first,
int
second)
{
this
.first = first;
this
.second = second;
}
}
class
Main {
static
int
INF =
0x3f3f3f3f
;
public
static
int
minPath(
int
V,
int
src,
int
des,
Graph g, Graph r)
{
List<Integer> dist
=
new
ArrayList<>(Collections.nCopies(V, INF));
List<Integer> dist2
=
new
ArrayList<>(Collections.nCopies(V, INF));
List<Integer> dist3
=
new
ArrayList<>(Collections.nCopies(V, INF));
List<Integer> dist4
=
new
ArrayList<>(Collections.nCopies(V, INF));
g.shortestPath(src, dist);
g.shortestPath(des, dist2);
r.shortestPath(src, dist3);
r.shortestPath(des, dist4);
int
ans = Integer.MAX_VALUE;
for
(
int
i =
0
; i < V; i++) {
if
(i != des && i != src) {
ans = Math.min(
ans, dist.get(i) + dist2.get(i)
+ dist3.get(i) + dist4.get(i));
}
}
return
ans;
}
public
static
void
main(String[] args)
{
int
V =
5
, src =
0
, des =
1
;
Graph g =
new
Graph(V);
Graph r =
new
Graph(V);
g.addEdge(
0
,
2
,
1
);
g.addEdge(
0
,
4
,
5
);
g.addEdge(
1
,
4
,
1
);
g.addEdge(
2
,
0
,
10
);
g.addEdge(
2
,
3
,
5
);
g.addEdge(
3
,
1
,
1
);
g.addEdge(
4
,
0
,
5
);
g.addEdge(
4
,
2
,
100
);
g.addEdge(
4
,
3
,
5
);
r.addEdge(
2
,
0
,
1
);
r.addEdge(
4
,
0
,
5
);
r.addEdge(
4
,
1
,
1
);
r.addEdge(
0
,
2
,
10
);
r.addEdge(
3
,
2
,
5
);
r.addEdge(
1
,
3
,
1
);
r.addEdge(
0
,
4
,
5
);
r.addEdge(
2
,
4
,
100
);
r.addEdge(
3
,
4
,
5
);
System.out.println(minPath(V, src, des, g, r));
}
}