图论part09
dijkstra(堆优化版)精讲(不熟悉)
代码随想录链接
题目链接


import java.util.*
;
class Edge {
int
to
;
int val;
Edge(
int
to
,
int val) {
this.
to =
to
;
this.val = val;
}
}
class MyComparison
implements Comparator<
Pair<
Integer
, Integer>
> {
@Override
public
int compare(Pair<
Integer
, Integer> lhs, Pair<
Integer
, Integer> rhs) {
return Integer.compare(lhs.second, rhs.second)
;
}
}
class Pair<
U
, V> {
public
final U first;
public
final V second;
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
}
public
class Main {
public
static
void main(String[] args) {
Scanner scanner =
new Scanner(System.in)
;
int n = scanner.nextInt(
)
;
int m = scanner.nextInt(
)
;
List<
List<
Edge>
> grid =
new ArrayList<
>(n + 1
)
;
for (
int i = 0
; i <= n; i++
) {
grid.add(
new ArrayList<
>(
)
)
;
}
for (
int i = 0
; i < m; i++
) {
int p1 = scanner.nextInt(
)
;
int p2 = scanner.nextInt(
)
;
int val = scanner.nextInt(
)
;
grid.get(p1).add(
new Edge(p2, val)
)
;
}
int start = 1
;
int end = n;
int[] minDist =
new
int[n + 1]
;
Arrays.fill(minDist, Integer.MAX_VALUE
)
;
boolean[] visited =
new
boolean[n + 1]
;
PriorityQueue<
Pair<
Integer
, Integer>
> pq =
new PriorityQueue<
>(
new MyComparison(
)
)
;
pq.add(
new Pair<
>(start, 0
)
)
;
minDist[start] = 0
;
while (!pq.isEmpty(
)
) {
Pair<
Integer
, Integer> cur = pq.poll(
)
;
if (visited[cur.first]
)
continue
;
visited[cur.first] = true
;
for (Edge edge : grid.get(cur.first)
) {
if (!visited[edge.
to] && minDist[cur.first] + edge.val < minDist[edge.
to]
) {
minDist[edge.
to] = minDist[cur.first] + edge.val;
pq.add(
new Pair<
>(edge.
to
, minDist[edge.
to]
)
)
;
}
}
}
if (minDist[end] == Integer.MAX_VALUE
) {
System.out.println(-1
)
;
}
else {
System.out.println(minDist[end]
)
;
}
}
}
Bellman_ford 算法精讲(不熟悉)
代码随想录链接
题目链接


代码
import java.util.*
;
public
class Main {
static
class Edge {
int from;
int
to
;
int val;
public Edge(
int from,
int
to
,
int val) {
this.from = from;
this.
to =
to
;
this.val = val;
}
}
public
static
void main(String[] args) {
Scanner sc =
new Scanner(System.in)
;
int n = sc.nextInt(
)
;
int m = sc.nextInt(
)
;
List<
Edge> edges =
new ArrayList<
>(
)
;
for (
int i = 0
; i < m; i++
) {
int from = sc.nextInt(
)
;
int
to = sc.nextInt(
)
;
int val = sc.nextInt(
)
;
edges.add(
new Edge(from,
to
, val)
)
;
}
int[] minDist =
new
int[n + 1]
;
Arrays.fill(minDist, Integer.MAX_VALUE
)
;
minDist[1] = 0
;
for (
int i = 1
; i < n; i++
) {
boolean updated = false
;
for (Edge edge : edges) {
if (minDist[edge.from] != Integer.MAX_VALUE &&
minDist[edge.from] + edge.val < minDist[edge.
to]
) {
minDist[edge.
to] = minDist[edge.from] + edge.val;
updated = true
;
}
}
if (!updated)
break
;
}
if (minDist[n] == Integer.MAX_VALUE
) {
System.out.println("unconnected"
)
;
}
else {
System.out.println(minDist[n]
)
;
}
}
}