-
Notifications
You must be signed in to change notification settings - Fork 0
/
杭电 1874 AC代码JAVA B-F实现
98 lines (69 loc) · 1.7 KB
/
杭电 1874 AC代码JAVA B-F实现
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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main{
static final int infinity=100000;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
int n=in.nextInt();
int m=in.nextInt();
int dis[] = new int[n];
boolean used[] = new boolean[n];
int graph[][] = new int[n][n];
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(i==j) {
graph[i][j] =0;
}else {
graph[i][j] = infinity;
}
}
}
for(int i=0;i<m;i++) {
int r=in.nextInt();
int c=in.nextInt();
int value = in.nextInt();
if(value<graph[r][c])
graph[r][c] = graph[c][r]= value;
}
int start=in.nextInt();
int end = in.nextInt();
for(int i=0;i<n;i++) {
dis[i] = i==start?0:infinity;
}
Bellman_Ford(dis,graph,used,end,start);
}
in.close();
}
public static void Bellman_Ford(int dis[],int graph[][],boolean used[],int end,int start) {
dis[start]=0;
for(int count=1;count<=dis.length-1;count++) {
for(int k=0;k<graph.length;k++) {
for(int i=0;i<graph.length;i++) {
if(graph[k][i]!=infinity) {
if(dis[i]>dis[k]+graph[k][i]) {
dis[i]=dis[k]+graph[k][i];
}
}
}
}
}
//还少了对于负权回路的判断,下面补充上了
for(int i=0;i<dis.length;i++) {
for(int j=0;j<dis.length;j++) {
if(graph[i][j]!=infinity) {
if(dis[j]>dis[i]+graph[i][j]) {
System.out.println("存在负环");
}
}
}
}
if(dis[end]!=infinity) {
System.out.println(dis[end]);
}else {
System.out.println(-1);
}
}
}